# Midnight Docs > Comprehensive documentation for building on Midnight. - [Midnight Docs](/index.md) ## ai-integration Build on Midnight with AI coding assistants that verify generated code against the real compiler and source, so you ship working code, not hallucinations. - [AI integration](/ai-integration.md): Build on Midnight with AI coding assistants that verify generated code against the real compiler and source, so you ship working code, not hallucinations. ### kapa-mcp-server The Kapa MCP server gives AI coding assistants documentation-grounded answers about Midnight directly inside your editor. - [Kapa MCP server](/ai-integration/kapa-mcp-server.md): The Kapa MCP server gives AI coding assistants documentation-grounded answers about Midnight directly inside your editor. ### midnight-expert Midnight Expert is a suite of Claude Code plugins that help you write and review Compact, scaffold DApps, and verify generated code against the real compiler. - [Midnight Expert](/ai-integration/midnight-expert.md): Midnight Expert is a suite of Claude Code plugins that help you write and review Compact, scaffold DApps, and verify generated code against the real compiler. ## api-reference Complete reference for Midnight TypeScript APIs, covering smart contracts, wallets, indexer, and blockchain interactions. - [API reference](/api-reference.md): Complete reference for Midnight TypeScript APIs, covering smart contracts, wallets, indexer, and blockchain interactions. ### compact-runtime @midnight-ntwrk/compact-runtime v0.19.0 - [Compact runtime API](/api-reference/compact-runtime.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ChargedState](/api-reference/compact-runtime/classes/ChargedState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactError](/api-reference/compact-runtime/classes/CompactError.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeBoolean](/api-reference/compact-runtime/classes/CompactTypeBoolean.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeBytes](/api-reference/compact-runtime/classes/CompactTypeBytes.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeCurvePoint](/api-reference/compact-runtime/classes/CompactTypeCurvePoint.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeEnum](/api-reference/compact-runtime/classes/CompactTypeEnum.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeField](/api-reference/compact-runtime/classes/CompactTypeField.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeMerkleTreeDigest](/api-reference/compact-runtime/classes/CompactTypeMerkleTreeDigest.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeMerkleTreePath](/api-reference/compact-runtime/classes/CompactTypeMerkleTreePath.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeMerkleTreePathEntry](/api-reference/compact-runtime/classes/CompactTypeMerkleTreePathEntry.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeOpaqueString](/api-reference/compact-runtime/classes/CompactTypeOpaqueString.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeOpaqueUint8Array](/api-reference/compact-runtime/classes/CompactTypeOpaqueUint8Array.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeUnsignedInteger](/api-reference/compact-runtime/classes/CompactTypeUnsignedInteger.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeVector](/api-reference/compact-runtime/classes/CompactTypeVector.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractInterfaceMismatchError](/api-reference/compact-runtime/classes/ContractInterfaceMismatchError.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractMaintenanceAuthority](/api-reference/compact-runtime/classes/ContractMaintenanceAuthority.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractOperation](/api-reference/compact-runtime/classes/ContractOperation.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractState](/api-reference/compact-runtime/classes/ContractState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CostModel](/api-reference/compact-runtime/classes/CostModel.md): @midnight-ntwrk/compact-runtime v0.19.0 - [QueryContext](/api-reference/compact-runtime/classes/QueryContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [QueryResults](/api-reference/compact-runtime/classes/QueryResults.md): @midnight-ntwrk/compact-runtime v0.19.0 - [StateBoundedMerkleTree](/api-reference/compact-runtime/classes/StateBoundedMerkleTree.md): @midnight-ntwrk/compact-runtime v0.19.0 - [StateMap](/api-reference/compact-runtime/classes/StateMap.md): @midnight-ntwrk/compact-runtime v0.19.0 - [StateValue](/api-reference/compact-runtime/classes/StateValue.md): @midnight-ntwrk/compact-runtime v0.19.0 - [VmResults](/api-reference/compact-runtime/classes/VmResults.md): @midnight-ntwrk/compact-runtime v0.19.0 - [VmStack](/api-reference/compact-runtime/classes/VmStack.md): @midnight-ntwrk/compact-runtime v0.19.0 - [NetworkId](/api-reference/compact-runtime/enumerations/NetworkId.md): @midnight-ntwrk/compact-runtime v0.9.0 - [addField](/api-reference/compact-runtime/functions/addField.md): @midnight-ntwrk/compact-runtime v0.19.0 - [alignedConcat](/api-reference/compact-runtime/functions/alignedConcat.md): @midnight-ntwrk/compact-runtime v0.19.0 - [assert](/api-reference/compact-runtime/functions/assert.md): @midnight-ntwrk/compact-runtime v0.19.0 - [assertDefined](/api-reference/compact-runtime/functions/assertDefined.md): @midnight-ntwrk/compact-runtime v0.19.0 - [assertIsContractAddress](/api-reference/compact-runtime/functions/assertIsContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [assertUndefined](/api-reference/compact-runtime/functions/assertUndefined.md): @midnight-ntwrk/compact-runtime v0.19.0 - [bigIntModFr](/api-reference/compact-runtime/functions/bigIntModFr.md): @midnight-ntwrk/compact-runtime v0.19.0 - [bigIntToValue](/api-reference/compact-runtime/functions/bigIntToValue.md): @midnight-ntwrk/compact-runtime v0.19.0 - [checkProofData](/api-reference/compact-runtime/functions/checkProofData.md): @midnight-ntwrk/compact-runtime v0.9.0 - [checkRuntimeVersion](/api-reference/compact-runtime/functions/checkRuntimeVersion.md): @midnight-ntwrk/compact-runtime v0.19.0 - [coinCommitment](/api-reference/compact-runtime/functions/coinCommitment.md): @midnight-ntwrk/compact-runtime v0.9.0 - [communicationCommitment](/api-reference/compact-runtime/functions/communicationCommitment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [communicationCommitmentRandomness](/api-reference/compact-runtime/functions/communicationCommitmentRandomness.md): @midnight-ntwrk/compact-runtime v0.19.0 - [constructJubjubPoint](/api-reference/compact-runtime/functions/constructJubjubPoint.md): @midnight-ntwrk/compact-runtime v0.19.0 - [constructorContext](/api-reference/compact-runtime/functions/constructorContext.md): @midnight-ntwrk/compact-runtime v0.9.0 - [contractDependencies](/api-reference/compact-runtime/functions/contractDependencies.md): @midnight-ntwrk/compact-runtime v0.19.0 - [convert_bigint_to_Uint8Array](/api-reference/compact-runtime/functions/convert_bigint_to_Uint8Array.md): @midnight-ntwrk/compact-runtime v0.8.1 - [convert_Uint8Array_to_bigint](/api-reference/compact-runtime/functions/convert_Uint8Array_to_bigint.md): @midnight-ntwrk/compact-runtime v0.8.1 - [convertBigintToBytes](/api-reference/compact-runtime/functions/convertBigintToBytes.md): @midnight-ntwrk/compact-runtime v0.19.0 - [convertBytesToField](/api-reference/compact-runtime/functions/convertBytesToField.md): @midnight-ntwrk/compact-runtime v0.19.0 - [convertBytesToUint](/api-reference/compact-runtime/functions/convertBytesToUint.md): @midnight-ntwrk/compact-runtime v0.19.0 - [convertFieldToBytes](/api-reference/compact-runtime/functions/convertFieldToBytes.md): @midnight-ntwrk/compact-runtime v0.16.0 - [convertNumericToJubjubScalar](/api-reference/compact-runtime/functions/convertNumericToJubjubScalar.md): @midnight-ntwrk/compact-runtime v0.19.0 - [copyCircuitContext](/api-reference/compact-runtime/functions/copyCircuitContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createCallContext](/api-reference/compact-runtime/functions/createCallContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createCircuitContext](/api-reference/compact-runtime/functions/createCircuitContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createConstructorContext](/api-reference/compact-runtime/functions/createConstructorContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createInitialQueryContext](/api-reference/compact-runtime/functions/createInitialQueryContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createWitnessContext](/api-reference/compact-runtime/functions/createWitnessContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createZswapInput](/api-reference/compact-runtime/functions/createZswapInput.md): @midnight-ntwrk/compact-runtime v0.19.0 - [createZswapOutput](/api-reference/compact-runtime/functions/createZswapOutput.md): @midnight-ntwrk/compact-runtime v0.19.0 - [crossContractCall](/api-reference/compact-runtime/functions/crossContractCall.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeCoinInfo](/api-reference/compact-runtime/functions/decodeCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [decodeCoinPublicKey](/api-reference/compact-runtime/functions/decodeCoinPublicKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeContractAddress](/api-reference/compact-runtime/functions/decodeContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeQualifiedCoinInfo](/api-reference/compact-runtime/functions/decodeQualifiedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [decodeQualifiedShieldedCoinInfo](/api-reference/compact-runtime/functions/decodeQualifiedShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeRawTokenType](/api-reference/compact-runtime/functions/decodeRawTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeRecipient](/api-reference/compact-runtime/functions/decodeRecipient.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeShieldedCoinInfo](/api-reference/compact-runtime/functions/decodeShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeTokenType](/api-reference/compact-runtime/functions/decodeTokenType.md): @midnight-ntwrk/compact-runtime v0.9.0 - [decodeUserAddress](/api-reference/compact-runtime/functions/decodeUserAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [decodeZswapLocalState](/api-reference/compact-runtime/functions/decodeZswapLocalState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [degradeToTransient](/api-reference/compact-runtime/functions/degradeToTransient.md): @midnight-ntwrk/compact-runtime v0.19.0 - [dummyContractAddress](/api-reference/compact-runtime/functions/dummyContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [dummyUserAddress](/api-reference/compact-runtime/functions/dummyUserAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ecAdd](/api-reference/compact-runtime/functions/ecAdd.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ecMul](/api-reference/compact-runtime/functions/ecMul.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ecMulGenerator](/api-reference/compact-runtime/functions/ecMulGenerator.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ecNeg](/api-reference/compact-runtime/functions/ecNeg.md): @midnight-ntwrk/compact-runtime v0.19.0 - [emptyRunningCost](/api-reference/compact-runtime/functions/emptyRunningCost.md): @midnight-ntwrk/compact-runtime v0.19.0 - [emptyZswapLocalState](/api-reference/compact-runtime/functions/emptyZswapLocalState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeCoinInfo](/api-reference/compact-runtime/functions/encodeCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [encodeCoinPublicKey](/api-reference/compact-runtime/functions/encodeCoinPublicKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeContractAddress](/api-reference/compact-runtime/functions/encodeContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeQualifiedCoinInfo](/api-reference/compact-runtime/functions/encodeQualifiedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [encodeQualifiedShieldedCoinInfo](/api-reference/compact-runtime/functions/encodeQualifiedShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeRawTokenType](/api-reference/compact-runtime/functions/encodeRawTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeRecipient](/api-reference/compact-runtime/functions/encodeRecipient.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeShieldedCoinInfo](/api-reference/compact-runtime/functions/encodeShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeTokenType](/api-reference/compact-runtime/functions/encodeTokenType.md): @midnight-ntwrk/compact-runtime v0.9.0 - [encodeUserAddress](/api-reference/compact-runtime/functions/encodeUserAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [encodeZswapLocalState](/api-reference/compact-runtime/functions/encodeZswapLocalState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [entryPointHash](/api-reference/compact-runtime/functions/entryPointHash.md): @midnight-ntwrk/compact-runtime v0.19.0 - [finalizeCallProofData](/api-reference/compact-runtime/functions/finalizeCallProofData.md): @midnight-ntwrk/compact-runtime v0.19.0 - [fromHex](/api-reference/compact-runtime/functions/fromHex.md): @midnight-ntwrk/compact-runtime v0.19.0 - [hasCoinCommitment](/api-reference/compact-runtime/functions/hasCoinCommitment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [hashToCurve](/api-reference/compact-runtime/functions/hashToCurve.md): @midnight-ntwrk/compact-runtime v0.19.0 - [isContractAddress](/api-reference/compact-runtime/functions/isContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [isEncodedContractAddress](/api-reference/compact-runtime/functions/isEncodedContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [jubjubPointX](/api-reference/compact-runtime/functions/jubjubPointX.md): @midnight-ntwrk/compact-runtime v0.19.0 - [jubjubPointY](/api-reference/compact-runtime/functions/jubjubPointY.md): @midnight-ntwrk/compact-runtime v0.19.0 - [jubjubSampleScalar](/api-reference/compact-runtime/functions/jubjubSampleScalar.md): @midnight-ntwrk/compact-runtime v0.19.0 - [jubjubSchnorrSign](/api-reference/compact-runtime/functions/jubjubSchnorrSign.md): @midnight-ntwrk/compact-runtime v0.19.0 - [jubjubSchnorrVerify](/api-reference/compact-runtime/functions/jubjubSchnorrVerify.md): @midnight-ntwrk/compact-runtime v0.19.0 - [jubjubSchnorrVerifyingKey](/api-reference/compact-runtime/functions/jubjubSchnorrVerifyingKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [keccak256](/api-reference/compact-runtime/functions/keccak256.md): @midnight-ntwrk/compact-runtime v0.19.0 - [leafHash](/api-reference/compact-runtime/functions/leafHash.md): @midnight-ntwrk/compact-runtime v0.19.0 - [maxAlignedSize](/api-reference/compact-runtime/functions/maxAlignedSize.md): @midnight-ntwrk/compact-runtime v0.19.0 - [maxField](/api-reference/compact-runtime/functions/maxField.md): @midnight-ntwrk/compact-runtime v0.19.0 - [mulField](/api-reference/compact-runtime/functions/mulField.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ownPublicKey](/api-reference/compact-runtime/functions/ownPublicKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [persistentCommit](/api-reference/compact-runtime/functions/persistentCommit.md): @midnight-ntwrk/compact-runtime v0.19.0 - [persistentHash](/api-reference/compact-runtime/functions/persistentHash.md): @midnight-ntwrk/compact-runtime v0.19.0 - [proofDataIntoSerializedPreimage](/api-reference/compact-runtime/functions/proofDataIntoSerializedPreimage.md): @midnight-ntwrk/compact-runtime v0.19.0 - [queryLedgerState](/api-reference/compact-runtime/functions/queryLedgerState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [rawTokenType](/api-reference/compact-runtime/functions/rawTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [runProgram](/api-reference/compact-runtime/functions/runProgram.md): @midnight-ntwrk/compact-runtime v0.19.0 - [runtimeCoinCommitment](/api-reference/compact-runtime/functions/runtimeCoinCommitment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [sampleContractAddress](/api-reference/compact-runtime/functions/sampleContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [sampleRawTokenType](/api-reference/compact-runtime/functions/sampleRawTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [sampleSigningKey](/api-reference/compact-runtime/functions/sampleSigningKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [sampleTokenType](/api-reference/compact-runtime/functions/sampleTokenType.md): @midnight-ntwrk/compact-runtime v0.9.0 - [sampleUserAddress](/api-reference/compact-runtime/functions/sampleUserAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1Add](/api-reference/compact-runtime/functions/secp256k1Add.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1BaseAdd](/api-reference/compact-runtime/functions/secp256k1BaseAdd.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1BaseInv](/api-reference/compact-runtime/functions/secp256k1BaseInv.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1BaseMul](/api-reference/compact-runtime/functions/secp256k1BaseMul.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1BaseNeg](/api-reference/compact-runtime/functions/secp256k1BaseNeg.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1BaseSub](/api-reference/compact-runtime/functions/secp256k1BaseSub.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1EcdsaRecover](/api-reference/compact-runtime/functions/secp256k1EcdsaRecover.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1FromProjective](/api-reference/compact-runtime/functions/secp256k1FromProjective.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1Mul](/api-reference/compact-runtime/functions/secp256k1Mul.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1MulGenerator](/api-reference/compact-runtime/functions/secp256k1MulGenerator.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1PointX](/api-reference/compact-runtime/functions/secp256k1PointX.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1PointY](/api-reference/compact-runtime/functions/secp256k1PointY.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1ScalarAdd](/api-reference/compact-runtime/functions/secp256k1ScalarAdd.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1ScalarInv](/api-reference/compact-runtime/functions/secp256k1ScalarInv.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1ScalarMul](/api-reference/compact-runtime/functions/secp256k1ScalarMul.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1ScalarNeg](/api-reference/compact-runtime/functions/secp256k1ScalarNeg.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1ScalarSub](/api-reference/compact-runtime/functions/secp256k1ScalarSub.md): @midnight-ntwrk/compact-runtime v0.19.0 - [secp256k1ToProjective](/api-reference/compact-runtime/functions/secp256k1ToProjective.md): @midnight-ntwrk/compact-runtime v0.19.0 - [signatureVerifyingKey](/api-reference/compact-runtime/functions/signatureVerifyingKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [signData](/api-reference/compact-runtime/functions/signData.md): @midnight-ntwrk/compact-runtime v0.19.0 - [signingKeyFromBip340](/api-reference/compact-runtime/functions/signingKeyFromBip340.md): @midnight-ntwrk/compact-runtime v0.19.0 - [subField](/api-reference/compact-runtime/functions/subField.md): @midnight-ntwrk/compact-runtime v0.19.0 - [toBinaryRepr](/api-reference/compact-runtime/functions/toBinaryRepr.md): @midnight-ntwrk/compact-runtime v0.19.0 - [toHex](/api-reference/compact-runtime/functions/toHex.md): @midnight-ntwrk/compact-runtime v0.19.0 - [tokenType](/api-reference/compact-runtime/functions/tokenType.md): @midnight-ntwrk/compact-runtime v0.9.0 - [transientCommit](/api-reference/compact-runtime/functions/transientCommit.md): @midnight-ntwrk/compact-runtime v0.19.0 - [transientHash](/api-reference/compact-runtime/functions/transientHash.md): @midnight-ntwrk/compact-runtime v0.19.0 - [type_error](/api-reference/compact-runtime/functions/type_error.md): @midnight-ntwrk/compact-runtime v0.9.0 - [typeError](/api-reference/compact-runtime/functions/typeError.md): @midnight-ntwrk/compact-runtime v0.19.0 - [upgradeFromTransient](/api-reference/compact-runtime/functions/upgradeFromTransient.md): @midnight-ntwrk/compact-runtime v0.19.0 - [valueToBigInt](/api-reference/compact-runtime/functions/valueToBigInt.md): @midnight-ntwrk/compact-runtime v0.19.0 - [verifySignature](/api-reference/compact-runtime/functions/verifySignature.md): @midnight-ntwrk/compact-runtime v0.19.0 - [witnessContext](/api-reference/compact-runtime/functions/witnessContext.md): @midnight-ntwrk/compact-runtime v0.9.0 - [globals](/api-reference/compact-runtime/globals.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CallProofData](/api-reference/compact-runtime/interfaces/CallProofData.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CircuitContext](/api-reference/compact-runtime/interfaces/CircuitContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CircuitResults](/api-reference/compact-runtime/interfaces/CircuitResults.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CommunicationCommitmentData](/api-reference/compact-runtime/interfaces/CommunicationCommitmentData.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactType](/api-reference/compact-runtime/interfaces/CompactType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ConstructorContext](/api-reference/compact-runtime/interfaces/ConstructorContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ConstructorResult](/api-reference/compact-runtime/interfaces/ConstructorResult.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractStateProvider](/api-reference/compact-runtime/interfaces/ContractStateProvider.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CurvePoint](/api-reference/compact-runtime/interfaces/CurvePoint.md): @midnight-ntwrk/compact-runtime v0.9.0 - [EncodedCoinInfo](/api-reference/compact-runtime/interfaces/EncodedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [EncodedCoinPublicKey](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EncodedContractAddress](/api-reference/compact-runtime/interfaces/EncodedContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EncodedQualifiedCoinInfo](/api-reference/compact-runtime/interfaces/EncodedQualifiedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [EncodedQualifiedShieldedCoinInfo](/api-reference/compact-runtime/interfaces/EncodedQualifiedShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EncodedRecipient](/api-reference/compact-runtime/interfaces/EncodedRecipient.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EncodedShieldedCoinInfo](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EncodedZswapLocalState](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [JubjubPoint](/api-reference/compact-runtime/interfaces/JubjubPoint.md): @midnight-ntwrk/compact-runtime v0.19.0 - [JubjubSchnorrSignature](/api-reference/compact-runtime/interfaces/JubjubSchnorrSignature.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MerkleTreeDigest](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MerkleTreePath](/api-reference/compact-runtime/interfaces/MerkleTreePath.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MerkleTreePathEntry](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md): @midnight-ntwrk/compact-runtime v0.19.0 - [NativePoint](/api-reference/compact-runtime/interfaces/NativePoint.md): @midnight-ntwrk/compact-runtime v0.14.0 - [PartialProofData](/api-reference/compact-runtime/interfaces/PartialProofData.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ProofData](/api-reference/compact-runtime/interfaces/ProofData.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Recipient](/api-reference/compact-runtime/interfaces/Recipient.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Secp256k1Point](/api-reference/compact-runtime/interfaces/Secp256k1Point.md): @midnight-ntwrk/compact-runtime v0.19.0 - [WitnessContext](/api-reference/compact-runtime/interfaces/WitnessContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ZswapLocalState](/api-reference/compact-runtime/interfaces/ZswapLocalState.md): @midnight-ntwrk/compact-runtime v0.19.0 - [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Alignment](/api-reference/compact-runtime/type-aliases/Alignment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [AlignmentAtom](/api-reference/compact-runtime/type-aliases/AlignmentAtom.md): @midnight-ntwrk/compact-runtime v0.19.0 - [AlignmentSegment](/api-reference/compact-runtime/type-aliases/AlignmentSegment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [BlockContext](/api-reference/compact-runtime/type-aliases/BlockContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CallContext](/api-reference/compact-runtime/type-aliases/CallContext.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CallProofDataTrace](/api-reference/compact-runtime/type-aliases/CallProofDataTrace.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CircuitId](/api-reference/compact-runtime/type-aliases/CircuitId.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CoinCommitment](/api-reference/compact-runtime/type-aliases/CoinCommitment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CoinInfo](/api-reference/compact-runtime/type-aliases/CoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CoinPublicKey](/api-reference/compact-runtime/type-aliases/CoinPublicKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CommunicationCommitment](/api-reference/compact-runtime/type-aliases/CommunicationCommitment.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CommunicationCommitmentRand](/api-reference/compact-runtime/type-aliases/CommunicationCommitmentRand.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractReferenceLocations](/api-reference/compact-runtime/type-aliases/ContractReferenceLocations.md): @midnight-ntwrk/compact-runtime v0.19.0 - [DomainSeparator](/api-reference/compact-runtime/type-aliases/DomainSeparator.md): @midnight-ntwrk/compact-runtime v0.19.0 - [DomainSeperator](/api-reference/compact-runtime/type-aliases/DomainSeperator.md): @midnight-ntwrk/compact-runtime v0.9.0 - [DustTokenType](/api-reference/compact-runtime/type-aliases/DustTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Effects](/api-reference/compact-runtime/type-aliases/Effects.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EmptyPublicLedger](/api-reference/compact-runtime/type-aliases/EmptyPublicLedger.md): @midnight-ntwrk/compact-runtime v0.19.0 - [EncodedStateValue](/api-reference/compact-runtime/type-aliases/EncodedStateValue.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Fr](/api-reference/compact-runtime/type-aliases/Fr.md): @midnight-ntwrk/compact-runtime v0.19.0 - [GatherResult](/api-reference/compact-runtime/type-aliases/GatherResult.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Key](/api-reference/compact-runtime/type-aliases/Key.md): @midnight-ntwrk/compact-runtime v0.19.0 - [LogEvent](/api-reference/compact-runtime/type-aliases/LogEvent.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Nonce](/api-reference/compact-runtime/type-aliases/Nonce.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Nullifier](/api-reference/compact-runtime/type-aliases/Nullifier.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Op](/api-reference/compact-runtime/type-aliases/Op.md): @midnight-ntwrk/compact-runtime v0.19.0 - [PublicAddress](/api-reference/compact-runtime/type-aliases/PublicAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [PublicLedgerSegments](/api-reference/compact-runtime/type-aliases/PublicLedgerSegments.md): @midnight-ntwrk/compact-runtime v0.19.0 - [QualifiedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.9.0 - [QualifiedShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [RawTokenType](/api-reference/compact-runtime/type-aliases/RawTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [RunningCost](/api-reference/compact-runtime/type-aliases/RunningCost.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ShieldedTokenType](/api-reference/compact-runtime/type-aliases/ShieldedTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Signature](/api-reference/compact-runtime/type-aliases/Signature.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SignatureVerifyingKey](/api-reference/compact-runtime/type-aliases/SignatureVerifyingKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SigningKey](/api-reference/compact-runtime/type-aliases/SigningKey.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactADT](/api-reference/compact-runtime/type-aliases/SparseCompactADT.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactArrayLikeADT](/api-reference/compact-runtime/type-aliases/SparseCompactArrayLikeADT.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactCellADT](/api-reference/compact-runtime/type-aliases/SparseCompactCellADT.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactContractAddress](/api-reference/compact-runtime/type-aliases/SparseCompactContractAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactListADT](/api-reference/compact-runtime/type-aliases/SparseCompactListADT.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactMapADT](/api-reference/compact-runtime/type-aliases/SparseCompactMapADT.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactSetADT](/api-reference/compact-runtime/type-aliases/SparseCompactSetADT.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactStruct](/api-reference/compact-runtime/type-aliases/SparseCompactStruct.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactType](/api-reference/compact-runtime/type-aliases/SparseCompactType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactValue](/api-reference/compact-runtime/type-aliases/SparseCompactValue.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SparseCompactVector](/api-reference/compact-runtime/type-aliases/SparseCompactVector.md): @midnight-ntwrk/compact-runtime v0.19.0 - [TokenType](/api-reference/compact-runtime/type-aliases/TokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Transcript](/api-reference/compact-runtime/type-aliases/Transcript.md): @midnight-ntwrk/compact-runtime v0.19.0 - [UnshieldedTokenType](/api-reference/compact-runtime/type-aliases/UnshieldedTokenType.md): @midnight-ntwrk/compact-runtime v0.19.0 - [UserAddress](/api-reference/compact-runtime/type-aliases/UserAddress.md): @midnight-ntwrk/compact-runtime v0.19.0 - [Value](/api-reference/compact-runtime/type-aliases/Value.md): @midnight-ntwrk/compact-runtime v0.19.0 - [BooleanDescriptor](/api-reference/compact-runtime/variables/BooleanDescriptor.md): @midnight-ntwrk/compact-runtime v0.9.0 - [Bytes32Descriptor](/api-reference/compact-runtime/variables/Bytes32Descriptor.md): @midnight-ntwrk/compact-runtime v0.16.0 - [CoinInfoDescriptor](/api-reference/compact-runtime/variables/CoinInfoDescriptor.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CoinRecipientDescriptor](/api-reference/compact-runtime/variables/CoinRecipientDescriptor.md): @midnight-ntwrk/compact-runtime v0.9.0 - [CompactTypeBoolean](/api-reference/compact-runtime/variables/CompactTypeBoolean.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeField](/api-reference/compact-runtime/variables/CompactTypeField.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeJubjubPoint](/api-reference/compact-runtime/variables/CompactTypeJubjubPoint.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeMerkleTreeDigest](/api-reference/compact-runtime/variables/CompactTypeMerkleTreeDigest.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeMerkleTreePathEntry](/api-reference/compact-runtime/variables/CompactTypeMerkleTreePathEntry.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeNativePoint](/api-reference/compact-runtime/variables/CompactTypeNativePoint.md): @midnight-ntwrk/compact-runtime v0.14.0 - [CompactTypeOpaqueString](/api-reference/compact-runtime/variables/CompactTypeOpaqueString.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeOpaqueUint8Array](/api-reference/compact-runtime/variables/CompactTypeOpaqueUint8Array.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeSecp256k1Base](/api-reference/compact-runtime/variables/CompactTypeSecp256k1Base.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeSecp256k1Point](/api-reference/compact-runtime/variables/CompactTypeSecp256k1Point.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CompactTypeSecp256k1Scalar](/api-reference/compact-runtime/variables/CompactTypeSecp256k1Scalar.md): @midnight-ntwrk/compact-runtime v0.19.0 - [CONTRACT_ADDRESS_BYTE_LENGTH](/api-reference/compact-runtime/variables/CONTRACT_ADDRESS_BYTE_LENGTH.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ContractAddressDescriptor](/api-reference/compact-runtime/variables/ContractAddressDescriptor.md): @midnight-ntwrk/compact-runtime v0.16.0 - [DUMMY_ADDRESS](/api-reference/compact-runtime/variables/DUMMY_ADDRESS.md): @midnight-ntwrk/compact-runtime v0.19.0 - [FIELD_MODULUS](/api-reference/compact-runtime/variables/FIELD_MODULUS.md): @midnight-ntwrk/compact-runtime v0.19.0 - [HEX_REGEX_NO_PREFIX](/api-reference/compact-runtime/variables/HEX_REGEX_NO_PREFIX.md): @midnight-ntwrk/compact-runtime v0.19.0 - [JUBJUB_SCALAR_MODULUS](/api-reference/compact-runtime/variables/JUBJUB_SCALAR_MODULUS.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MAX_FIELD](/api-reference/compact-runtime/variables/MAX_FIELD.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MAX_JUBJUB_SCALAR](/api-reference/compact-runtime/variables/MAX_JUBJUB_SCALAR.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MAX_SECP256K1_BASE](/api-reference/compact-runtime/variables/MAX_SECP256K1_BASE.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MAX_SECP256K1_SCALAR](/api-reference/compact-runtime/variables/MAX_SECP256K1_SCALAR.md): @midnight-ntwrk/compact-runtime v0.19.0 - [MaxUint8Descriptor](/api-reference/compact-runtime/variables/MaxUint8Descriptor.md): @midnight-ntwrk/compact-runtime v0.16.0 - [sampleJubjubSchnorrSk](/api-reference/compact-runtime/variables/sampleJubjubSchnorrSk.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SECP256K1_BASE_MODULUS](/api-reference/compact-runtime/variables/SECP256K1_BASE_MODULUS.md): @midnight-ntwrk/compact-runtime v0.19.0 - [SECP256K1_SCALAR_MODULUS](/api-reference/compact-runtime/variables/SECP256K1_SCALAR_MODULUS.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ShieldedCoinInfoDescriptor](/api-reference/compact-runtime/variables/ShieldedCoinInfoDescriptor.md): @midnight-ntwrk/compact-runtime v0.16.0 - [ShieldedCoinRecipientDescriptor](/api-reference/compact-runtime/variables/ShieldedCoinRecipientDescriptor.md): @midnight-ntwrk/compact-runtime v0.16.0 - [versionString](/api-reference/compact-runtime/variables/versionString.md): @midnight-ntwrk/compact-runtime v0.19.0 - [ZswapCoinPublicKeyDescriptor](/api-reference/compact-runtime/variables/ZswapCoinPublicKeyDescriptor.md): @midnight-ntwrk/compact-runtime v0.16.0 ### dapp-connector @midnight-ntwrk/dapp-connector-api v4.0.1 - [Midnight DApp connector API](/api-reference/dapp-connector.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [globals](/api-reference/dapp-connector/globals.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [APIError](/api-reference/dapp-connector/type-aliases/APIError.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [Configuration](/api-reference/dapp-connector/type-aliases/Configuration.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [ConnectedAPI](/api-reference/dapp-connector/type-aliases/ConnectedAPI.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [ConnectionStatus](/api-reference/dapp-connector/type-aliases/ConnectionStatus.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [DesiredInput](/api-reference/dapp-connector/type-aliases/DesiredInput.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [DesiredOutput](/api-reference/dapp-connector/type-aliases/DesiredOutput.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [ErrorCode](/api-reference/dapp-connector/type-aliases/ErrorCode.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [ExecutionStatus](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [HintUsage](/api-reference/dapp-connector/type-aliases/HintUsage.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [HistoryEntry](/api-reference/dapp-connector/type-aliases/HistoryEntry.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [InitialAPI](/api-reference/dapp-connector/type-aliases/InitialAPI.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [KeyMaterialProvider](/api-reference/dapp-connector/type-aliases/KeyMaterialProvider.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [ProvingProvider](/api-reference/dapp-connector/type-aliases/ProvingProvider.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [Signature](/api-reference/dapp-connector/type-aliases/Signature.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [SignDataOptions](/api-reference/dapp-connector/type-aliases/SignDataOptions.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [TokenType](/api-reference/dapp-connector/type-aliases/TokenType.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [TxStatus](/api-reference/dapp-connector/type-aliases/TxStatus.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [WalletConnectedAPI](/api-reference/dapp-connector/type-aliases/WalletConnectedAPI.md): @midnight-ntwrk/dapp-connector-api v4.0.1 - [ErrorCodes](/api-reference/dapp-connector/variables/ErrorCodes.md): @midnight-ntwrk/dapp-connector-api v4.0.1 ### error-reference - [DApp Connector API errors](/api-reference/error-reference/dapp-connector-errors.md): Error codes returned by the Midnight DApp Connector API when a DApp interacts with a wallet. - [Midnight indexer error codes](/api-reference/error-reference/indexer-errors.md): Error codes and messages returned by the Midnight Indexer API and infrastructure services. - [Ledger error reference](/api-reference/error-reference/ledger-errors.md): Rust-level error types from the Midnight ledger crate covering transaction validation, execution, and state management failures. - [Proof server errors](/api-reference/error-reference/proof-server-errors.md): Error codes returned by the Midnight proof server during zero-knowledge proof generation. ### ledger @midnight/ledger v8.0.3 - [Ledger API](/api-reference/ledger.md): @midnight/ledger v8.0.3 - [Binding](/api-reference/ledger/classes/Binding.md): @midnight/ledger v8.0.3 - [ChargedState](/api-reference/ledger/classes/ChargedState.md): @midnight/ledger v8.0.3 - [ClaimRewardsTransaction](/api-reference/ledger/classes/ClaimRewardsTransaction.md): @midnight/ledger v8.0.3 - [CoinSecretKey](/api-reference/ledger/classes/CoinSecretKey.md): @midnight/ledger v8.0.3 - [ContractCall](/api-reference/ledger/classes/ContractCall.md): @midnight/ledger v8.0.3 - [ContractCallPrototype](/api-reference/ledger/classes/ContractCallPrototype.md): @midnight/ledger v8.0.3 - [ContractDeploy](/api-reference/ledger/classes/ContractDeploy.md): @midnight/ledger v8.0.3 - [ContractMaintenanceAuthority](/api-reference/ledger/classes/ContractMaintenanceAuthority.md): @midnight/ledger v8.0.3 - [ContractOperation](/api-reference/ledger/classes/ContractOperation.md): @midnight/ledger v8.0.3 - [ContractOperationVersion](/api-reference/ledger/classes/ContractOperationVersion.md): @midnight/ledger v8.0.3 - [ContractOperationVersionedVerifierKey](/api-reference/ledger/classes/ContractOperationVersionedVerifierKey.md): @midnight/ledger v8.0.3 - [ContractState](/api-reference/ledger/classes/ContractState.md): @midnight/ledger v8.0.3 - [CostModel](/api-reference/ledger/classes/CostModel.md): @midnight/ledger v8.0.3 - [DustActions](/api-reference/ledger/classes/DustActions.md): @midnight/ledger v8.0.3 - [DustGenerationState](/api-reference/ledger/classes/DustGenerationState.md): @midnight/ledger v8.0.3 - [DustLocalState](/api-reference/ledger/classes/DustLocalState.md): @midnight/ledger v8.0.3 - [DustLocalStateWithChanges](/api-reference/ledger/classes/DustLocalStateWithChanges.md): @midnight/ledger v8.0.3 - [DustParameters](/api-reference/ledger/classes/DustParameters.md): @midnight/ledger v8.0.3 - [DustRegistration](/api-reference/ledger/classes/DustRegistration.md): @midnight/ledger v8.0.3 - [DustSecretKey](/api-reference/ledger/classes/DustSecretKey.md): @midnight/ledger v8.0.3 - [DustSpend](/api-reference/ledger/classes/DustSpend.md): @midnight/ledger v8.0.3 - [DustState](/api-reference/ledger/classes/DustState.md): @midnight/ledger v8.0.3 - [DustStateChanges](/api-reference/ledger/classes/DustStateChanges.md): @midnight/ledger v8.0.3 - [DustUtxoState](/api-reference/ledger/classes/DustUtxoState.md): @midnight/ledger v8.0.3 - [EncryptionSecretKey](/api-reference/ledger/classes/EncryptionSecretKey.md): @midnight/ledger v8.0.3 - [Event](/api-reference/ledger/classes/Event.md): @midnight/ledger v8.0.3 - [Intent](/api-reference/ledger/classes/Intent.md): @midnight/ledger v8.0.3 - [LedgerParameters](/api-reference/ledger/classes/LedgerParameters.md): @midnight/ledger v8.0.3 - [LedgerState](/api-reference/ledger/classes/LedgerState.md): @midnight/ledger v8.0.3 - [MaintenanceUpdate](/api-reference/ledger/classes/MaintenanceUpdate.md): @midnight/ledger v8.0.3 - [MerkleTreeCollapsedUpdate](/api-reference/ledger/classes/MerkleTreeCollapsedUpdate.md): @midnight/ledger v8.0.3 - [NoBinding](/api-reference/ledger/classes/NoBinding.md): @midnight/ledger v8.0.3 - [NoProof](/api-reference/ledger/classes/NoProof.md): @midnight/ledger v8.0.3 - [PreBinding](/api-reference/ledger/classes/PreBinding.md): @midnight/ledger v8.0.3 - [PrePartitionContractCall](/api-reference/ledger/classes/PrePartitionContractCall.md): @midnight/ledger v8.0.3 - [PreProof](/api-reference/ledger/classes/PreProof.md): @midnight/ledger v8.0.3 - [PreTranscript](/api-reference/ledger/classes/PreTranscript.md): @midnight/ledger v8.0.3 - [Proof](/api-reference/ledger/classes/Proof.md): @midnight/ledger v8.0.3 - [QueryContext](/api-reference/ledger/classes/QueryContext.md): @midnight/ledger v8.0.3 - [QueryResults](/api-reference/ledger/classes/QueryResults.md): @midnight/ledger v8.0.3 - [ReplaceAuthority](/api-reference/ledger/classes/ReplaceAuthority.md): @midnight/ledger v8.0.3 - [SignatureEnabled](/api-reference/ledger/classes/SignatureEnabled.md): @midnight/ledger v8.0.3 - [SignatureErased](/api-reference/ledger/classes/SignatureErased.md): @midnight/ledger v8.0.3 - [StateBoundedMerkleTree](/api-reference/ledger/classes/StateBoundedMerkleTree.md): @midnight/ledger v8.0.3 - [StateMap](/api-reference/ledger/classes/StateMap.md): @midnight/ledger v8.0.3 - [StateValue](/api-reference/ledger/classes/StateValue.md): @midnight/ledger v8.0.3 - [SystemTransaction](/api-reference/ledger/classes/SystemTransaction.md): @midnight/ledger v8.0.3 - [Transaction](/api-reference/ledger/classes/Transaction.md): @midnight/ledger v8.0.3 - [TransactionContext](/api-reference/ledger/classes/TransactionContext.md): @midnight/ledger v8.0.3 - [TransactionCostModel](/api-reference/ledger/classes/TransactionCostModel.md): @midnight/ledger v8.0.3 - [TransactionResult](/api-reference/ledger/classes/TransactionResult.md): @midnight/ledger v8.0.3 - [UnshieldedOffer](/api-reference/ledger/classes/UnshieldedOffer.md): @midnight/ledger v8.0.3 - [UtxoMeta](/api-reference/ledger/classes/UtxoMeta.md): @midnight/ledger v8.0.3 - [UtxoState](/api-reference/ledger/classes/UtxoState.md): @midnight/ledger v8.0.3 - [VerifiedTransaction](/api-reference/ledger/classes/VerifiedTransaction.md): @midnight/ledger v8.0.3 - [VerifierKeyInsert](/api-reference/ledger/classes/VerifierKeyInsert.md): @midnight/ledger v8.0.3 - [VerifierKeyRemove](/api-reference/ledger/classes/VerifierKeyRemove.md): @midnight/ledger v8.0.3 - [VmResults](/api-reference/ledger/classes/VmResults.md): @midnight/ledger v8.0.3 - [VmStack](/api-reference/ledger/classes/VmStack.md): @midnight/ledger v8.0.3 - [WellFormedStrictness](/api-reference/ledger/classes/WellFormedStrictness.md): @midnight/ledger v8.0.3 - [ZswapChainState](/api-reference/ledger/classes/ZswapChainState.md): @midnight/ledger v8.0.3 - [ZswapInput](/api-reference/ledger/classes/ZswapInput.md): @midnight/ledger v8.0.3 - [ZswapLocalState](/api-reference/ledger/classes/ZswapLocalState.md): @midnight/ledger v8.0.3 - [ZswapLocalStateWithChanges](/api-reference/ledger/classes/ZswapLocalStateWithChanges.md): @midnight/ledger v8.0.3 - [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md): @midnight/ledger v8.0.3 - [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md): @midnight/ledger v8.0.3 - [ZswapSecretKeys](/api-reference/ledger/classes/ZswapSecretKeys.md): @midnight/ledger v8.0.3 - [ZswapStateChanges](/api-reference/ledger/classes/ZswapStateChanges.md): @midnight/ledger v8.0.3 - [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md): @midnight/ledger v8.0.3 - [addressFromKey](/api-reference/ledger/functions/addressFromKey.md): @midnight/ledger v8.0.3 - [bigIntModFr](/api-reference/ledger/functions/bigIntModFr.md): @midnight/ledger v8.0.3 - [bigIntToValue](/api-reference/ledger/functions/bigIntToValue.md): @midnight/ledger v8.0.3 - [coinCommitment](/api-reference/ledger/functions/coinCommitment.md): @midnight/ledger v8.0.3 - [coinNullifier](/api-reference/ledger/functions/coinNullifier.md): @midnight/ledger v8.0.3 - [communicationCommitment](/api-reference/ledger/functions/communicationCommitment.md): @midnight/ledger v8.0.3 - [communicationCommitmentRandomness](/api-reference/ledger/functions/communicationCommitmentRandomness.md): @midnight/ledger v8.0.3 - [createCheckPayload](/api-reference/ledger/functions/createCheckPayload.md): @midnight/ledger v8.0.3 - [createProvingPayload](/api-reference/ledger/functions/createProvingPayload.md): @midnight/ledger v8.0.3 - [createProvingTransactionPayload](/api-reference/ledger/functions/createProvingTransactionPayload.md): @midnight/ledger v8.0.3 - [createShieldedCoinInfo](/api-reference/ledger/functions/createShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [decodeCoinPublicKey](/api-reference/ledger/functions/decodeCoinPublicKey.md): @midnight/ledger v8.0.3 - [decodeContractAddress](/api-reference/ledger/functions/decodeContractAddress.md): @midnight/ledger v8.0.3 - [decodeQualifiedShieldedCoinInfo](/api-reference/ledger/functions/decodeQualifiedShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [decodeRawTokenType](/api-reference/ledger/functions/decodeRawTokenType.md): @midnight/ledger v8.0.3 - [decodeShieldedCoinInfo](/api-reference/ledger/functions/decodeShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [decodeUserAddress](/api-reference/ledger/functions/decodeUserAddress.md): @midnight/ledger v8.0.3 - [degradeToTransient](/api-reference/ledger/functions/degradeToTransient.md): @midnight/ledger v8.0.3 - [dummyContractAddress](/api-reference/ledger/functions/dummyContractAddress.md): @midnight/ledger v8.0.3 - [dummyUserAddress](/api-reference/ledger/functions/dummyUserAddress.md): @midnight/ledger v8.0.3 - [ecAdd](/api-reference/ledger/functions/ecAdd.md): @midnight/ledger v8.0.3 - [ecMul](/api-reference/ledger/functions/ecMul.md): @midnight/ledger v8.0.3 - [ecMulGenerator](/api-reference/ledger/functions/ecMulGenerator.md): @midnight/ledger v8.0.3 - [encodeCoinPublicKey](/api-reference/ledger/functions/encodeCoinPublicKey.md): @midnight/ledger v8.0.3 - [encodeContractAddress](/api-reference/ledger/functions/encodeContractAddress.md): @midnight/ledger v8.0.3 - [encodeQualifiedShieldedCoinInfo](/api-reference/ledger/functions/encodeQualifiedShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [encodeRawTokenType](/api-reference/ledger/functions/encodeRawTokenType.md): @midnight/ledger v8.0.3 - [encodeShieldedCoinInfo](/api-reference/ledger/functions/encodeShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [encodeUserAddress](/api-reference/ledger/functions/encodeUserAddress.md): @midnight/ledger v8.0.3 - [entryPointHash](/api-reference/ledger/functions/entryPointHash.md): @midnight/ledger v8.0.3 - [feeToken](/api-reference/ledger/functions/feeToken.md): @midnight/ledger v8.0.3 - [hashToCurve](/api-reference/ledger/functions/hashToCurve.md): @midnight/ledger v8.0.3 - [leafHash](/api-reference/ledger/functions/leafHash.md): @midnight/ledger v8.0.3 - [maxAlignedSize](/api-reference/ledger/functions/maxAlignedSize.md): @midnight/ledger v8.0.3 - [maxField](/api-reference/ledger/functions/maxField.md): @midnight/ledger v8.0.3 - [nativeToken](/api-reference/ledger/functions/nativeToken.md): @midnight/ledger v8.0.3 - [parseCheckResult](/api-reference/ledger/functions/parseCheckResult.md): @midnight/ledger v8.0.3 - [partitionTranscripts](/api-reference/ledger/functions/partitionTranscripts.md): @midnight/ledger v8.0.3 - [persistentCommit](/api-reference/ledger/functions/persistentCommit.md): @midnight/ledger v8.0.3 - [persistentHash](/api-reference/ledger/functions/persistentHash.md): @midnight/ledger v8.0.3 - [proofDataIntoSerializedPreimage](/api-reference/ledger/functions/proofDataIntoSerializedPreimage.md): @midnight/ledger v8.0.3 - [rawTokenType](/api-reference/ledger/functions/rawTokenType.md): @midnight/ledger v8.0.3 - [runProgram](/api-reference/ledger/functions/runProgram.md): @midnight/ledger v8.0.3 - [runtimeCoinCommitment](/api-reference/ledger/functions/runtimeCoinCommitment.md): @midnight/ledger v8.0.3 - [runtimeCoinNullifier](/api-reference/ledger/functions/runtimeCoinNullifier.md): @midnight/ledger v8.0.3 - [sampleCoinPublicKey](/api-reference/ledger/functions/sampleCoinPublicKey.md): @midnight/ledger v8.0.3 - [sampleContractAddress](/api-reference/ledger/functions/sampleContractAddress.md): @midnight/ledger v8.0.3 - [sampleDustSecretKey](/api-reference/ledger/functions/sampleDustSecretKey.md): @midnight/ledger v8.0.3 - [sampleEncryptionPublicKey](/api-reference/ledger/functions/sampleEncryptionPublicKey.md): @midnight/ledger v8.0.3 - [sampleIntentHash](/api-reference/ledger/functions/sampleIntentHash.md): @midnight/ledger v8.0.3 - [sampleRawTokenType](/api-reference/ledger/functions/sampleRawTokenType.md): @midnight/ledger v8.0.3 - [sampleSigningKey](/api-reference/ledger/functions/sampleSigningKey.md): @midnight/ledger v8.0.3 - [sampleUserAddress](/api-reference/ledger/functions/sampleUserAddress.md): @midnight/ledger v8.0.3 - [shieldedToken](/api-reference/ledger/functions/shieldedToken.md): @midnight/ledger v8.0.3 - [signatureVerifyingKey](/api-reference/ledger/functions/signatureVerifyingKey.md): @midnight/ledger v8.0.3 - [signData](/api-reference/ledger/functions/signData.md): @midnight/ledger v8.0.3 - [signingKeyFromBip340](/api-reference/ledger/functions/signingKeyFromBip340.md): @midnight/ledger v8.0.3 - [transientCommit](/api-reference/ledger/functions/transientCommit.md): @midnight/ledger v8.0.3 - [transientHash](/api-reference/ledger/functions/transientHash.md): @midnight/ledger v8.0.3 - [unshieldedToken](/api-reference/ledger/functions/unshieldedToken.md): @midnight/ledger v8.0.3 - [updatedValue](/api-reference/ledger/functions/updatedValue.md): @midnight/ledger v8.0.3 - [upgradeFromTransient](/api-reference/ledger/functions/upgradeFromTransient.md): @midnight/ledger v8.0.3 - [valueToBigInt](/api-reference/ledger/functions/valueToBigInt.md): @midnight/ledger v8.0.3 - [verifySignature](/api-reference/ledger/functions/verifySignature.md): @midnight/ledger v8.0.3 - [globals](/api-reference/ledger/globals.md): @midnight/ledger v8.0.3 - [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md): @midnight/ledger v8.0.3 - [Alignment](/api-reference/ledger/type-aliases/Alignment.md): @midnight/ledger v8.0.3 - [AlignmentAtom](/api-reference/ledger/type-aliases/AlignmentAtom.md): @midnight/ledger v8.0.3 - [AlignmentSegment](/api-reference/ledger/type-aliases/AlignmentSegment.md): @midnight/ledger v8.0.3 - [Bindingish](/api-reference/ledger/type-aliases/Bindingish.md): @midnight/ledger v8.0.3 - [BlockContext](/api-reference/ledger/type-aliases/BlockContext.md): @midnight/ledger v8.0.3 - [CallContext](/api-reference/ledger/type-aliases/CallContext.md): @midnight/ledger v8.0.3 - [ClaimKind](/api-reference/ledger/type-aliases/ClaimKind.md): @midnight/ledger v8.0.3 - [CoinCommitment](/api-reference/ledger/type-aliases/CoinCommitment.md): @midnight/ledger v8.0.3 - [CoinPublicKey](/api-reference/ledger/type-aliases/CoinPublicKey.md): @midnight/ledger v8.0.3 - [CommunicationCommitment](/api-reference/ledger/type-aliases/CommunicationCommitment.md): @midnight/ledger v8.0.3 - [CommunicationCommitmentRand](/api-reference/ledger/type-aliases/CommunicationCommitmentRand.md): @midnight/ledger v8.0.3 - [ContractAction](/api-reference/ledger/type-aliases/ContractAction.md): @midnight/ledger v8.0.3 - [ContractAddress](/api-reference/ledger/type-aliases/ContractAddress.md): @midnight/ledger v8.0.3 - [DomainSeparator](/api-reference/ledger/type-aliases/DomainSeparator.md): @midnight/ledger v8.0.3 - [DustCommitment](/api-reference/ledger/type-aliases/DustCommitment.md): @midnight/ledger v8.0.3 - [DustGenerationInfo](/api-reference/ledger/type-aliases/DustGenerationInfo.md): @midnight/ledger v8.0.3 - [DustGenerationUniquenessInfo](/api-reference/ledger/type-aliases/DustGenerationUniquenessInfo.md): @midnight/ledger v8.0.3 - [DustInitialNonce](/api-reference/ledger/type-aliases/DustInitialNonce.md): @midnight/ledger v8.0.3 - [DustNonce](/api-reference/ledger/type-aliases/DustNonce.md): @midnight/ledger v8.0.3 - [DustNullifier](/api-reference/ledger/type-aliases/DustNullifier.md): @midnight/ledger v8.0.3 - [DustOutput](/api-reference/ledger/type-aliases/DustOutput.md): @midnight/ledger v8.0.3 - [DustPublicKey](/api-reference/ledger/type-aliases/DustPublicKey.md): @midnight/ledger v8.0.3 - [DustTokenType](/api-reference/ledger/type-aliases/DustTokenType.md): @midnight/ledger v8.0.3 - [Effects](/api-reference/ledger/type-aliases/Effects.md): @midnight/ledger v8.0.3 - [EncodedStateValue](/api-reference/ledger/type-aliases/EncodedStateValue.md): @midnight/ledger v8.0.3 - [EncPublicKey](/api-reference/ledger/type-aliases/EncPublicKey.md): @midnight/ledger v8.0.3 - [ErasedTransactionResult](/api-reference/ledger/type-aliases/ErasedTransactionResult.md): @midnight/ledger v8.0.3 - [FeePrices](/api-reference/ledger/type-aliases/FeePrices.md): @midnight/ledger v8.0.3 - [FinalizedTransaction](/api-reference/ledger/type-aliases/FinalizedTransaction.md): @midnight/ledger v8.0.3 - [Fr](/api-reference/ledger/type-aliases/Fr.md): @midnight/ledger v8.0.3 - [GatherResult](/api-reference/ledger/type-aliases/GatherResult.md): @midnight/ledger v8.0.3 - [IntentHash](/api-reference/ledger/type-aliases/IntentHash.md): @midnight/ledger v8.0.3 - [Key](/api-reference/ledger/type-aliases/Key.md): @midnight/ledger v8.0.3 - [Nonce](/api-reference/ledger/type-aliases/Nonce.md): @midnight/ledger v8.0.3 - [NormalizedCost](/api-reference/ledger/type-aliases/NormalizedCost.md): @midnight/ledger v8.0.3 - [Nullifier](/api-reference/ledger/type-aliases/Nullifier.md): @midnight/ledger v8.0.3 - [Op](/api-reference/ledger/type-aliases/Op.md): @midnight/ledger v8.0.3 - [PartitionedTranscript](/api-reference/ledger/type-aliases/PartitionedTranscript.md): @midnight/ledger v8.0.3 - [ProofErasedTransaction](/api-reference/ledger/type-aliases/ProofErasedTransaction.md): @midnight/ledger v8.0.3 - [Proofish](/api-reference/ledger/type-aliases/Proofish.md): @midnight/ledger v8.0.3 - [ProvingKeyMaterial](/api-reference/ledger/type-aliases/ProvingKeyMaterial.md): @midnight/ledger v8.0.3 - [ProvingProvider](/api-reference/ledger/type-aliases/ProvingProvider.md): @midnight/ledger v8.0.3 - [PublicAddress](/api-reference/ledger/type-aliases/PublicAddress.md): @midnight/ledger v8.0.3 - [QualifiedDustOutput](/api-reference/ledger/type-aliases/QualifiedDustOutput.md): @midnight/ledger v8.0.3 - [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md): @midnight/ledger v8.0.3 - [RunningCost](/api-reference/ledger/type-aliases/RunningCost.md): @midnight/ledger v8.0.3 - [SegmentSpecifier](/api-reference/ledger/type-aliases/SegmentSpecifier.md): @midnight/ledger v8.0.3 - [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md): @midnight/ledger v8.0.3 - [ShieldedTokenType](/api-reference/ledger/type-aliases/ShieldedTokenType.md): @midnight/ledger v8.0.3 - [Signature](/api-reference/ledger/type-aliases/Signature.md): @midnight/ledger v8.0.3 - [SignatureVerifyingKey](/api-reference/ledger/type-aliases/SignatureVerifyingKey.md): @midnight/ledger v8.0.3 - [Signaturish](/api-reference/ledger/type-aliases/Signaturish.md): @midnight/ledger v8.0.3 - [SigningKey](/api-reference/ledger/type-aliases/SigningKey.md): @midnight/ledger v8.0.3 - [SingleUpdate](/api-reference/ledger/type-aliases/SingleUpdate.md): @midnight/ledger v8.0.3 - [SyntheticCost](/api-reference/ledger/type-aliases/SyntheticCost.md): @midnight/ledger v8.0.3 - [TokenType](/api-reference/ledger/type-aliases/TokenType.md): @midnight/ledger v8.0.3 - [TransactionHash](/api-reference/ledger/type-aliases/TransactionHash.md): @midnight/ledger v8.0.3 - [TransactionId](/api-reference/ledger/type-aliases/TransactionId.md): @midnight/ledger v8.0.3 - [Transcript](/api-reference/ledger/type-aliases/Transcript.md): @midnight/ledger v8.0.3 - [UnprovenInput](/api-reference/ledger/type-aliases/UnprovenInput.md): @midnight/ledger v8.0.3 - [UnprovenIntent](/api-reference/ledger/type-aliases/UnprovenIntent.md): @midnight/ledger v8.0.3 - [UnprovenOffer](/api-reference/ledger/type-aliases/UnprovenOffer.md): @midnight/ledger v8.0.3 - [UnprovenOutput](/api-reference/ledger/type-aliases/UnprovenOutput.md): @midnight/ledger v8.0.3 - [UnprovenTransaction](/api-reference/ledger/type-aliases/UnprovenTransaction.md): @midnight/ledger v8.0.3 - [UnprovenTransient](/api-reference/ledger/type-aliases/UnprovenTransient.md): @midnight/ledger v8.0.3 - [UnshieldedTokenType](/api-reference/ledger/type-aliases/UnshieldedTokenType.md): @midnight/ledger v8.0.3 - [UserAddress](/api-reference/ledger/type-aliases/UserAddress.md): @midnight/ledger v8.0.3 - [Utxo](/api-reference/ledger/type-aliases/Utxo.md): @midnight/ledger v8.0.3 - [UtxoOutput](/api-reference/ledger/type-aliases/UtxoOutput.md): @midnight/ledger v8.0.3 - [UtxoSpend](/api-reference/ledger/type-aliases/UtxoSpend.md): @midnight/ledger v8.0.3 - [Value](/api-reference/ledger/type-aliases/Value.md): @midnight/ledger v8.0.3 ### midnight-indexer The Midnight Indexer API exposes a GraphQL API that enables clients to query and subscribe to blockchain data—blocks, transactions, contracts, DUST generation, and shielded/unshielded transaction events, indexed from the Midnight blockchain. These capabilities facilitate both historical lookups and real-time monitoring. - [Midnight Indexer API v4](/api-reference/midnight-indexer.md): The Midnight Indexer API exposes a GraphQL API that enables clients to query and subscribe to blockchain data—blocks, transactions, contracts, DUST generation, and shielded/unshielded transaction events, indexed from the Midnight blockchain. These capabilities facilitate both historical lookups and real-time monitoring. - [include](/api-reference/midnight-indexer/operations/directives/include.md): Directs the executor to include this field or fragment only when the if argument is true. - [skip](/api-reference/midnight-indexer/operations/directives/skip.md): Directs the executor to skip this field or fragment when the if argument is true. - [connect](/api-reference/midnight-indexer/operations/mutations/connect.md): Connect the wallet with the given viewing key and return a session ID. - [disconnect](/api-reference/midnight-indexer/operations/mutations/disconnect.md): Disconnect the wallet with the given session ID. - [block](/api-reference/midnight-indexer/operations/queries/block.md): Find a block for the given optional offset; if not present, the latest block is returned. - [committee](/api-reference/midnight-indexer/operations/queries/committee.md): Get committee membership for an epoch. - [contractAction](/api-reference/midnight-indexer/operations/queries/contract-action.md): Find a contract action for the given address and optional offset. - [currentEpochInfo](/api-reference/midnight-indexer/operations/queries/current-epoch-info.md): Get current epoch information. - [dParameterHistory](/api-reference/midnight-indexer/operations/queries/d-parameter-history.md): Get the full history of D-parameter changes for governance auditability. - [dustGenerationStatus](/api-reference/midnight-indexer/operations/queries/dust-generation-status.md): Get DUST generation status for specific Cardano reward addresses. - [epochPerformance](/api-reference/midnight-indexer/operations/queries/epoch-performance.md): Get epoch performance for all SPOs. - [epochUtilization](/api-reference/midnight-indexer/operations/queries/epoch-utilization.md): Get epoch utilization (produced/expected ratio). - [poolMetadata](/api-reference/midnight-indexer/operations/queries/pool-metadata.md): Get pool metadata by pool ID. - [poolMetadataList](/api-reference/midnight-indexer/operations/queries/pool-metadata-list.md): List pool metadata with pagination. - [registeredFirstValidEpochs](/api-reference/midnight-indexer/operations/queries/registered-first-valid-epochs.md): Get first valid epoch for each SPO identity. - [registeredPresence](/api-reference/midnight-indexer/operations/queries/registered-presence.md): Get raw presence events for an epoch range. - [registeredSpoSeries](/api-reference/midnight-indexer/operations/queries/registered-spo-series.md): Get registration statistics for an epoch range. - [registeredTotalsSeries](/api-reference/midnight-indexer/operations/queries/registered-totals-series.md): Get cumulative registration totals for an epoch range. - [spoByPoolId](/api-reference/midnight-indexer/operations/queries/spo-by-pool-id.md): Get SPO with metadata by pool ID. - [spoCompositeByPoolId](/api-reference/midnight-indexer/operations/queries/spo-composite-by-pool-id.md): Get composite SPO data (identity + metadata + performance). - [spoCount](/api-reference/midnight-indexer/operations/queries/spo-count.md): Get total count of SPOs. - [spoIdentities](/api-reference/midnight-indexer/operations/queries/spo-identities.md): List SPO identities with pagination. - [spoIdentityByPoolId](/api-reference/midnight-indexer/operations/queries/spo-identity-by-pool-id.md): Get SPO identity by pool ID. - [spoList](/api-reference/midnight-indexer/operations/queries/spo-list.md): List SPOs with optional search. - [spoPerformanceBySpoSk](/api-reference/midnight-indexer/operations/queries/spo-performance-by-spo-sk.md): Get SPO performance by SPO key. - [spoPerformanceLatest](/api-reference/midnight-indexer/operations/queries/spo-performance-latest.md): Get latest SPO performance entries. - [stakeDistribution](/api-reference/midnight-indexer/operations/queries/stake-distribution.md): Get stake distribution with search and ordering. - [stakePoolOperators](/api-reference/midnight-indexer/operations/queries/stake-pool-operators.md): Get SPO identifiers ordered by performance. - [termsAndConditionsHistory](/api-reference/midnight-indexer/operations/queries/terms-and-conditions-history.md): Get the full history of Terms and Conditions changes for governance auditability. - [transactions](/api-reference/midnight-indexer/operations/queries/transactions.md): Find transactions for the given offset. - [blocks](/api-reference/midnight-indexer/operations/subscriptions/blocks.md): Subscribe to blocks starting at the given offset or at the latest block if the offset is - [contractActions](/api-reference/midnight-indexer/operations/subscriptions/contract-actions.md): Subscribe to contract actions with the given address starting at the given offset or at the - [dustLedgerEvents](/api-reference/midnight-indexer/operations/subscriptions/dust-ledger-events.md): Subscribe to dust ledger events starting at the given ID or at the very start if omitted. - [shieldedTransactions](/api-reference/midnight-indexer/operations/subscriptions/shielded-transactions.md): Subscribe to shielded transaction events for the given session ID starting at the given - [unshieldedTransactions](/api-reference/midnight-indexer/operations/subscriptions/unshielded-transactions.md): Subscribe unshielded transaction events for the given address and the given transaction ID - [zswapLedgerEvents](/api-reference/midnight-indexer/operations/subscriptions/zswap-ledger-events.md): Subscribe to zswap ledger events starting at the given ID or at the very start if omitted. - [deprecated](/api-reference/midnight-indexer/types/directives/deprecated.md): Marks an element of a GraphQL schema as no longer supported. - [oneOf](/api-reference/midnight-indexer/types/directives/one-of.md): Indicates that an Input Object is a OneOf Input Object (and thus requires exactly one of its field be provided) - [specifiedBy](/api-reference/midnight-indexer/types/directives/specified-by.md): Exposes a URL that specifies the behavior of this scalar. - [TransactionResultStatus](/api-reference/midnight-indexer/types/enums/transaction-result-status.md): The status of the transaction result: success, partial success or failure. - [BlockOffset](/api-reference/midnight-indexer/types/inputs/block-offset.md): Either a block hash or a block height. - [ContractActionOffset](/api-reference/midnight-indexer/types/inputs/contract-action-offset.md): Either a block offset or a transaction offset. - [TransactionOffset](/api-reference/midnight-indexer/types/inputs/transaction-offset.md): Either a transaction hash or a transaction identifier. - [ContractAction](/api-reference/midnight-indexer/types/interfaces/contract-action.md): A contract action. - [DustLedgerEvent](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md): A dust related ledger event. - [Transaction](/api-reference/midnight-indexer/types/interfaces/transaction.md): A Midnight transaction. - [Block](/api-reference/midnight-indexer/types/objects/block.md): A block with its relevant data. - [CollapsedMerkleTree](/api-reference/midnight-indexer/types/objects/collapsed-merkle-tree.md): No description - [CommitteeMember](/api-reference/midnight-indexer/types/objects/committee-member.md): Committee member for an epoch. - [ContractBalance](/api-reference/midnight-indexer/types/objects/contract-balance.md): Represents a token balance held by a contract. - [ContractCall](/api-reference/midnight-indexer/types/objects/contract-call.md): A contract call. - [ContractDeploy](/api-reference/midnight-indexer/types/objects/contract-deploy.md): A contract deployment. - [ContractUpdate](/api-reference/midnight-indexer/types/objects/contract-update.md): A contract update. - [DParameter](/api-reference/midnight-indexer/types/objects/dparameter.md): The D-parameter controlling validator committee composition. - [DParameterChange](/api-reference/midnight-indexer/types/objects/dparameter-change.md): D-parameter change record for history queries. - [DustGenerationDtimeUpdate](/api-reference/midnight-indexer/types/objects/dust-generation-dtime-update.md): No description - [DustGenerationStatus](/api-reference/midnight-indexer/types/objects/dust-generation-status.md): DUST generation status for a specific Cardano reward address. - [DustInitialUtxo](/api-reference/midnight-indexer/types/objects/dust-initial-utxo.md): No description - [DustOutput](/api-reference/midnight-indexer/types/objects/dust-output.md): A dust output. - [DustSpendProcessed](/api-reference/midnight-indexer/types/objects/dust-spend-processed.md): No description - [EpochInfo](/api-reference/midnight-indexer/types/objects/epoch-info.md): Current epoch information. - [EpochPerf](/api-reference/midnight-indexer/types/objects/epoch-perf.md): SPO performance for an epoch. - [FirstValidEpoch](/api-reference/midnight-indexer/types/objects/first-valid-epoch.md): First valid epoch for an SPO identity. - [ParamChange](/api-reference/midnight-indexer/types/objects/param-change.md): No description - [PoolMetadata](/api-reference/midnight-indexer/types/objects/pool-metadata.md): Pool metadata from Cardano. - [PresenceEvent](/api-reference/midnight-indexer/types/objects/presence-event.md): Presence event for an SPO in an epoch. - [RegisteredStat](/api-reference/midnight-indexer/types/objects/registered-stat.md): Registration statistics for an epoch. - [RegisteredTotals](/api-reference/midnight-indexer/types/objects/registered-totals.md): Cumulative registration totals for an epoch. - [RegularTransaction](/api-reference/midnight-indexer/types/objects/regular-transaction.md): A regular Midnight transaction. - [RelevantTransaction](/api-reference/midnight-indexer/types/objects/relevant-transaction.md): A transaction relevant for the subscribing wallet and an optional collapsed merkle tree. - [Segment](/api-reference/midnight-indexer/types/objects/segment.md): One of many segments for a partially successful transaction result showing success for some - [ShieldedTransactionsProgress](/api-reference/midnight-indexer/types/objects/shielded-transactions-progress.md): Information about the shielded transactions indexing progress. - [Spo](/api-reference/midnight-indexer/types/objects/spo.md): SPO with optional metadata. - [SpoComposite](/api-reference/midnight-indexer/types/objects/spo-composite.md): Composite SPO data (identity + metadata + performance). - [SpoIdentity](/api-reference/midnight-indexer/types/objects/spo-identity.md): SPO identity information. - [StakeShare](/api-reference/midnight-indexer/types/objects/stake-share.md): Stake share information for an SPO. - [SystemParameters](/api-reference/midnight-indexer/types/objects/system-parameters.md): System parameters at a specific block height. - [SystemTransaction](/api-reference/midnight-indexer/types/objects/system-transaction.md): A system Midnight transaction. - [TermsAndConditions](/api-reference/midnight-indexer/types/objects/terms-and-conditions.md): Terms and Conditions agreement. - [TermsAndConditionsChange](/api-reference/midnight-indexer/types/objects/terms-and-conditions-change.md): Terms and Conditions change record for history queries. - [TransactionFees](/api-reference/midnight-indexer/types/objects/transaction-fees.md): Fees information for a transaction, including both paid and estimated fees. - [TransactionResult](/api-reference/midnight-indexer/types/objects/transaction-result.md): The result of applying a transaction to the ledger state. In case of a partial success (status), - [UnshieldedTransaction](/api-reference/midnight-indexer/types/objects/unshielded-transaction.md): A transaction that created and/or spent UTXOs alongside these and other information. - [UnshieldedTransactionsProgress](/api-reference/midnight-indexer/types/objects/unshielded-transactions-progress.md): Information about the unshielded indexing progress. - [UnshieldedUtxo](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md): Represents an unshielded UTXO. - [ZswapLedgerEvent](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md): A zswap related ledger event. - [Boolean](/api-reference/midnight-indexer/types/scalars/boolean.md): The Boolean scalar type represents true or false. - [CardanoRewardAddress](/api-reference/midnight-indexer/types/scalars/cardano-reward-address.md): No description - [DustAddress](/api-reference/midnight-indexer/types/scalars/dust-address.md): No description - [Float](/api-reference/midnight-indexer/types/scalars/float.md): The Float scalar type represents signed double-precision fractional values as specified by IEEE 754. - [HexEncoded](/api-reference/midnight-indexer/types/scalars/hex-encoded.md): No description - [Int](/api-reference/midnight-indexer/types/scalars/int.md): The Int scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. - [String](/api-reference/midnight-indexer/types/scalars/string.md): The String scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. - [Unit](/api-reference/midnight-indexer/types/scalars/unit.md): No description - [UnshieldedAddress](/api-reference/midnight-indexer/types/scalars/unshielded-address.md): No description - [ViewingKey](/api-reference/midnight-indexer/types/scalars/viewing-key.md): No description - [ShieldedTransactionsEvent](/api-reference/midnight-indexer/types/unions/shielded-transactions-event.md): An event of the shielded transactions subscription. - [UnshieldedTransactionsEvent](/api-reference/midnight-indexer/types/unions/unshielded-transactions-event.md): An event of the unshielded transactions subscription. ### midnight-js Midnight.js API Reference v4.0.4 - [Midnight JS API](/api-reference/midnight-js.md): Midnight.js API Reference v4.0.4 - [midnight-js](/api-reference/midnight-js/@midnight-ntwrk/midnight-js.md): Midnight.js API Reference v4.0.4 - [midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md): Midnight.js API Reference v4.0.4 - [CallTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/CallTxFailedError.md): Midnight.js API Reference v4.0.4 - [ContractTypeError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/ContractTypeError.md): Midnight.js API Reference v4.0.4 - [DeployTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/DeployTxFailedError.md): Midnight.js API Reference v4.0.4 - [IncompleteCallTxPrivateStateConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/IncompleteCallTxPrivateStateConfig.md): Midnight.js API Reference v4.0.4 - [IncompleteFindContractPrivateStateConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/IncompleteFindContractPrivateStateConfig.md): Midnight.js API Reference v4.0.4 - [InsertVerifierKeyTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/InsertVerifierKeyTxFailedError.md): Midnight.js API Reference v4.0.4 - [RemoveVerifierKeyTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/RemoveVerifierKeyTxFailedError.md): Midnight.js API Reference v4.0.4 - [ReplaceMaintenanceAuthorityTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/ReplaceMaintenanceAuthorityTxFailedError.md): Midnight.js API Reference v4.0.4 - [TxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md): Midnight.js API Reference v4.0.4 - [createCallTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCallTxOptions.md): Midnight.js API Reference v4.0.4 - [createCircuitCallTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCircuitCallTxInterface.md): Midnight.js API Reference v4.0.4 - [createCircuitMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCircuitMaintenanceTxInterface.md): Midnight.js API Reference v4.0.4 - [createCircuitMaintenanceTxInterfaces](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCircuitMaintenanceTxInterfaces.md): Midnight.js API Reference v4.0.4 - [createContractMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createContractMaintenanceTxInterface.md): Midnight.js API Reference v4.0.4 - [createUnprovenCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenCallTx.md): Midnight.js API Reference v4.0.4 - [createUnprovenCallTxFromInitialStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenCallTxFromInitialStates.md): Midnight.js API Reference v4.0.4 - [createUnprovenDeployTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenDeployTx.md): Midnight.js API Reference v4.0.4 - [createUnprovenDeployTxFromVerifierKeys](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenDeployTxFromVerifierKeys.md): Midnight.js API Reference v4.0.4 - [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md): Midnight.js API Reference v4.0.4 - [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md): Midnight.js API Reference v4.0.4 - [getPublicStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/getPublicStates.md): Midnight.js API Reference v4.0.4 - [getStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/getStates.md): Midnight.js API Reference v4.0.4 - [getUnshieldedBalances](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/getUnshieldedBalances.md): Midnight.js API Reference v4.0.4 - [submitCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitCallTx.md): Midnight.js API Reference v4.0.4 - [submitCallTxAsync](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitCallTxAsync.md): Midnight.js API Reference v4.0.4 - [submitDeployTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitDeployTx.md): Midnight.js API Reference v4.0.4 - [submitInsertVerifierKeyTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitInsertVerifierKeyTx.md): Midnight.js API Reference v4.0.4 - [submitRemoveVerifierKeyTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitRemoveVerifierKeyTx.md): Midnight.js API Reference v4.0.4 - [submitReplaceAuthorityTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitReplaceAuthorityTx.md): Midnight.js API Reference v4.0.4 - [submitTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTx.md): Midnight.js API Reference v4.0.4 - [submitTxAsync](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTxAsync.md): Midnight.js API Reference v4.0.4 - [verifierKeysEqual](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/verifierKeysEqual.md): Midnight.js API Reference v4.0.4 - [verifyContractState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/verifyContractState.md): Midnight.js API Reference v4.0.4 - [ContractMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/ContractMaintenanceTxInterface.md): Midnight.js API Reference v4.0.4 - [TransactionContext](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/TransactionContext.md): Midnight.js API Reference v4.0.4 - [CallOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptions.md): Midnight.js API Reference v4.0.4 - [CallOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsBase.md): Midnight.js API Reference v4.0.4 - [CallOptionsProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsProviderDataDependencies.md): Midnight.js API Reference v4.0.4 - [CallOptionsWithArguments](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithArguments.md): Midnight.js API Reference v4.0.4 - [CallOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithPrivateState.md): Midnight.js API Reference v4.0.4 - [CallOptionsWithProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithProviderDataDependencies.md): Midnight.js API Reference v4.0.4 - [CallResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md): Midnight.js API Reference v4.0.4 - [CallResultPrivate](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResultPrivate.md): Midnight.js API Reference v4.0.4 - [CallResultPublic](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResultPublic.md): Midnight.js API Reference v4.0.4 - [CallTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptions.md): Midnight.js API Reference v4.0.4 - [CallTxOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsBase.md): Midnight.js API Reference v4.0.4 - [CallTxOptionsWithPrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsWithPrivateStateId.md): Midnight.js API Reference v4.0.4 - [CircuitCallTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitCallTxInterface.md): Midnight.js API Reference v4.0.4 - [CircuitMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md): Midnight.js API Reference v4.0.4 - [CircuitMaintenanceTxInterfaces](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterfaces.md): Midnight.js API Reference v4.0.4 - [ContractConstructorOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptions.md): Midnight.js API Reference v4.0.4 - [ContractConstructorOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsBase.md): Midnight.js API Reference v4.0.4 - [ContractConstructorOptionsProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsProviderDataDependencies.md): Midnight.js API Reference v4.0.4 - [ContractConstructorOptionsWithArguments](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithArguments.md): Midnight.js API Reference v4.0.4 - [ContractConstructorOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithPrivateState.md): Midnight.js API Reference v4.0.4 - [ContractConstructorOptionsWithProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithProviderDataDependencies.md): Midnight.js API Reference v4.0.4 - [ContractConstructorResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorResult.md): Midnight.js API Reference v4.0.4 - [ContractProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md): Midnight.js API Reference v4.0.4 - [ContractStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md): Midnight.js API Reference v4.0.4 - [DeployContractOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptions.md): Midnight.js API Reference v4.0.4 - [DeployContractOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsBase.md): Midnight.js API Reference v4.0.4 - [DeployContractOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsWithPrivateState.md): Midnight.js API Reference v4.0.4 - [DeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md): Midnight.js API Reference v4.0.4 - [DeployTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptions.md): Midnight.js API Reference v4.0.4 - [DeployTxOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md): Midnight.js API Reference v4.0.4 - [DeployTxOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md): Midnight.js API Reference v4.0.4 - [DeployTxOptionsWithPrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateStateId.md): Midnight.js API Reference v4.0.4 - [FinalizedCallTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md): Midnight.js API Reference v4.0.4 - [FinalizedDeployTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md): Midnight.js API Reference v4.0.4 - [FinalizedDeployTxDataBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxDataBase.md): Midnight.js API Reference v4.0.4 - [FindDeployedContractOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptions.md): Midnight.js API Reference v4.0.4 - [FindDeployedContractOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsBase.md): Midnight.js API Reference v4.0.4 - [FindDeployedContractOptionsExistingPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsExistingPrivateState.md): Midnight.js API Reference v4.0.4 - [FindDeployedContractOptionsStorePrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsStorePrivateState.md): Midnight.js API Reference v4.0.4 - [FoundContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md): Midnight.js API Reference v4.0.4 - [PublicContractStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md): Midnight.js API Reference v4.0.4 - [ScopedTransactionOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ScopedTransactionOptions.md): Midnight.js API Reference v4.0.4 - [SubmittedCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmittedCallTx.md): Midnight.js API Reference v4.0.4 - [SubmitTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxOptions.md): Midnight.js API Reference v4.0.4 - [SubmitTxProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxProviders.md): Midnight.js API Reference v4.0.4 - [UnprovenCallTxProvidersBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersBase.md): Midnight.js API Reference v4.0.4 - [UnprovenCallTxProvidersWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersWithPrivateState.md): Midnight.js API Reference v4.0.4 - [UnprovenDeployTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenDeployTxOptions.md): Midnight.js API Reference v4.0.4 - [UnprovenDeployTxProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenDeployTxProviders.md): Midnight.js API Reference v4.0.4 - [UnsubmittedCallTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md): Midnight.js API Reference v4.0.4 - [UnsubmittedDeployTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md): Midnight.js API Reference v4.0.4 - [UnsubmittedDeployTxDataBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxDataBase.md): Midnight.js API Reference v4.0.4 - [UnsubmittedDeployTxPrivateData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxPrivateData.md): Midnight.js API Reference v4.0.4 - [UnsubmittedDeployTxPublicData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxPublicData.md): Midnight.js API Reference v4.0.4 - [UnsubmittedTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedTxData.md): Midnight.js API Reference v4.0.4 - [withContractScopedTransaction](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/variables/withContractScopedTransaction.md): Midnight.js API Reference v4.0.4 - [midnight-js-dapp-connector-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider.md): Midnight.js API Reference v4.0.4 - [dappConnectorProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/functions/dappConnectorProofProvider.md): Midnight.js API Reference v4.0.4 - [dappConnectorProvingProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/functions/dappConnectorProvingProvider.md): Midnight.js API Reference v4.0.4 - [DAppConnectorProvingAPI](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/type-aliases/DAppConnectorProvingAPI.md): Midnight.js API Reference v4.0.4 - [midnight-js-fetch-zk-config-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-fetch-zk-config-provider.md): Midnight.js API Reference v4.0.4 - [FetchZkConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-fetch-zk-config-provider/classes/FetchZkConfigProvider.md): Midnight.js API Reference v4.0.4 - [midnight-js-http-client-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md): Midnight.js API Reference v4.0.4 - [httpClientProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/functions/httpClientProofProvider.md): Midnight.js API Reference v4.0.4 - [httpClientProvingProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/functions/httpClientProvingProvider.md): Midnight.js API Reference v4.0.4 - [ProvingProviderConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/interfaces/ProvingProviderConfig.md): Midnight.js API Reference v4.0.4 - [DEFAULT_CONFIG](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/variables/DEFAULT_CONFIG.md): Midnight.js API Reference v4.0.4 - [DEFAULT_TIMEOUT](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/variables/DEFAULT_TIMEOUT.md): Midnight.js API Reference v4.0.4 - [midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md): Midnight.js API Reference v4.0.4 - [IndexerFormattedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/classes/IndexerFormattedError.md): Midnight.js API Reference v4.0.4 - [indexerPublicDataProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/indexerPublicDataProvider.md): Midnight.js API Reference v4.0.4 - [isRegularTransaction](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/isRegularTransaction.md): Midnight.js API Reference v4.0.4 - [toSegmentStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toSegmentStatus.md): Midnight.js API Reference v4.0.4 - [toSegmentStatusMap](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toSegmentStatusMap.md): Midnight.js API Reference v4.0.4 - [toTxStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toTxStatus.md): Midnight.js API Reference v4.0.4 - [toUnshieldedBalances](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toUnshieldedBalances.md): Midnight.js API Reference v4.0.4 - [toUnshieldedUtxos](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toUnshieldedUtxos.md): Midnight.js API Reference v4.0.4 - [IndexerUtxo](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/type-aliases/IndexerUtxo.md): Midnight.js API Reference v4.0.4 - [midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md): Midnight.js API Reference v4.0.4 - [StorageEncryption](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/classes/StorageEncryption.md): Midnight.js API Reference v4.0.4 - [decryptValue](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/functions/decryptValue.md): Midnight.js API Reference v4.0.4 - [levelPrivateStateProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/functions/levelPrivateStateProvider.md): Midnight.js API Reference v4.0.4 - [migrateToAccountScoped](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/functions/migrateToAccountScoped.md): Midnight.js API Reference v4.0.4 - [CryptoBackend](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/CryptoBackend.md): Midnight.js API Reference v4.0.4 - [LevelPrivateStateProviderConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/LevelPrivateStateProviderConfig.md): Midnight.js API Reference v4.0.4 - [MigrationResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/MigrationResult.md): Midnight.js API Reference v4.0.4 - [PasswordRotationOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/PasswordRotationOptions.md): Midnight.js API Reference v4.0.4 - [PasswordRotationResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/PasswordRotationResult.md): Midnight.js API Reference v4.0.4 - [StorageEncryptionOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/StorageEncryptionOptions.md): Midnight.js API Reference v4.0.4 - [CryptoBackendType](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/CryptoBackendType.md): Midnight.js API Reference v4.0.4 - [DatabaseLevel](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/DatabaseLevel.md): Midnight.js API Reference v4.0.4 - [LevelFactory](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/LevelFactory.md): Midnight.js API Reference v4.0.4 - [PrivateStoragePasswordProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/PrivateStoragePasswordProvider.md): Midnight.js API Reference v4.0.4 - [DEFAULT_CONFIG](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/variables/DEFAULT_CONFIG.md): Midnight.js API Reference v4.0.4 - [midnight-js-logger-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-logger-provider.md): Midnight.js API Reference v4.0.4 - [LoggerProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-logger-provider/classes/LoggerProvider.md): Midnight.js API Reference v4.0.4 - [midnight-js-network-id](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id.md): Midnight.js API Reference v4.0.4 - [getNetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/functions/getNetworkId.md): Midnight.js API Reference v4.0.4 - [setNetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/functions/setNetworkId.md): Midnight.js API Reference v4.0.4 - [NetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/type-aliases/NetworkId.md): Midnight.js API Reference v4.0.4 - [midnight-js-node-zk-config-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-node-zk-config-provider.md): Midnight.js API Reference v4.0.4 - [NodeZkConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-node-zk-config-provider/classes/NodeZkConfigProvider.md): Midnight.js API Reference v4.0.4 - [midnight-js-protocol](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-protocol.md): Midnight.js API Reference v4.0.4 - [midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md): Midnight.js API Reference v4.0.4 - [ExportDecryptionError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ExportDecryptionError.md): Midnight.js API Reference v4.0.4 - [ImportConflictError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ImportConflictError.md): Midnight.js API Reference v4.0.4 - [InvalidExportFormatError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/InvalidExportFormatError.md): Midnight.js API Reference v4.0.4 - [InvalidProtocolSchemeError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/InvalidProtocolSchemeError.md): Midnight.js API Reference v4.0.4 - [PrivateStateExportError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateExportError.md): Midnight.js API Reference v4.0.4 - [PrivateStateImportError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md): Midnight.js API Reference v4.0.4 - [SigningKeyExportError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/SigningKeyExportError.md): Midnight.js API Reference v4.0.4 - [ZKConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ZKConfigProvider.md): Midnight.js API Reference v4.0.4 - [LogLevel](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/enumerations/LogLevel.md): Midnight.js API Reference v4.0.4 - [asContractAddress](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/asContractAddress.md): Midnight.js API Reference v4.0.4 - [asEffectOption](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/asEffectOption.md): Midnight.js API Reference v4.0.4 - [createProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createProofProvider.md): Midnight.js API Reference v4.0.4 - [createProverKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createProverKey.md): Midnight.js API Reference v4.0.4 - [createVerifierKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createVerifierKey.md): Midnight.js API Reference v4.0.4 - [createZKIR](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createZKIR.md): Midnight.js API Reference v4.0.4 - [zkConfigToProvingKeyMaterial](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/zkConfigToProvingKeyMaterial.md): Midnight.js API Reference v4.0.4 - [ExportPrivateStatesOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ExportPrivateStatesOptions.md): Midnight.js API Reference v4.0.4 - [ExportSigningKeysOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ExportSigningKeysOptions.md): Midnight.js API Reference v4.0.4 - [FinalizedTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/FinalizedTxData.md): Midnight.js API Reference v4.0.4 - [ImportPrivateStatesOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesOptions.md): Midnight.js API Reference v4.0.4 - [ImportPrivateStatesResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesResult.md): Midnight.js API Reference v4.0.4 - [ImportSigningKeysOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysOptions.md): Midnight.js API Reference v4.0.4 - [ImportSigningKeysResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysResult.md): Midnight.js API Reference v4.0.4 - [LoggerProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/LoggerProvider.md): Midnight.js API Reference v4.0.4 - [MidnightProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/MidnightProvider.md): Midnight.js API Reference v4.0.4 - [MidnightProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/MidnightProviders.md): Midnight.js API Reference v4.0.4 - [PrivateStateExport](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateExport.md): Midnight.js API Reference v4.0.4 - [PrivateStateProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateProvider.md): Midnight.js API Reference v4.0.4 - [ProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md): Midnight.js API Reference v4.0.4 - [ProveTxConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProveTxConfig.md): Midnight.js API Reference v4.0.4 - [PublicDataProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PublicDataProvider.md): Midnight.js API Reference v4.0.4 - [SigningKeyExport](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/SigningKeyExport.md): Midnight.js API Reference v4.0.4 - [WalletProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/WalletProvider.md): Midnight.js API Reference v4.0.4 - [ZKConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ZKConfig.md): Midnight.js API Reference v4.0.4 - [All](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/All.md): Midnight.js API Reference v4.0.4 - [AnyPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/AnyPrivateState.md): Midnight.js API Reference v4.0.4 - [AnyProvableCircuitId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/AnyProvableCircuitId.md): Midnight.js API Reference v4.0.4 - [BlockHash](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHash.md): Midnight.js API Reference v4.0.4 - [BlockHashConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHashConfig.md): Midnight.js API Reference v4.0.4 - [BlockHeightConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHeightConfig.md): Midnight.js API Reference v4.0.4 - [ContractExecutableRuntimeOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractExecutableRuntimeOptions.md): Midnight.js API Reference v4.0.4 - [ContractStateObservableConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractStateObservableConfig.md): Midnight.js API Reference v4.0.4 - [Fees](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/Fees.md): Midnight.js API Reference v4.0.4 - [KeyMaterialProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/KeyMaterialProvider.md): Midnight.js API Reference v4.0.4 - [Latest](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/Latest.md): Midnight.js API Reference v4.0.4 - [PrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateId.md): Midnight.js API Reference v4.0.4 - [PrivateStateImportErrorCause](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md): Midnight.js API Reference v4.0.4 - [ProverKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md): Midnight.js API Reference v4.0.4 - [SegmentStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/SegmentStatus.md): Midnight.js API Reference v4.0.4 - [TxIdConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/TxIdConfig.md): Midnight.js API Reference v4.0.4 - [TxStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/TxStatus.md): Midnight.js API Reference v4.0.4 - [UnboundTransaction](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnboundTransaction.md): Midnight.js API Reference v4.0.4 - [UnshieldedBalance](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalance.md): Midnight.js API Reference v4.0.4 - [UnshieldedBalances](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md): Midnight.js API Reference v4.0.4 - [UnshieldedUtxo](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxo.md): Midnight.js API Reference v4.0.4 - [UnshieldedUtxos](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxos.md): Midnight.js API Reference v4.0.4 - [VerifierKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md): Midnight.js API Reference v4.0.4 - [ZKIR](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md): Midnight.js API Reference v4.0.4 - [exitResultOrError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/exitResultOrError.md): Midnight.js API Reference v4.0.4 - [FailEntirely](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/FailEntirely.md): Midnight.js API Reference v4.0.4 - [FailFallible](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/FailFallible.md): Midnight.js API Reference v4.0.4 - [makeContractExecutableRuntime](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/makeContractExecutableRuntime.md): Midnight.js API Reference v4.0.4 - [MAX_EXPORT_SIGNING_KEYS](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/MAX_EXPORT_SIGNING_KEYS.md): Midnight.js API Reference v4.0.4 - [MAX_EXPORT_STATES](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/MAX_EXPORT_STATES.md): Midnight.js API Reference v4.0.4 - [SegmentFail](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SegmentFail.md): Midnight.js API Reference v4.0.4 - [SegmentSuccess](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SegmentSuccess.md): Midnight.js API Reference v4.0.4 - [SucceedEntirely](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SucceedEntirely.md): Midnight.js API Reference v4.0.4 - [midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md): Midnight.js API Reference v4.0.4 - [assertDefined](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertDefined.md): Midnight.js API Reference v4.0.4 - [assertIsContractAddress](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertIsContractAddress.md): Midnight.js API Reference v4.0.4 - [assertIsHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertIsHex.md): Midnight.js API Reference v4.0.4 - [assertSafeName](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertSafeName.md): Midnight.js API Reference v4.0.4 - [assertSemVer](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertSemVer.md): Midnight.js API Reference v4.0.4 - [assertUndefined](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertUndefined.md): Midnight.js API Reference v4.0.4 - [fromHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/fromHex.md): Midnight.js API Reference v4.0.4 - [isHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/isHex.md): Midnight.js API Reference v4.0.4 - [parseCoinPublicKeyToHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/parseCoinPublicKeyToHex.md): Midnight.js API Reference v4.0.4 - [parseEncPublicKeyToHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/parseEncPublicKeyToHex.md): Midnight.js API Reference v4.0.4 - [parseHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/parseHex.md): Midnight.js API Reference v4.0.4 - [toHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/toHex.md): Midnight.js API Reference v4.0.4 - [ttlOneHour](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/ttlOneHour.md): Midnight.js API Reference v4.0.4 - [ParsedHexString](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/type-aliases/ParsedHexString.md): Midnight.js API Reference v4.0.4 - [MAX_SAFE_NAME_LENGTH](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/variables/MAX_SAFE_NAME_LENGTH.md): Midnight.js API Reference v4.0.4 - [packages](/api-reference/midnight-js/packages.md): Midnight.js API Reference v4.0.4 ### onchain-runtime @midnight-ntwrk/onchain-runtime v3.0.0 - [Onchain Runtime API](/api-reference/onchain-runtime.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ChargedState](/api-reference/onchain-runtime/classes/ChargedState.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CoinSecretKey](/api-reference/onchain-runtime/classes/CoinSecretKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ContractMaintenanceAuthority](/api-reference/onchain-runtime/classes/ContractMaintenanceAuthority.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ContractOperation](/api-reference/onchain-runtime/classes/ContractOperation.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ContractState](/api-reference/onchain-runtime/classes/ContractState.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CostModel](/api-reference/onchain-runtime/classes/CostModel.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [QueryContext](/api-reference/onchain-runtime/classes/QueryContext.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [QueryResults](/api-reference/onchain-runtime/classes/QueryResults.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [StateBoundedMerkleTree](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [StateMap](/api-reference/onchain-runtime/classes/StateMap.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [StateValue](/api-reference/onchain-runtime/classes/StateValue.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [VmResults](/api-reference/onchain-runtime/classes/VmResults.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [VmStack](/api-reference/onchain-runtime/classes/VmStack.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [bigIntModFr](/api-reference/onchain-runtime/functions/bigIntModFr.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [bigIntToValue](/api-reference/onchain-runtime/functions/bigIntToValue.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [communicationCommitment](/api-reference/onchain-runtime/functions/communicationCommitment.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [communicationCommitmentRandomness](/api-reference/onchain-runtime/functions/communicationCommitmentRandomness.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [decodeCoinPublicKey](/api-reference/onchain-runtime/functions/decodeCoinPublicKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [decodeContractAddress](/api-reference/onchain-runtime/functions/decodeContractAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [decodeQualifiedShieldedCoinInfo](/api-reference/onchain-runtime/functions/decodeQualifiedShieldedCoinInfo.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [decodeRawTokenType](/api-reference/onchain-runtime/functions/decodeRawTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [decodeShieldedCoinInfo](/api-reference/onchain-runtime/functions/decodeShieldedCoinInfo.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [decodeUserAddress](/api-reference/onchain-runtime/functions/decodeUserAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [degradeToTransient](/api-reference/onchain-runtime/functions/degradeToTransient.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [dummyContractAddress](/api-reference/onchain-runtime/functions/dummyContractAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [dummyUserAddress](/api-reference/onchain-runtime/functions/dummyUserAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ecAdd](/api-reference/onchain-runtime/functions/ecAdd.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ecMul](/api-reference/onchain-runtime/functions/ecMul.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ecMulGenerator](/api-reference/onchain-runtime/functions/ecMulGenerator.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [encodeCoinPublicKey](/api-reference/onchain-runtime/functions/encodeCoinPublicKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [encodeContractAddress](/api-reference/onchain-runtime/functions/encodeContractAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [encodeQualifiedShieldedCoinInfo](/api-reference/onchain-runtime/functions/encodeQualifiedShieldedCoinInfo.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [encodeRawTokenType](/api-reference/onchain-runtime/functions/encodeRawTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [encodeShieldedCoinInfo](/api-reference/onchain-runtime/functions/encodeShieldedCoinInfo.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [encodeUserAddress](/api-reference/onchain-runtime/functions/encodeUserAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [entryPointHash](/api-reference/onchain-runtime/functions/entryPointHash.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [hashToCurve](/api-reference/onchain-runtime/functions/hashToCurve.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [leafHash](/api-reference/onchain-runtime/functions/leafHash.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [maxAlignedSize](/api-reference/onchain-runtime/functions/maxAlignedSize.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [maxField](/api-reference/onchain-runtime/functions/maxField.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [persistentCommit](/api-reference/onchain-runtime/functions/persistentCommit.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [persistentHash](/api-reference/onchain-runtime/functions/persistentHash.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [proofDataIntoSerializedPreimage](/api-reference/onchain-runtime/functions/proofDataIntoSerializedPreimage.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [rawTokenType](/api-reference/onchain-runtime/functions/rawTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [runProgram](/api-reference/onchain-runtime/functions/runProgram.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [runtimeCoinCommitment](/api-reference/onchain-runtime/functions/runtimeCoinCommitment.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [runtimeCoinNullifier](/api-reference/onchain-runtime/functions/runtimeCoinNullifier.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [sampleContractAddress](/api-reference/onchain-runtime/functions/sampleContractAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [sampleRawTokenType](/api-reference/onchain-runtime/functions/sampleRawTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [sampleSigningKey](/api-reference/onchain-runtime/functions/sampleSigningKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [sampleUserAddress](/api-reference/onchain-runtime/functions/sampleUserAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [signatureVerifyingKey](/api-reference/onchain-runtime/functions/signatureVerifyingKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [signData](/api-reference/onchain-runtime/functions/signData.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [signingKeyFromBip340](/api-reference/onchain-runtime/functions/signingKeyFromBip340.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [transientCommit](/api-reference/onchain-runtime/functions/transientCommit.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [transientHash](/api-reference/onchain-runtime/functions/transientHash.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [upgradeFromTransient](/api-reference/onchain-runtime/functions/upgradeFromTransient.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [valueToBigInt](/api-reference/onchain-runtime/functions/valueToBigInt.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [verifySignature](/api-reference/onchain-runtime/functions/verifySignature.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [globals](/api-reference/onchain-runtime/globals.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Alignment](/api-reference/onchain-runtime/type-aliases/Alignment.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [AlignmentAtom](/api-reference/onchain-runtime/type-aliases/AlignmentAtom.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [AlignmentSegment](/api-reference/onchain-runtime/type-aliases/AlignmentSegment.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [BlockContext](/api-reference/onchain-runtime/type-aliases/BlockContext.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CallContext](/api-reference/onchain-runtime/type-aliases/CallContext.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CoinCommitment](/api-reference/onchain-runtime/type-aliases/CoinCommitment.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CoinPublicKey](/api-reference/onchain-runtime/type-aliases/CoinPublicKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CommunicationCommitment](/api-reference/onchain-runtime/type-aliases/CommunicationCommitment.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [CommunicationCommitmentRand](/api-reference/onchain-runtime/type-aliases/CommunicationCommitmentRand.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ContractAddress](/api-reference/onchain-runtime/type-aliases/ContractAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [DomainSeparator](/api-reference/onchain-runtime/type-aliases/DomainSeparator.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [DustTokenType](/api-reference/onchain-runtime/type-aliases/DustTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Effects](/api-reference/onchain-runtime/type-aliases/Effects.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [EncodedStateValue](/api-reference/onchain-runtime/type-aliases/EncodedStateValue.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [FeePrices](/api-reference/onchain-runtime/type-aliases/FeePrices.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Fr](/api-reference/onchain-runtime/type-aliases/Fr.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [GatherResult](/api-reference/onchain-runtime/type-aliases/GatherResult.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Key](/api-reference/onchain-runtime/type-aliases/Key.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Nonce](/api-reference/onchain-runtime/type-aliases/Nonce.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Nullifier](/api-reference/onchain-runtime/type-aliases/Nullifier.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Op](/api-reference/onchain-runtime/type-aliases/Op.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [PublicAddress](/api-reference/onchain-runtime/type-aliases/PublicAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [QualifiedShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [RawTokenType](/api-reference/onchain-runtime/type-aliases/RawTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [RunningCost](/api-reference/onchain-runtime/type-aliases/RunningCost.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [ShieldedTokenType](/api-reference/onchain-runtime/type-aliases/ShieldedTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Signature](/api-reference/onchain-runtime/type-aliases/Signature.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [SignatureVerifyingKey](/api-reference/onchain-runtime/type-aliases/SignatureVerifyingKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [SigningKey](/api-reference/onchain-runtime/type-aliases/SigningKey.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [TokenType](/api-reference/onchain-runtime/type-aliases/TokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Transcript](/api-reference/onchain-runtime/type-aliases/Transcript.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [UnshieldedTokenType](/api-reference/onchain-runtime/type-aliases/UnshieldedTokenType.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [UserAddress](/api-reference/onchain-runtime/type-aliases/UserAddress.md): @midnight-ntwrk/onchain-runtime v3.0.0 - [Value](/api-reference/onchain-runtime/type-aliases/Value.md): @midnight-ntwrk/onchain-runtime v3.0.0 ### overview - [Authentication](/api-reference/overview/authentication.md): Learn about the authentication methods for deploying and interacting with smart contracts in Midnight. - [Usage limits](/api-reference/overview/usage-limits.md): Learn about the usage limits for transactions and other API calls. ### tags - [Tags](/api-reference/tags.md) - [4 docs tagged with "api reference"](/api-reference/tags/api-reference.md) - [One doc tagged with "authentication"](/api-reference/tags/authentication.md) - [One doc tagged with "dapp connector"](/api-reference/tags/dapp-connector.md) - [4 docs tagged with "error reference"](/api-reference/tags/error-reference.md) - [One doc tagged with "indexer"](/api-reference/tags/indexer.md) - [One doc tagged with "ledger"](/api-reference/tags/ledger.md) - [One doc tagged with "proof server"](/api-reference/tags/proof-server.md) - [One doc tagged with "usage limits"](/api-reference/tags/usage-limits.md) ### testkit-js @midnight-ntwrk/testkit-js v4.0.4 - [Testkit JS API](/api-reference/testkit-js.md): @midnight-ntwrk/testkit-js v4.0.4 - [DAppConnectorInitialAPI](/api-reference/testkit-js/classes/DAppConnectorInitialAPI.md): @midnight-ntwrk/testkit-js v4.0.4 - [DAppConnectorWalletAdapter](/api-reference/testkit-js/classes/DAppConnectorWalletAdapter.md): @midnight-ntwrk/testkit-js v4.0.4 - [DynamicProofServerContainer](/api-reference/testkit-js/classes/DynamicProofServerContainer.md): @midnight-ntwrk/testkit-js v4.0.4 - [EnvVarRemoteTestEnvironment](/api-reference/testkit-js/classes/EnvVarRemoteTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [FaucetClient](/api-reference/testkit-js/classes/FaucetClient.md): @midnight-ntwrk/testkit-js v4.0.4 - [FluentWalletBuilder](/api-reference/testkit-js/classes/FluentWalletBuilder.md): @midnight-ntwrk/testkit-js v4.0.4 - [GzipFile](/api-reference/testkit-js/classes/GzipFile.md): @midnight-ntwrk/testkit-js v4.0.4 - [IndexerClient](/api-reference/testkit-js/classes/IndexerClient.md): @midnight-ntwrk/testkit-js v4.0.4 - [LocalTestConfiguration](/api-reference/testkit-js/classes/LocalTestConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [LocalTestEnvironment](/api-reference/testkit-js/classes/LocalTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [MidnightWalletProvider](/api-reference/testkit-js/classes/MidnightWalletProvider.md): @midnight-ntwrk/testkit-js v4.0.4 - [NodeClient](/api-reference/testkit-js/classes/NodeClient.md): @midnight-ntwrk/testkit-js v4.0.4 - [PreprodTestEnvironment](/api-reference/testkit-js/classes/PreprodTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [PreviewTestEnvironment](/api-reference/testkit-js/classes/PreviewTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [ProofServerClient](/api-reference/testkit-js/classes/ProofServerClient.md): @midnight-ntwrk/testkit-js v4.0.4 - [QanetTestEnvironment](/api-reference/testkit-js/classes/QanetTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [RemoteTestEnvironment](/api-reference/testkit-js/classes/RemoteTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [StaticProofServerContainer](/api-reference/testkit-js/classes/StaticProofServerContainer.md): @midnight-ntwrk/testkit-js v4.0.4 - [TestEnvironment](/api-reference/testkit-js/classes/TestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [WalletFactory](/api-reference/testkit-js/classes/WalletFactory.md): @midnight-ntwrk/testkit-js v4.0.4 - [WalletSaveStateProvider](/api-reference/testkit-js/classes/WalletSaveStateProvider.md): @midnight-ntwrk/testkit-js v4.0.4 - [WalletSeeds](/api-reference/testkit-js/classes/WalletSeeds.md): @midnight-ntwrk/testkit-js v4.0.4 - [buildUrlWithPath](/api-reference/testkit-js/functions/buildUrlWithPath.md): @midnight-ntwrk/testkit-js v4.0.4 - [createDefaultTestLogger](/api-reference/testkit-js/functions/createDefaultTestLogger.md): @midnight-ntwrk/testkit-js v4.0.4 - [createLogger](/api-reference/testkit-js/functions/createLogger.md): @midnight-ntwrk/testkit-js v4.0.4 - [delay](/api-reference/testkit-js/functions/delay.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectFoundAndDeployedStatesEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedStatesEqual.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectFoundAndDeployedTxDataEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedTxDataEqual.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectFoundAndDeployedTxPrivateDataEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedTxPrivateDataEqual.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectFoundAndDeployedTxPublicDataEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedTxPublicDataEqual.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectSuccessfulCallTx](/api-reference/testkit-js/functions/expectSuccessfulCallTx.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectSuccessfulDeployTx](/api-reference/testkit-js/functions/expectSuccessfulDeployTx.md): @midnight-ntwrk/testkit-js v4.0.4 - [expectSuccessfulTxData](/api-reference/testkit-js/functions/expectSuccessfulTxData.md): @midnight-ntwrk/testkit-js v4.0.4 - [getContainersConfiguration](/api-reference/testkit-js/functions/getContainersConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [getDustSeed](/api-reference/testkit-js/functions/getDustSeed.md): @midnight-ntwrk/testkit-js v4.0.4 - [getInitialShieldedState](/api-reference/testkit-js/functions/getInitialShieldedState.md): @midnight-ntwrk/testkit-js v4.0.4 - [getInitialState](/api-reference/testkit-js/functions/getInitialState.md): @midnight-ntwrk/testkit-js v4.0.4 - [getInitialUnshieldedState](/api-reference/testkit-js/functions/getInitialUnshieldedState.md): @midnight-ntwrk/testkit-js v4.0.4 - [getShieldedSeed](/api-reference/testkit-js/functions/getShieldedSeed.md): @midnight-ntwrk/testkit-js v4.0.4 - [getTestEnvironment](/api-reference/testkit-js/functions/getTestEnvironment.md): @midnight-ntwrk/testkit-js v4.0.4 - [getUnshieldedSeed](/api-reference/testkit-js/functions/getUnshieldedSeed.md): @midnight-ntwrk/testkit-js v4.0.4 - [getWalletStateFilename](/api-reference/testkit-js/functions/getWalletStateFilename.md): @midnight-ntwrk/testkit-js v4.0.4 - [initializeMidnightProviders](/api-reference/testkit-js/functions/initializeMidnightProviders.md): @midnight-ntwrk/testkit-js v4.0.4 - [inMemoryPrivateStateProvider](/api-reference/testkit-js/functions/inMemoryPrivateStateProvider.md): @midnight-ntwrk/testkit-js v4.0.4 - [setContainersConfiguration](/api-reference/testkit-js/functions/setContainersConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [stateValueEqual](/api-reference/testkit-js/functions/stateValueEqual.md): @midnight-ntwrk/testkit-js v4.0.4 - [syncWallet](/api-reference/testkit-js/functions/syncWallet.md): @midnight-ntwrk/testkit-js v4.0.4 - [txsEqual](/api-reference/testkit-js/functions/txsEqual.md): @midnight-ntwrk/testkit-js v4.0.4 - [waitForFunds](/api-reference/testkit-js/functions/waitForFunds.md): @midnight-ntwrk/testkit-js v4.0.4 - [globals](/api-reference/testkit-js/globals.md): @midnight-ntwrk/testkit-js v4.0.4 - [ContainerEndpoints](/api-reference/testkit-js/interfaces/ContainerEndpoints.md): @midnight-ntwrk/testkit-js v4.0.4 - [ContainersConfiguration](/api-reference/testkit-js/interfaces/ContainersConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [ContractConfiguration](/api-reference/testkit-js/interfaces/ContractConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [DustWalletOptions](/api-reference/testkit-js/interfaces/DustWalletOptions.md): @midnight-ntwrk/testkit-js v4.0.4 - [EnvironmentConfiguration](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [LogConfiguration](/api-reference/testkit-js/interfaces/LogConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [ProofServerContainer](/api-reference/testkit-js/interfaces/ProofServerContainer.md): @midnight-ntwrk/testkit-js v4.0.4 - [ProofServerContainerConfiguration](/api-reference/testkit-js/interfaces/ProofServerContainerConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [StandaloneContainerNames](/api-reference/testkit-js/interfaces/StandaloneContainerNames.md): @midnight-ntwrk/testkit-js v4.0.4 - [StandaloneContainersConfiguration](/api-reference/testkit-js/interfaces/StandaloneContainersConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [ComponentPortsConfiguration](/api-reference/testkit-js/type-aliases/ComponentPortsConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [DEFAULT_DUST_OPTIONS](/api-reference/testkit-js/variables/DEFAULT_DUST_OPTIONS.md): @midnight-ntwrk/testkit-js v4.0.4 - [DEFAULT_WALLET_STATE_DIRECTORY](/api-reference/testkit-js/variables/DEFAULT_WALLET_STATE_DIRECTORY.md): @midnight-ntwrk/testkit-js v4.0.4 - [defaultContainersConfiguration](/api-reference/testkit-js/variables/defaultContainersConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [latestContainersConfiguration](/api-reference/testkit-js/variables/latestContainersConfiguration.md): @midnight-ntwrk/testkit-js v4.0.4 - [logger](/api-reference/testkit-js/variables/logger.md): @midnight-ntwrk/testkit-js v4.0.4 - [MINUTE](/api-reference/testkit-js/variables/MINUTE.md): @midnight-ntwrk/testkit-js v4.0.4 - [TEST_MNEMONIC](/api-reference/testkit-js/variables/TEST_MNEMONIC.md): @midnight-ntwrk/testkit-js v4.0.4 ### wallet-sdk API reference for the Midnight Wallet SDK covering the facade, HD key derivation, address encoding, transfers, DUST management, and atomic swaps. - [Wallet SDK API Reference](/api-reference/wallet-sdk.md): API reference for the Midnight Wallet SDK covering the facade, HD key derivation, address encoding, transfers, DUST management, and atomic swaps. ### zswap @midnight/zswap v4.0.0-rc - [ZSwap API](/api-reference/zswap.md): @midnight/zswap v4.0.0-rc - [AuthorizedMint](/api-reference/zswap/classes/AuthorizedMint.md): @midnight/zswap v4.0.0-rc - [CoinSecretKey](/api-reference/zswap/classes/CoinSecretKey.md): @midnight/zswap v4.0.0-rc - [EncryptionSecretKey](/api-reference/zswap/classes/EncryptionSecretKey.md): @midnight/zswap v4.0.0-rc - [Input](/api-reference/zswap/classes/Input.md): @midnight/zswap v4.0.0-rc - [LedgerParameters](/api-reference/zswap/classes/LedgerParameters.md): @midnight/zswap v4.0.0-rc - [LocalState](/api-reference/zswap/classes/LocalState.md): @midnight/zswap v4.0.0-rc - [MerkleTreeCollapsedUpdate](/api-reference/zswap/classes/MerkleTreeCollapsedUpdate.md): @midnight/zswap v4.0.0-rc - [Offer](/api-reference/zswap/classes/Offer.md): @midnight/zswap v4.0.0-rc - [Output](/api-reference/zswap/classes/Output.md): @midnight/zswap v4.0.0-rc - [ProofErasedAuthorizedMint](/api-reference/zswap/classes/ProofErasedAuthorizedMint.md): @midnight/zswap v4.0.0-rc - [ProofErasedInput](/api-reference/zswap/classes/ProofErasedInput.md): @midnight/zswap v4.0.0-rc - [ProofErasedOffer](/api-reference/zswap/classes/ProofErasedOffer.md): @midnight/zswap v4.0.0-rc - [ProofErasedOutput](/api-reference/zswap/classes/ProofErasedOutput.md): @midnight/zswap v4.0.0-rc - [ProofErasedTransaction](/api-reference/zswap/classes/ProofErasedTransaction.md): @midnight/zswap v4.0.0-rc - [ProofErasedTransient](/api-reference/zswap/classes/ProofErasedTransient.md): @midnight/zswap v4.0.0-rc - [SecretKeys](/api-reference/zswap/classes/SecretKeys.md): @midnight/zswap v4.0.0-rc - [SystemTransaction](/api-reference/zswap/classes/SystemTransaction.md): @midnight/zswap v4.0.0-rc - [Transaction](/api-reference/zswap/classes/Transaction.md): @midnight/zswap v4.0.0-rc - [TransactionCostModel](/api-reference/zswap/classes/TransactionCostModel.md): @midnight/zswap v4.0.0-rc - [Transient](/api-reference/zswap/classes/Transient.md): @midnight/zswap v4.0.0-rc - [UnprovenAuthorizedMint](/api-reference/zswap/classes/UnprovenAuthorizedMint.md): @midnight/zswap v4.0.0-rc - [UnprovenInput](/api-reference/zswap/classes/UnprovenInput.md): @midnight/zswap v4.0.0-rc - [UnprovenOffer](/api-reference/zswap/classes/UnprovenOffer.md): @midnight/zswap v4.0.0-rc - [UnprovenOutput](/api-reference/zswap/classes/UnprovenOutput.md): @midnight/zswap v4.0.0-rc - [UnprovenTransaction](/api-reference/zswap/classes/UnprovenTransaction.md): @midnight/zswap v4.0.0-rc - [UnprovenTransient](/api-reference/zswap/classes/UnprovenTransient.md): @midnight/zswap v4.0.0-rc - [ZswapChainState](/api-reference/zswap/classes/ZswapChainState.md): @midnight/zswap v4.0.0-rc - [NetworkId](/api-reference/zswap/enumerations/NetworkId.md): @midnight/zswap v4.0.0-rc - [coinCommitment](/api-reference/zswap/functions/coinCommitment.md): @midnight/zswap v4.0.0-rc - [coinNullifier](/api-reference/zswap/functions/coinNullifier.md): @midnight/zswap v4.0.0-rc - [createCoinInfo](/api-reference/zswap/functions/createCoinInfo.md): @midnight/zswap v4.0.0-rc - [nativeToken](/api-reference/zswap/functions/nativeToken.md): @midnight/zswap v4.0.0-rc - [sampleCoinPublicKey](/api-reference/zswap/functions/sampleCoinPublicKey.md): @midnight/zswap v4.0.0-rc - [sampleContractAddress](/api-reference/zswap/functions/sampleContractAddress.md): @midnight/zswap v4.0.0-rc - [sampleEncryptionPublicKey](/api-reference/zswap/functions/sampleEncryptionPublicKey.md): @midnight/zswap v4.0.0-rc - [sampleTokenType](/api-reference/zswap/functions/sampleTokenType.md): @midnight/zswap v4.0.0-rc - [globals](/api-reference/zswap/globals.md): @midnight/zswap v4.0.0-rc - [CoinCommitment](/api-reference/zswap/type-aliases/CoinCommitment.md): @midnight/zswap v4.0.0-rc - [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md): @midnight/zswap v4.0.0-rc - [CoinPublicKey](/api-reference/zswap/type-aliases/CoinPublicKey.md): @midnight/zswap v4.0.0-rc - [ContractAddress](/api-reference/zswap/type-aliases/ContractAddress.md): @midnight/zswap v4.0.0-rc - [EncPublicKey](/api-reference/zswap/type-aliases/EncPublicKey.md): @midnight/zswap v4.0.0-rc - [Nonce](/api-reference/zswap/type-aliases/Nonce.md): @midnight/zswap v4.0.0-rc - [Nullifier](/api-reference/zswap/type-aliases/Nullifier.md): @midnight/zswap v4.0.0-rc - [QualifiedCoinInfo](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md): @midnight/zswap v4.0.0-rc - [TokenType](/api-reference/zswap/type-aliases/TokenType.md): @midnight/zswap v4.0.0-rc - [TransactionHash](/api-reference/zswap/type-aliases/TransactionHash.md): @midnight/zswap v4.0.0-rc - [TransactionId](/api-reference/zswap/type-aliases/TransactionId.md): @midnight/zswap v4.0.0-rc ## compact Midnight comes with its own programming language, Compact, which enables you to write smart contracts for the Midnight ecosystem. The Compact compiler outputs zero-knowledge circuits that are used to prove the correctness of interactions with the ledger. - [The Compact language](/compact.md): Midnight comes with its own programming language, Compact, which enables you to write smart contracts for the Midnight ecosystem. The Compact compiler outputs zero-knowledge circuits that are used to prove the correctness of interactions with the ledger. ### compilation-and-tooling - [Compact compiler usage page](/compact/compilation-and-tooling/compiler-usage.md): This is the usage page of compactc, a compiler for Compact. - [Compact command-line tool usage page](/compact/compilation-and-tooling/dev-tool-usage.md): This is the usage page of the Compact command-line tool. This tool allows the - [Compact fixup usage page](/compact/compilation-and-tooling/fixup-usage.md): This is the usage page of fixup-compact, a fix up tool for Compact. - [Compact formatter usage page](/compact/compilation-and-tooling/formatter-usage.md): This is the usage page of format-compact, a formatter for Compact. - [Neovim setup for Compact](/compact/compilation-and-tooling/neovim-setup.md): compact.vim is a community-driven plugin that provides Compact language support for Neovim. - [Visual Studio Code extension for Compact](/compact/compilation-and-tooling/vscode-plugin.md): The [Visual Studio Code extension] for Compact is a plugin ### data-types - [Ledger data types](/compact/data-types/ledger-adt.md): Compact language version 0.26.0, compiler version 0.34.0. - [Opaque data types](/compact/data-types/opaque_data.md): Data types whose representations are visible are called transparent. These expose the inner structure of the data so that operations on the data can be understood. ### reference - [Compact grammar](/compact/reference/compact-grammar.md): Compact language version 0.26.0. - [Compact keywords](/compact/reference/compact-keywords.md): Module-related keywords - [Compact reference](/compact/reference/compact-reference.md): Overview - [Explicit disclosure in Compact: The Midnight "Witness Protection Program"](/compact/reference/explicit-disclosure.md): Introduction - [Ledger data types](/compact/reference/ledger-adt.md): Compact language version 0.26.0, compiler version 0.34.0. - [Writing a contract](/compact/reference/writing.md): This page walks ### smart-contract-security Compact smart contracts on Midnight combine privacy-preserving computation with cryptographic guarantees. The compiler enforces certain rules and restrictions, but much of the responsibility for secure contract interaction is up to the developer implementing the smart contract. For this reason, it is very important for smart contract developers to understand common pitfalls and adhere to security best practices. - [Smart contract security](/compact/smart-contract-security.md): Compact smart contracts on Midnight combine privacy-preserving computation with cryptographic guarantees. The compiler enforces certain rules and restrictions, but much of the responsibility for secure contract interaction is up to the developer implementing the smart contract. For this reason, it is very important for smart contract developers to understand common pitfalls and adhere to security best practices. ### standard-library CompactStandardLibrary ∙ Detailed API reference - [Compact standard library](/compact/standard-library.md): CompactStandardLibrary ∙ Detailed API reference - [Detailed API reference](/compact/standard-library/exports.md): Top-level exports and native types and functions ### test-and-debug Learn how to test and debug Compact smart contracts. - [Test and debug](/compact/test-and-debug.md): Learn how to test and debug Compact smart contracts. ## concepts Understand the core ideas behind Midnight, including confidentiality with zero-knowledge proofs, contracts, and verifiable computation. - [Concepts](/concepts.md): Understand the core ideas behind Midnight, including confidentiality with zero-knowledge proofs, contracts, and verifiable computation. ### account A reference on the account model. - [Account model](/concepts/account.md): A reference on the account model. ### blockchain-space-tokenization Learn how blockchain space tokenization (BST) resolves the trade-off between low transaction fees and fast processing times. - [Blockchain space tokenization (BST)](/concepts/blockchain-space-tokenization.md): Learn how blockchain space tokenization (BST) resolves the trade-off between low transaction fees and fast processing times. ### dual-component-tokenomics Learn why Midnight uses a dual-component tokenomics model with NIGHT and DUST, and how it solves the limitations of single-token proof-of-stake systems. - [Dual-component tokenomics in Midnight](/concepts/dual-component-tokenomics.md): Learn why Midnight uses a dual-component tokenomics model with NIGHT and DUST, and how it solves the limitations of single-token proof-of-stake systems. ### dust-architecture A reference on the architecture of DUST and network usage. - [DUST architecture](/concepts/dust-architecture.md): A reference on the architecture of DUST and network usage. ### fully-homomorphic-encryption What is fully homomorphic encryption, how does it compare to zero-knowledge proofs, and which platforms provide it? A plain explainer. - [What is FHE (fully homomorphic encryption)?](/concepts/fully-homomorphic-encryption.md): What is fully homomorphic encryption, how does it compare to zero-knowledge proofs, and which platforms provide it? A plain explainer. ### how-midnight-works - [Building blocks](/concepts/how-midnight-works/building-blocks.md): Midnight's transaction structure is unique and may not be immediately - [Compact as a privacy-first language](/concepts/how-midnight-works/compact-privacy-first-language.md): Explains why Midnight uses its own smart contract language and how Compact treats privacy-aware circuits as first-class citizens. - [End-to-end architecture](/concepts/how-midnight-works/end-to-end-architecture.md): One diagram connecting private computation on your device to public verification on the Midnight network, and what each layer can and cannot see. - [The Impact VM](/concepts/how-midnight-works/impact.md): Impact is still under active revision. Expect its attributes, including storage-related costs, to change. - [Private data](/concepts/how-midnight-works/keeping-data-private.md): This document describes some strategies for keeping data private in - [Midnight's hybrid architecture](/concepts/how-midnight-works/midnight-combined-model.md): Midnight combines approaches to create a hybrid architecture that doesn't force you to choose between models but integrates both to maximize benefits. - [Transaction semantics](/concepts/how-midnight-works/semantics.md): Ledger states - [Smart contracts on Midnight](/concepts/how-midnight-works/smart-contracts.md): While you may have some familiarity with smart - [Zswap](/concepts/how-midnight-works/zswap.md): The details of Midnight's native currency implementation are not yet stable and will ### how-privacy-blockchains-work How privacy blockchains work, the techniques they use to protect data, and which platforms enable compliant privacy for enterprise use cases. - [How privacy blockchains work](/concepts/how-privacy-blockchains-work.md): How privacy blockchains work, the techniques they use to protect data, and which platforms enable compliant privacy for enterprise use cases. ### kachina A reference on the Kachina model. - [Kachina](/concepts/kachina.md): A reference on the Kachina model. ### ledgers A reference on the ledger model. - [Ledgers](/concepts/ledgers.md): A reference on the ledger model. ### network-architecture - [Consensus](/concepts/network-architecture/consensus.md): What blockchain consensus is, the main consensus mechanism families, and how Midnight implements it with AURA block production and GRANDPA finality. - [Cryptography](/concepts/network-architecture/cryptography.md): A reference on cryptography in Midnight nodes. - [Onchain logic and state](/concepts/network-architecture/onchain-logic.md): A reference on onchain logic and state in Midnight nodes. - [P2P networking](/concepts/network-architecture/p2p-networking.md): A reference on P2P networking in Midnight nodes. - [RPC interface](/concepts/network-architecture/rpc-networking.md): A reference on the RPC interface. - [Storage](/concepts/network-architecture/storage.md): A reference on storage in Midnight nodes. - [Transactions](/concepts/network-architecture/transactions.md): A reference on the Midnight transaction format, its classification vocabulary, and the non-ledger transaction categories the node owns. ### sidechains-partnerchains Understanding the research foundation of the partner chain framework - [The origins of sidechains and partner chains](/concepts/sidechains-partnerchains.md): Understanding the research foundation of the partner chain framework ### utxo The UTXO model is a different way to reason about digital value. If the account model feels familiar because it mirrors traditional banking, UTXO can feel unfamiliar at first. Once you understand it, the design trade-offs become clear and explain why Midnight uses it as a foundation for privacy and parallelism. - [UTXO model](/concepts/utxo.md): The UTXO model is a different way to reason about digital value. If the account model feels familiar because it mirrors traditional banking, UTXO can feel unfamiliar at first. Once you understand it, the design trade-offs become clear and explain why Midnight uses it as a foundation for privacy and parallelism. ### web3 A reference on the Web3 model. - [Web3](/concepts/web3.md): A reference on the Web3 model. ### zero-knowledge-proofs A reference on how zero-knowledge proofs work and how they are used in Midnight. - [Zero-knowledge proofs](/concepts/zero-knowledge-proofs.md): A reference on how zero-knowledge proofs work and how they are used in Midnight. ### zk-snark-vs-zk-stark zk-SNARK vs zk-STARK compared on trusted setup, proof size, verification speed, and quantum resistance, with real platform examples for each. - [zk-SNARK vs zk-STARK: which approach do privacy-focused blockchains use?](/concepts/zk-snark-vs-zk-stark.md): zk-SNARK vs zk-STARK compared on trusted setup, proof size, verification speed, and quantum resistance, with real platform examples for each. ### zk-vs-fhe-vs-mpc Compare zero-knowledge proofs, FHE, and MPC for privacy-preserving DApps: what each protects, example platforms, and which approach to choose. - [ZK vs FHE vs MPC: which should you use for a privacy-focused DApp?](/concepts/zk-vs-fhe-vs-mpc.md): Compare zero-knowledge proofs, FHE, and MPC for privacy-preserving DApps: what each protects, example platforms, and which approach to choose. ### zswap A reference on how Zswap works and how it is used in Midnight. - [Zswap](/concepts/zswap.md): A reference on how Zswap works and how it is used in Midnight. ## examples Browse every documented Midnight example by the feature or problem it demonstrates, then open the contract or DApp closest to what you are building. - [Examples](/examples.md): Browse every documented Midnight example by the feature or problem it demonstrates, then open the contract or DApp closest to what you are building. ### contracts Standalone Compact contract examples that isolate specific language features like witness functions, token operations, and private state. - [Contract examples](/examples/contracts.md): Standalone Compact contract examples that isolate specific language features like witness functions, token operations, and private state. - [Battleship Simple Version](/examples/contracts/battleship-simple.md): Example contract - [Calculator Contract](/examples/contracts/calculator.md): Example contract for math operations - [Election Contract](/examples/contracts/election.md): Example contract for private state access - [Private Guest List Contract](/examples/contracts/private-guest-list.md): Example contract - [Private Reserve Auction Contract](/examples/contracts/private-reserve-auction.md): Example contract - [Shielded and Unshielded Token Transfers](/examples/contracts/token-transfers.md): Token transfer examples ### dapps End-to-end DApp examples with contract code, CLI tooling, and deployment steps you can study and adapt to your own project. - [DApp examples](/examples/dapps.md): End-to-end DApp examples with contract code, CLI tooling, and deployment steps you can study and adapt to your own project. - [Bulletin board DApp](/examples/dapps/bboard.md): Learn how the bulletin board DApp demonstrates privacy-preserving message posting with Zero Knowledge proofs on Midnight Network. - [Leaderboard DApp](/examples/dapps/leaderboard.md): Learn how the leaderboard DApp demonstrates privacy-preserving score submission and ownership verification with zero-knowledge proofs on Midnight Network. - [ZK Loan DApp](/examples/dapps/zkloan.md): Privacy-preserving loan application on Midnight Network — credit data stays on the user's machine, only the loan outcome lands on-chain. ## getting-started Start building on Midnight. - [Get started](/getting-started.md): Start building on Midnight. ### hello-world Learn how to create and compile a Hello World smart contract on Midnight's Preprod network. - [Create your first Midnight contract](/getting-started/hello-world.md): Learn how to create and compile a Hello World smart contract on Midnight's Preprod network. ### installation Get your Midnight development environment running to set up tools, configure wallets, and deploy your first zero-knowledge application. - [Install the toolchain](/getting-started/installation.md): Get your Midnight development environment running to set up tools, configure wallets, and deploy your first zero-knowledge application. ### quickstart Get started creating a Midnight DApp using the create-mn-app CLI tool. - [Create a Midnight DApp](/getting-started/quickstart.md): Get started creating a Midnight DApp using the create-mn-app CLI tool. ## glossary Glossary of terms used in Midnight Network. - [Midnight Network Glossary](/glossary.md): Glossary of terms used in Midnight Network. ## guides ### acquire-tokens Get tNIGHT from the faucet and register it for DUST generation, in Lace or with the wallet SDK, so your wallet can pay transaction fees. - [Funding a wallet](/guides/acquire-tokens.md): Get tNIGHT from the faucet and register it for DUST generation, in Lace or with the wallet SDK, so your wallet can pay transaction fees. ### build-cross-chain-dapp-with-effectstream Run the EVM and Midnight template, learn how a rollup joins two chains without a bridge, and extend it with a field of your own. - [Build a cross-chain DApp with EffectStream](/guides/build-cross-chain-dapp-with-effectstream.md): Run the EVM and Midnight template, learn how a rollup joins two chains without a bridge, and extend it with a field of your own. ### compact-javascript-runtime Run a Compact contract's logic from JavaScript: implement witnesses, call circuits, write unit tests, and read the generated module's exports and errors. - [Using Compact contracts from JavaScript](/guides/compact-javascript-runtime.md): Run a Compact contract's logic from JavaScript: implement witnesses, call circuits, write unit tests, and read the generated module's exports and errors. ### deploy-and-operate Wire the Midnight.js providers, deploy a Compact contract to a network, observe its state, and operate the maintenance authority that keeps it updatable. - [Deploying and operating a contract](/guides/deploy-and-operate.md): Wire the Midnight.js providers, deploy a Compact contract to a network, observe its state, and operate the maintenance authority that keeps it updatable. ### dust-sponsorship Pay DUST fees on behalf of your users. The sponsorship model, the contract rule, both sides of the flow, and a runnable reference example. - [Sponsor transaction fees with DUST](/guides/dust-sponsorship.md): Pay DUST fees on behalf of your users. The sponsorship model, the contract rule, both sides of the flow, and a runnable reference example. ### index-state-with-effectstream Run an EffectStream node that watches a Midnight contract, decode its public ledger with a schema, and serve the result over HTTP. - [Index contract state with EffectStream](/guides/index-state-with-effectstream.md): Run an EffectStream node that watches a Midnight contract, decode its public ledger with a schema, and serve the result over HTTP. ### local-proving Why Midnight needs Docker, the proof server and proof generation, and how to run, verify, and connect to a local proof server. - [Proving transactions locally](/guides/local-proving.md): Why Midnight needs Docker, the proof server and proof generation, and how to run, verify, and connect to a local proof server. ### networks-and-environments Understand Midnight's networks, choose the right one, connect a DApp with the correct network ID and endpoints, fund it, and prepare for mainnet. - [Networks and environments](/guides/networks-and-environments.md): Understand Midnight's networks, choose the right one, connect a DApp with the correct network ID and endpoints, fund it, and prepare for mainnet. ### nextjs-wallet-connect Learn how to create a Next.js application that connects to a wallet using the Midnight DApp Connector API. - [Create a Next.js wallet connector](/guides/nextjs-wallet-connect.md): Learn how to create a Next.js application that connects to a wallet using the Midnight DApp Connector API. ### react-wallet-connect Learn how to create a React application that connects to a wallet using the Midnight DApp Connector API. - [Create a React wallet connector](/guides/react-wallet-connect.md): Learn how to create a React application that connects to a wallet using the Midnight DApp Connector API. ### run-proof-server Learn how to run the proof server for the Midnight Network. - [Proof server](/guides/run-proof-server.md): Learn how to run the proof server for the Midnight Network. ### security-best-practices Secure a Midnight DApp: concepts, procedures, and references for authentication, access control, arithmetic, deadlines, replay, keys, proving, and privacy. - [Security and best practices](/guides/security-best-practices.md): Secure a Midnight DApp: concepts, procedures, and references for authentication, access control, arithmetic, deadlines, replay, keys, proving, and privacy. ### windows-compact-setup Learn how to set up the Midnight development environment on Windows using Windows Subsystem for Linux (WSL). - [Windows Compact setup](/guides/windows-compact-setup.md): Learn how to set up the Midnight development environment on Windows using Windows Subsystem for Linux (WSL). ## how-to ### bun-runtime-midnight Set up Bun package manager and the Compact compiler to build smart contracts and applications on the Midnight blockchain. - [Set up Bun for Midnight development](/how-to/bun-runtime-midnight.md): Set up Bun package manager and the Compact compiler to build smart contracts and applications on the Midnight blockchain. ### decode-1010-transaction-rejection-errors Decode the inner u8 in Substrate code 1010 "Invalid Transaction" responses to identify the underlying Midnight ledger error variant. - [Decode 1010 transaction rejection errors](/how-to/decode-1010-transaction-rejection-errors.md): Decode the inner u8 in Substrate code 1010 "Invalid Transaction" responses to identify the underlying Midnight ledger error variant. ### fix-package-repository-access-failures Resolve 403 Forbidden and authentication errors when installing @midnight-ntwrk npm packages. Covers registry, network, configuration, and token fixes. - [Fix package repository access failures](/how-to/fix-package-repository-access-failures.md): Resolve 403 Forbidden and authentication errors when installing @midnight-ntwrk npm packages. Covers registry, network, configuration, and token fixes. ### fix-version-mismatches Resolve version compatibility issues between Midnight compiler, runtime, and other components using the official compatibility matrix. - [Fix version mismatch errors](/how-to/fix-version-mismatches.md): Resolve version compatibility issues between Midnight compiler, runtime, and other components using the official compatibility matrix. ## nodes A reference on Midnight nodes. - [Midnight Node overview](/nodes.md): A reference on Midnight nodes. ### boot-node A reference on setting up boot nodes for Midnight. - [Set up boot node](/nodes/boot-node.md): A reference on setting up boot nodes for Midnight. ### cardano-db-sync A reference on setting up Cardano-db-sync for Midnight. - [Set up Cardano-db-sync](/nodes/cardano-db-sync.md): A reference on setting up Cardano-db-sync for Midnight. ### cardano-node A reference on setting up Cardano Node for Midnight. - [Set up Cardano node](/nodes/cardano-node.md): A reference on setting up Cardano Node for Midnight. ### error-codes A list of Midnight node error codes and their troubleshooting steps. - [Midnight node error codes](/nodes/error-codes.md): A list of Midnight node error codes and their troubleshooting steps. ### full-node A reference on setting up full and archive nodes for Midnight. - [Set up full node](/nodes/full-node.md): A reference on setting up full and archive nodes for Midnight. ### node-endpoints A reference for Midnight Network endpoints and RPC access. - [Node endpoints](/nodes/node-endpoints.md): A reference for Midnight Network endpoints and RPC access. ### rpc-node A reference on setting up RPC nodes for Midnight. - [Set up RPC node for Midnight](/nodes/rpc-node.md): A reference on setting up RPC nodes for Midnight. ## relnotes ### compact Compact is Midnight's smart contract programming language, designed for building secure, efficient, and adaptable decentralized applications. - [Compact toolchain](/relnotes/compact.md): Compact is Midnight's smart contract programming language, designed for building secure, efficient, and adaptable decentralized applications. ### compact-js Compact.js provides a TypeScript-based execution environment for smart contracts compiled with the Compact compiler. - [Compact.js](/relnotes/compact-js.md): Compact.js provides a TypeScript-based execution environment for smart contracts compiled with the Compact compiler. ### compact-tools Compact is Midnight's dedicated smart contract programming language, designed for building secure, efficient, and adaptable decentralized applications. - [Compact developer tools](/relnotes/compact-tools.md): Compact is Midnight's dedicated smart contract programming language, designed for building secure, efficient, and adaptable decentralized applications. ### dapp-connector-api DApp Connector API allows decentralized applications (DApps) to request wallet access, verify authorization, and retrieve service URIs for interacting with the Midnight network. - [DApp Connector API](/relnotes/dapp-connector-api.md): DApp Connector API allows decentralized applications (DApps) to request wallet access, verify authorization, and retrieve service URIs for interacting with the Midnight network. ### ledger The ledger in Midnight is a public record of contract states and token states, consisting of Zswap’s cryptographic commitments and a mapping of contract addresses to their respective states. - [Ledger](/relnotes/ledger.md): The ledger in Midnight is a public record of contract states and token states, consisting of Zswap’s cryptographic commitments and a mapping of contract addresses to their respective states. ### midnight-indexer The Midnight Indexer is a set of components designed to optimize the flow of blockchain data from a Midnight node to end-user applications. It retrieves history of blocks, processes them, stores indexed data efficiently, and provides a GraphQL API for queries and subscriptions. - [Midnight Indexer](/relnotes/midnight-indexer.md): The Midnight Indexer is a set of components designed to optimize the flow of blockchain data from a Midnight node to end-user applications. It retrieves history of blocks, processes them, stores indexed data efficiently, and provides a GraphQL API for queries and subscriptions. ### midnight-js Midnight.js is a client library designed to facilitate the development of decentralized applications on the Midnight blockchain. - [Midnight.js](/relnotes/midnight-js.md): Midnight.js is a client library designed to facilitate the development of decentralized applications on the Midnight blockchain. ### midnight-wallet-api The Wallet API is deprecated. Wallet functionality is now handled through the Wallet SDK. Please migrate to the Wallet SDK for all wallet operations and integrations. - [Wallet API](/relnotes/midnight-wallet-api.md): The Wallet API is deprecated. Wallet functionality is now handled through the Wallet SDK. Please migrate to the Wallet SDK for all wallet operations and integrations. ### network Environments and endpoints for Midnight. - [Environments and endpoints](/relnotes/network.md): Environments and endpoints for Midnight. ### node Node is a core component of the Midnight network, responsible for syncing, validating transactions, and maintaining the chain state. - [Node](/relnotes/node.md): Node is a core component of the Midnight network, responsible for syncing, validating transactions, and maintaining the chain state. ### onchain-runtime Starting with Ledger 7.0.0, Onchain Runtime releases are included as part of the Ledger release. For the most recent Onchain Runtime releases and updates, please refer to the release notes overview. - [Onchain Runtime](/relnotes/onchain-runtime.md): Starting with Ledger 7.0.0, Onchain Runtime releases are included as part of the Ledger release. For the most recent Onchain Runtime releases and updates, please refer to the release notes overview. ### overview Latest stable release - [Latest stable release](/relnotes/overview.md): Latest stable release ### proof-server Starting with Ledger 7.0.0, Proof Server releases are included as part of the Ledger release. For the most recent Proof Server releases and updates, please refer to the release notes overview. - [Proof Server](/relnotes/proof-server.md): Starting with Ledger 7.0.0, Proof Server releases are included as part of the Ledger release. For the most recent Proof Server releases and updates, please refer to the release notes overview. ### support-matrix --- - [Compatibility matrix](/relnotes/support-matrix.md): --- ### wallet Midnight Wallet SDK is the SDK of the digital wallet designed for the Midnight blockchain, enabling users to securely store private keys, manage assets, and interact with decentralized applications. - [Wallet SDK](/relnotes/wallet.md): Midnight Wallet SDK is the SDK of the digital wallet designed for the Midnight blockchain, enabling users to securely store private keys, manage assets, and interact with decentralized applications. ## sdks Build privacy-preserving decentralized applications with Midnight's comprehensive SDK ecosystem. Whether you're creating smart contracts, wallets, or full-stack DApps, we have the tools you need. - [Midnight SDKs](/sdks.md): Build privacy-preserving decentralized applications with Midnight's comprehensive SDK ecosystem. Whether you're creating smart contracts, wallets, or full-stack DApps, we have the tools you need. ### community Third-party libraries and tools built on Midnight by the wider community. - [Community projects](/sdks/community.md): Third-party libraries and tools built on Midnight by the wider community. - [Midnight agent skills](/sdks/community/ai-tools/midnight-agent-skills.md): midnight_agent_skills is a set of four modular agent skills that give AI coding assistants accurate knowledge of Compact syntax, Midnight SDK, network configuration, and common gotchas sourced from the developer community. - [Edda Midnight starter template](/sdks/community/edda-midnight-starter.md): A full-stack starter template for building DApps on Midnight with a React frontend, Compact smart contract, CLI tooling, and educational materials. - [Midnames](/sdks/community/midnames.md): Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. - [Midnight Explorer](/sdks/community/midnight-explorer.md): Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. - [Midnight Live View](/sdks/community/midnight-live-view.md): A real-time terminal dashboard and persistent block monitor for Midnight validator nodes, inspired by CNTool's gLiveView. - [Nightforge](/sdks/community/nightforge.md): Compile, deploy, and operate Compact contracts from one CLI with Nightforge, a community development environment for Midnight. - [OpenZeppelin contracts for Compact](/sdks/community/openzeppelin-compact-contracts.md): A library of token standards, access control, and security primitives for Compact smart contracts, modeled on OpenZeppelin's Solidity contracts. - [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md): Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. - [Integrate a wallet](/sdks/community/wallets/community-wallets-integration.md): Integrate a community wallet on the Midnight Network with the DApp Connector (CAIP-372): discovery, connect, ZK proving, fees, and portable React code. - [Community wallets](/sdks/community/wallets/community-wallets-overview.md): Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. - [Wallet reference](/sdks/community/wallets/community-wallets-reference.md): Reference for Midnight Network community wallets: the functionality matrix, troubleshooting and error codes, a security checklist, ecosystem, and glossary. ### error-reference - [Midnight.js error reference](/sdks/error-reference/midnight-js.md): Error reference for the Midnight.js SDK. - [Wallet SDK error reference](/sdks/error-reference/wallet-sdk.md): Error reference for the Wallet SDK. ### official - [Midnight.js](/sdks/official/midnight-js.md): Comprehensive TypeScript SDK for building DApps on Midnight Network. - [Midnight wallet SDK](/sdks/official/wallet-developer-guide.md): Developer guide for the Midnight Wallet SDK, covering unshielded, shielded, and DUST wallet operations. ### tags - [Tags](/sdks/tags.md) - [One doc tagged with "1am"](/sdks/tags/1-am.md) - [One doc tagged with "access-control"](/sdks/tags/access-control.md) - [One doc tagged with "address-resolution"](/sdks/tags/address-resolution.md) - [One doc tagged with "agent-skills"](/sdks/tags/agent-skills.md) - [One doc tagged with "ai"](/sdks/tags/ai.md) - [One doc tagged with "ai-agents"](/sdks/tags/ai-agents.md) - [One doc tagged with "analytics"](/sdks/tags/analytics.md) - [One doc tagged with "automation"](/sdks/tags/automation.md) - [One doc tagged with "blocks"](/sdks/tags/blocks.md) - [One doc tagged with "caip-372"](/sdks/tags/caip-372.md) - [2 docs tagged with "cli"](/sdks/tags/cli.md) - [11 docs tagged with "community"](/sdks/tags/community.md) - [3 docs tagged with "compact"](/sdks/tags/compact.md) - [One doc tagged with "contracts"](/sdks/tags/contracts.md) - [One doc tagged with "counter"](/sdks/tags/counter.md) - [One doc tagged with "custody"](/sdks/tags/custody.md) - [One doc tagged with "dapp"](/sdks/tags/dapp.md) - [One doc tagged with "dapp-connector"](/sdks/tags/dapp-connector.md) - [One doc tagged with "dashboard"](/sdks/tags/dashboard.md) - [One doc tagged with "deployment"](/sdks/tags/deployment.md) - [One doc tagged with "developer guide"](/sdks/tags/developer-guide.md) - [2 docs tagged with "developer-tools"](/sdks/tags/developer-tools.md) - [One doc tagged with "devnet"](/sdks/tags/devnet.md) - [One doc tagged with "domains"](/sdks/tags/domains.md) - [2 docs tagged with "dust"](/sdks/tags/dust.md) - [One doc tagged with "ecosystem"](/sdks/tags/ecosystem.md) - [2 docs tagged with "error reference"](/sdks/tags/error-reference.md) - [One doc tagged with "explorer"](/sdks/tags/explorer.md) - [One doc tagged with "fireblocks"](/sdks/tags/fireblocks.md) - [One doc tagged with "glossary"](/sdks/tags/glossary.md) - [2 docs tagged with "integration"](/sdks/tags/integration.md) - [One doc tagged with "issues"](/sdks/tags/issues.md) - [One doc tagged with "kuira"](/sdks/tags/kuira.md) - [One doc tagged with "lace"](/sdks/tags/lace.md) - [2 docs tagged with "matrix"](/sdks/tags/matrix.md) - [One doc tagged with "mcp"](/sdks/tags/mcp.md) - [One doc tagged with "midnames"](/sdks/tags/midnames.md) - [One doc tagged with "midnight.js"](/sdks/tags/midnight-js.md) - [One doc tagged with "mobile"](/sdks/tags/mobile.md) - [One doc tagged with "monitoring"](/sdks/tags/monitoring.md) - [One doc tagged with "name-service"](/sdks/tags/name-service.md) - [One doc tagged with "nameservice"](/sdks/tags/nameservice.md) - [One doc tagged with "nextjs"](/sdks/tags/nextjs.md) - [One doc tagged with "node"](/sdks/tags/node.md) - [One doc tagged with "npm"](/sdks/tags/npm.md) - [One doc tagged with "openzeppelin"](/sdks/tags/openzeppelin.md) - [One doc tagged with "playground"](/sdks/tags/playground.md) - [One doc tagged with "proof-server"](/sdks/tags/proof-server.md) - [One doc tagged with "proving"](/sdks/tags/proving.md) - [2 docs tagged with "react"](/sdks/tags/react.md) - [One doc tagged with "scaffolding"](/sdks/tags/scaffolding.md) - [6 docs tagged with "sdk"](/sdks/tags/sdk.md) - [One doc tagged with "security"](/sdks/tags/security.md) - [One doc tagged with "self-custody"](/sdks/tags/self-custody.md) - [One doc tagged with "shell"](/sdks/tags/shell.md) - [One doc tagged with "starter"](/sdks/tags/starter.md) - [One doc tagged with "template"](/sdks/tags/template.md) - [One doc tagged with "testing"](/sdks/tags/testing.md) - [One doc tagged with "third-party"](/sdks/tags/third-party.md) - [One doc tagged with "tokens"](/sdks/tags/tokens.md) - [One doc tagged with "tooling"](/sdks/tags/tooling.md) - [One doc tagged with "transactions"](/sdks/tags/transactions.md) - [One doc tagged with "troubleshooting"](/sdks/tags/troubleshooting.md) - [2 docs tagged with "typescript"](/sdks/tags/typescript.md) - [One doc tagged with "validator"](/sdks/tags/validator.md) - [2 docs tagged with "wallet"](/sdks/tags/wallet.md) - [4 docs tagged with "wallets"](/sdks/tags/wallets.md) ### troubleshoot Troubleshoot common issues when building on Midnight Network. - [Common SDK integration issues](/sdks/troubleshoot.md): Troubleshoot common issues when building on Midnight Network. ## search - [Search the documentation](/search.md) ## tokens ### overview Understand NIGHT, DUST, shielded and unshielded tokens, custom tokens, and fees on the Midnight Network. - [Tokens on Midnight](/tokens/overview.md): Understand NIGHT, DUST, shielded and unshielded tokens, custom tokens, and fees on the Midnight Network. ### shielded-token Build, deploy, and transfer a privacy-preserving (shielded) token in Compact on Midnight, where value lives in immutable coins and balances stay hidden. - [Create and transfer a shielded token](/tokens/shielded-token.md): Build, deploy, and transfer a privacy-preserving (shielded) token in Compact on Midnight, where value lives in immutable coins and balances stay hidden. ### unshielded-token Build, deploy, and transfer a transparent (unshielded) token in Compact on Midnight, with on-chain balances you read straight from wallet state. - [Create and transfer an unshielded token](/tokens/unshielded-token.md): Build, deploy, and transfer a transparent (unshielded) token in Compact on Midnight, with on-chain balances you read straight from wallet state. ## troubleshoot ### compiler-errors Common Compact compiler errors and their solutions, including lexer, parser, witness, disclosure, ZKIR, and runtime errors with fix instructions. - [Troubleshoot compiler errors](/troubleshoot/compiler-errors.md): Common Compact compiler errors and their solutions, including lexer, parser, witness, disclosure, ZKIR, and runtime errors with fix instructions. ### faq Frequently asked questions about Midnight Network. - [Frequently asked questions](/troubleshoot/faq.md): Frequently asked questions about Midnight Network. ### getting-help Get help with Midnight Network development and troubleshooting. - [Support](/troubleshoot/getting-help.md): Get help with Midnight Network development and troubleshooting. ### troubleshoot-compact-nixos Troubleshoot Midnight Compact tools installation issue on NixOS - [Troubleshoot Compact toolchain installation issue on NixOS](/troubleshoot/troubleshoot-compact-nixos.md): Troubleshoot Midnight Compact tools installation issue on NixOS ## tutorials Step-by-step tutorials for building DApps on Midnight Network, from your first Compact contract to a full-stack deployment with wallet integration. - [Tutorials](/tutorials.md): Step-by-step tutorials for building DApps on Midnight Network, from your first Compact contract to a full-stack deployment with wallet integration. ### bboard Build a privacy-preserving bulletin board DApp with ZK proofs for identity verification, a reusable API layer, and a CLI. - [Bulletin board tutorial](/tutorials/bboard.md): Build a privacy-preserving bulletin board DApp with ZK proofs for identity verification, a reusable API layer, and a CLI. - [Bulletin board API implementation](/tutorials/bboard/bboard-api-implementation.md): Implement the API package for the bulletin board CLI. - [Bulletin board CLI](/tutorials/bboard/bboard-cli.md): Learn how to build a bulletin board CLI DApp on Midnight Network. - [Bulletin board CLI implementation](/tutorials/bboard/bboard-cli-implementation.md): Implement the CLI package for the bulletin board application. - [Bulletin board contract](/tutorials/bboard/smart-contract.md): Learn how to build a privacy-preserving bulletin board contract on Midnight Network. ### bship Write a Battleship contract that mixes public and private state as a state machine, then verify it with MidnightJS tests. - [Battleship tutorial](/tutorials/bship.md): Write a Battleship contract that mixes public and private state as a state machine, then verify it with MidnightJS tests. - [Battleship contract](/tutorials/bship/smart-contract.md): Learn about best practices while building a Battleship contract. - [Battleship tests](/tutorials/bship/test-suite.md): Learn how to test the Battleship contract. ### leaderboard Build a full-stack leaderboard DApp with privacy controls, Lace wallet integration, a React frontend, and Vercel deployment. - [Leaderboard tutorial](/tutorials/leaderboard.md): Build a full-stack leaderboard DApp with privacy controls, Lace wallet integration, a React frontend, and Vercel deployment. - [Part 2: TypeScript integration](/tutorials/leaderboard/api-layer.md): Set up the TypeScript witness provider, contract exports, and a shared API class for deploying and interacting with the leaderboard DApp on Midnight. - [Part 3: Browser DApp](/tutorials/leaderboard/browser-dapp.md): Build a React frontend that connects to the Lace wallet, reads leaderboard state from the Midnight indexer, and submits scores on-chain with privacy modes. - [Part 4: Production deployment](/tutorials/leaderboard/deployment.md): Deploy a Midnight leaderboard DApp frontend to Vercel on Preprod. - [Build a privacy-preserving leaderboard DApp](/tutorials/leaderboard/overview.md): Build a full-stack DApp on the Midnight Network with privacy modes, ownership verification, and Lace wallet integration. - [Part 1: The smart contract](/tutorials/leaderboard/smart-contract.md): Write a Compact smart contract with privacy modes, ownership verification, and arcade-style scoring for a leaderboard Dapp on Midnight. ### private-party Write a private party contract that demonstrates the privacy boundary in Midnight DApps, then verify it with MidnightJS tests. - [Private party tutorial](/tutorials/private-party.md): Write a private party contract that demonstrates the privacy boundary in Midnight DApps, then verify it with MidnightJS tests. - [Private party contract](/tutorials/private-party/smart-contract.md): Build a private party contract on Midnight that demonstrates the privacy boundary, Unshielded NIGHT tokens, and access control in Compact. ### zk-loan Build a ZK loan DApp that privately evaluates credit data using zero-knowledge proofs, with a Schnorr attestation API and CLI. - [ZK Loan tutorial](/tutorials/zk-loan.md): Build a ZK loan DApp that privately evaluates credit data using zero-knowledge proofs, with a Schnorr attestation API and CLI. - [Attestation API](/tutorials/zk-loan/attestation-api.md): Build the attestation API and proof server for the zero-knowledge loan DApp on Midnight Network. - [CLI and end-to-end testing](/tutorials/zk-loan/cli.md): Build the CLI and run the full zero-knowledge loan DApp end-to-end on Midnight Network. - [ZK Loan smart contract](/tutorials/zk-loan/smart-contract.md): Build a zero-knowledge loan smart contract on Midnight Network that privately evaluates credit data using zero-knowledge proofs. ## what-is-midnight Midnight is a data protection blockchain platform. It addresses a fundamental challenge in blockchain technology: how to use the benefits of distributed ledgers while maintaining the privacy required for sensitive data. - [What is Midnight?](/what-is-midnight.md): Midnight is a data protection blockchain platform. It addresses a fundamental challenge in blockchain technology: how to use the benefits of distributed ledgers while maintaining the privacy required for sensitive data. --- # Full Documentation Content [Skip to main content](#__docusaurus_skipToContent_fallback) [![Midnight Logo](/img/midnight-header-logo-dark.svg)](/index.md) [API reference](/api-reference.md)[SDKs](/sdks.md)[Compact](/compact.md)[Dev Diaries](/blog) AI search [](https://discord.com/invite/midnightnetwork) Search # Search the documentation Type your search here v1 (current) Powered by[](https://www.algolia.com/) ![Midnight Logo](/img/midnight-header-logo-dark.svg)![Midnight Logo](/img/midnight-header-logo-dark.svg) © 2026 Input Output Global, Inc. All Rights Reserved. Resources * [Midnight Foundation](https://midnight.network/) * [Dev Diaries](/blog) * [Glacier Drop](https://www.midnight.gd/) * [Careers](https://midnight.network/careers) Legal * [Cookie Policy](https://45047878.fs1.hubspotusercontent-na1.net/hubfs/45047878/Midnight%20Foundation%20cookie-policy.pdf) * [Privacy Policy](https://45047878.fs1.hubspotusercontent-na1.net/hubfs/45047878/Midnight%20Foundation%20%20-%20Privacy%20Notice.pdf) * [Terms and Conditions](https://45047878.fs1.hubspotusercontent-na1.net/hubfs/45047878/Midnight%20Foundation%20-%20Website%20Terms%20of%20Use.pdf) Social * [![YouTube](/img/youtube.svg)](https://www.youtube.com/channel/UCy3oZ64F3FOtjZ5sZGQNgkA) * [![X/Twitter](/img/x.svg)](https://x.com/MidnightNtwrk) * [![Discord](/img/discord.svg)](https://discord.com/invite/midnightnetwork) * [![LinkedIn](/img/linkedin.svg)](https://www.linkedin.com/showcase/midnight-ntwrk/) --- ## A[​](#A "Direct link to A") * [api reference4](/api-reference/tags/api-reference.md) * [authentication1](/api-reference/tags/authentication.md) *** --- ## [DApp Connector API errors](/api-reference/error-reference/dapp-connector-errors.md) Error codes returned by the Midnight DApp Connector API when a DApp interacts with a wallet. --- ## [Authentication](/api-reference/overview/authentication.md) Learn about the authentication methods for deploying and interacting with smart contracts in Midnight. --- ## [DApp Connector API errors](/api-reference/error-reference/dapp-connector-errors.md) Error codes returned by the Midnight DApp Connector API when a DApp interacts with a wallet. --- ## [DApp Connector API errors](/api-reference/error-reference/dapp-connector-errors.md) Error codes returned by the Midnight DApp Connector API when a DApp interacts with a wallet. --- ## [Indexer error codes](/api-reference/error-reference/indexer-errors.md) Error codes and messages returned by the Midnight Indexer API and infrastructure services. --- ## [Ledger error reference](/api-reference/error-reference/ledger-errors.md) Rust-level error types from the Midnight ledger crate covering transaction validation, execution, and state management failures. --- ## [Proof server errors](/api-reference/error-reference/proof-server-errors.md) Error codes returned by the Midnight proof server during zero-knowledge proof generation. --- ## [Usage limits](/api-reference/overview/usage-limits.md) Learn about the usage limits for transactions and other API calls. --- > For the complete documentation index, see [llms.txt](/llms.txt) # API reference Comprehensive API documentation for building decentralized applications on the Midnight blockchain. These APIs provide the foundational building blocks for smart contract interaction, wallet integration, blockchain queries, and transaction management. ## Core APIs[​](#core-apis "Direct link to Core APIs") ### [Wallet SDK](/api-reference/wallet-sdk.md) TypeScript SDK for wallet operations, key management, and token transfers. [View API →](/api-reference/wallet-sdk.md) ### [Compact Runtime](/api-reference/compact-runtime.md) Runtime primitives for Compact smart contracts. [View API →](/api-reference/compact-runtime.md) ### [Midnight.js](/api-reference/midnight-js.md) TypeScript SDK for building decentralized applications. [View API →](/api-reference/midnight-js.md) ### [DApp Connector](/api-reference/dapp-connector.md) Standard interface for connecting DApps to Midnight wallets. [View API →](/api-reference/dapp-connector.md) ### [Midnight Indexer](/api-reference/midnight-indexer.md) GraphQL API for querying blockchain data. [View API →](/api-reference/midnight-indexer.md) ## Blockchain interactions[​](#blockchain-interactions "Direct link to Blockchain interactions") ### [Ledger](/api-reference/ledger.md) TypeScript bindings for transaction assembly and ledger operations. [View API →](/api-reference/ledger.md) ### [Onchain Runtime](/api-reference/onchain-runtime.md) Low-level interface to Midnight's onchain runtime. [View API →](/api-reference/onchain-runtime.md) ### [ZSwap](/api-reference/zswap.md) Privacy pool implementation for shielded transactions. [View API →](/api-reference/zswap.md) ## Testing and development[​](#testing-and-development "Direct link to Testing and development") ### [Testkit.js](/api-reference/testkit-js.md) Comprehensive testing solution for Midnight applications. [View API →](/api-reference/testkit-js.md) ## Version compatibility[​](#version-compatibility "Direct link to Version compatibility") For the latest version information and compatibility matrix, see the [release notes](/relnotes/overview.md) and [support matrix](/relnotes/support-matrix.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact runtime API **@midnight-ntwrk/compact-runtime v0.19.0** *** # Compact runtime library This API provides runtime primitives used by Compact's TypeScript output, both for use by the compiler output directly, and to utilise it or reproduce its behaviour. This API re-exports a number of items from `@midnight-ntwrk/onchain-runtime-v2`, and wraps others in a more TypeScript-friendly API. Key parts of the API are: * setNetworkId, required to ensure the right network is being targeted * [CircuitContext](/api-reference/compact-runtime/interfaces/CircuitContext.md), and [CircuitResults](/api-reference/compact-runtime/interfaces/CircuitResults.md) part of the input and output definition of all circuits * [WitnessContext](/api-reference/compact-runtime/interfaces/WitnessContext.md), part of the input definition of all circuits * Built-in functions: * Hashing/commitment * [transientHash](/api-reference/compact-runtime/functions/transientHash.md) * [transientCommit](/api-reference/compact-runtime/functions/transientCommit.md) * [persistentHash](/api-reference/compact-runtime/functions/persistentHash.md) * [persistentCommit](/api-reference/compact-runtime/functions/persistentCommit.md) * [degradeToTransient](/api-reference/compact-runtime/functions/degradeToTransient.md) * Elliptic curve * [ecAdd](/api-reference/compact-runtime/functions/ecAdd.md) * [ecNeg](/api-reference/compact-runtime/functions/ecNeg.md) * [ecMul](/api-reference/compact-runtime/functions/ecMul.md) * [ecMulGenerator](/api-reference/compact-runtime/functions/ecMulGenerator.md) * [hashToCurve](/api-reference/compact-runtime/functions/hashToCurve.md) * [ContractState](/api-reference/compact-runtime/classes/ContractState.md), encapsulating the entirety of a smart contract's on-chain state * [StateValue](/api-reference/compact-runtime/classes/StateValue.md), encoding data a contract maintains on-chain * [QueryContext](/api-reference/compact-runtime/classes/QueryContext.md), providing an annotated view into the contract state, against which on-chain VM programs can be run * [CompactType](/api-reference/compact-runtime/interfaces/CompactType.md), providing a runtime representation of basic Compact datatypes * Various TypeScript types matching same-named Compact types --- # ChargedState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ChargedState # Class: ChargedState Represents a [StateValue](/api-reference/compact-runtime/classes/StateValue.md) with storage annotations. These track the state usage that has been charged for so far. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ChargedState(state): ChargedState; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) #### Returns[​](#returns "Direct link to Returns") `ChargedState` ## Properties[​](#properties "Direct link to Properties") ### state[​](#state-1 "Direct link to state") ``` readonly state: StateValue; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # CompactError > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactError # Class: CompactError An error originating from code generated by the Compact compiler ## Extends[​](#extends "Direct link to Extends") * `Error` ## Extended by[​](#extended-by "Direct link to Extended by") * [`ContractInterfaceMismatchError`](/api-reference/compact-runtime/classes/ContractInterfaceMismatchError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactError(msg): CompactError; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### msg[​](#msg "Direct link to msg") `string` #### Returns[​](#returns "Direct link to Returns") `CompactError` #### Overrides[​](#overrides "Direct link to Overrides") ``` Error.constructor ``` ## Properties[​](#properties "Direct link to Properties") ### isCompactError[​](#iscompacterror "Direct link to isCompactError") ``` readonly isCompactError: true = true; ``` *** ### message[​](#message "Direct link to message") ``` message: string; ``` #### Inherited from[​](#inherited-from "Direct link to Inherited from") ``` Error.message ``` *** ### name[​](#name "Direct link to name") ``` name: string; ``` #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") ``` Error.name ``` *** ### stack?[​](#stack "Direct link to stack?") ``` optional stack: string; ``` #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") ``` Error.stack ``` *** ### stackTraceLimit[​](#stacktracelimit "Direct link to stackTraceLimit") ``` static stackTraceLimit: number; ``` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") ``` Error.stackTraceLimit ``` ## Methods[​](#methods "Direct link to Methods") ### captureStackTrace()[​](#capturestacktrace "Direct link to captureStackTrace()") ``` static captureStackTrace(targetObject, constructorOpt?): void; ``` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ``` const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ``` function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### targetObject[​](#targetobject "Direct link to targetObject") `object` ##### constructorOpt?[​](#constructoropt "Direct link to constructorOpt?") `Function` #### Returns[​](#returns-1 "Direct link to Returns") `void` #### Inherited from[​](#inherited-from-4 "Direct link to Inherited from") ``` Error.captureStackTrace ``` *** ### prepareStackTrace()[​](#preparestacktrace "Direct link to prepareStackTrace()") ``` static prepareStackTrace(err, stackTraces): any; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### err[​](#err "Direct link to err") `Error` ##### stackTraces[​](#stacktraces "Direct link to stackTraces") `CallSite`\[] #### Returns[​](#returns-2 "Direct link to Returns") `any` #### See[​](#see "Direct link to See") #### Inherited from[​](#inherited-from-5 "Direct link to Inherited from") ``` Error.prepareStackTrace ``` --- # CompactTypeBoolean > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeBoolean # Class: CompactTypeBoolean Runtime type of the builtin `Boolean` type ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`boolean`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeBoolean(): CompactTypeBoolean; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeBoolean` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): boolean; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `boolean` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `boolean` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeBytes > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeBytes # Class: CompactTypeBytes Runtime type of the builtin `Bytes` types ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`Uint8Array`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeBytes(length): CompactTypeBytes; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### length[​](#length "Direct link to length") `number` #### Returns[​](#returns "Direct link to Returns") `CompactTypeBytes` ## Properties[​](#properties "Direct link to Properties") ### length[​](#length-1 "Direct link to length") ``` readonly length: number; ``` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): Uint8Array; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `Uint8Array` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeCurvePoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeCurvePoint # Class: CompactTypeCurvePoint Runtime type of [CurvePoint](/api-reference/compact-runtime/interfaces/CurvePoint.md) ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<[`CurvePoint`](/api-reference/compact-runtime/interfaces/CurvePoint.md)> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeCurvePoint(): CompactTypeCurvePoint; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeCurvePoint` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): CurvePoint; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") [`CurvePoint`](/api-reference/compact-runtime/interfaces/CurvePoint.md) #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`CurvePoint`](/api-reference/compact-runtime/interfaces/CurvePoint.md) #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeEnum > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeEnum # Class: CompactTypeEnum Runtime type of an enum with a given number of entries ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`number`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeEnum(maxValue, length): CompactTypeEnum; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### maxValue[​](#maxvalue "Direct link to maxValue") `number` ##### length[​](#length "Direct link to length") `number` #### Returns[​](#returns "Direct link to Returns") `CompactTypeEnum` ## Properties[​](#properties "Direct link to Properties") ### length[​](#length-1 "Direct link to length") ``` readonly length: number; ``` *** ### maxValue[​](#maxvalue-1 "Direct link to maxValue") ``` readonly maxValue: number; ``` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): number; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `number` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `number` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeField # Class: CompactTypeField Runtime type of the builtin `Field` type ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`bigint`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeField(): CompactTypeField; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeField` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): bigint; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `bigint` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `bigint` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeMerkleTreeDigest > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeMerkleTreeDigest # Class: CompactTypeMerkleTreeDigest Runtime type of [MerkleTreeDigest](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md) ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<[`MerkleTreeDigest`](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md)> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeMerkleTreeDigest(): CompactTypeMerkleTreeDigest; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeMerkleTreeDigest` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): MerkleTreeDigest; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") [`MerkleTreeDigest`](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md) #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`MerkleTreeDigest`](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md) #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeMerkleTreePath > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeMerkleTreePath # Class: CompactTypeMerkleTreePath\ Runtime type of [MerkleTreePath](/api-reference/compact-runtime/interfaces/MerkleTreePath.md) ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<[`MerkleTreePath`](/api-reference/compact-runtime/interfaces/MerkleTreePath.md)<`A`>> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeMerkleTreePath(n, leaf): CompactTypeMerkleTreePath; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### n[​](#n "Direct link to n") `number` ##### leaf[​](#leaf "Direct link to leaf") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> #### Returns[​](#returns "Direct link to Returns") `CompactTypeMerkleTreePath`<`A`> ## Properties[​](#properties "Direct link to Properties") ### leaf[​](#leaf-1 "Direct link to leaf") ``` readonly leaf: CompactType; ``` *** ### path[​](#path "Direct link to path") ``` readonly path: CompactTypeVector; ``` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): MerkleTreePath; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") [`MerkleTreePath`](/api-reference/compact-runtime/interfaces/MerkleTreePath.md)<`A`> #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`MerkleTreePath`](/api-reference/compact-runtime/interfaces/MerkleTreePath.md)<`A`> #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeMerkleTreePathEntry > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeMerkleTreePathEntry # Class: CompactTypeMerkleTreePathEntry Runtime type of [MerkleTreePathEntry](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md) ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<[`MerkleTreePathEntry`](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md)> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeMerkleTreePathEntry(): CompactTypeMerkleTreePathEntry; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeMerkleTreePathEntry` ## Properties[​](#properties "Direct link to Properties") ### bool[​](#bool "Direct link to bool") ``` readonly bool: CompactTypeBoolean; ``` *** ### digest[​](#digest "Direct link to digest") ``` readonly digest: CompactTypeMerkleTreeDigest; ``` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): MerkleTreePathEntry; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") [`MerkleTreePathEntry`](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md) #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`MerkleTreePathEntry`](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md) #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeOpaqueString > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeOpaqueString # Class: CompactTypeOpaqueString Runtime type of `Opaque["string"]` ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`string`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeOpaqueString(): CompactTypeOpaqueString; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeOpaqueString` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): string; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `string` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `string` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeOpaqueUint8Array > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeOpaqueUint8Array # Class: CompactTypeOpaqueUint8Array Runtime type of `Opaque["Uint8Array"]` ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`Uint8Array`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeOpaqueUint8Array(): CompactTypeOpaqueUint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `CompactTypeOpaqueUint8Array` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): Uint8Array; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `Uint8Array` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeUnsignedInteger > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeUnsignedInteger # Class: CompactTypeUnsignedInteger Runtime type of the builtin `Unsigned Integer` types ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`bigint`> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeUnsignedInteger(maxValue, length): CompactTypeUnsignedInteger; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### maxValue[​](#maxvalue "Direct link to maxValue") `bigint` ##### length[​](#length "Direct link to length") `number` #### Returns[​](#returns "Direct link to Returns") `CompactTypeUnsignedInteger` ## Properties[​](#properties "Direct link to Properties") ### length[​](#length-1 "Direct link to length") ``` readonly length: number; ``` *** ### maxValue[​](#maxvalue-1 "Direct link to maxValue") ``` readonly maxValue: bigint; ``` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): bigint; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `bigint` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `bigint` #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # CompactTypeVector > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeVector # Class: CompactTypeVector\ Runtime type of the builtin `Vector` types ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Implements[​](#implements "Direct link to Implements") * [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`\[]> ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new CompactTypeVector(length, type): CompactTypeVector; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### length[​](#length "Direct link to length") `number` ##### type[​](#type "Direct link to type") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> #### Returns[​](#returns "Direct link to Returns") `CompactTypeVector`<`A`> ## Properties[​](#properties "Direct link to Properties") ### length[​](#length-1 "Direct link to length") ``` readonly length: number; ``` *** ### type[​](#type-1 "Direct link to type") ``` readonly type: CompactType; ``` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns-1 "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`alignment`](/api-reference/compact-runtime/interfaces/CompactType.md#alignment) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): A[]; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `A`\[] #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`fromValue`](/api-reference/compact-runtime/interfaces/CompactType.md#fromvalue) *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `A`\[] #### Returns[​](#returns-3 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md).[`toValue`](/api-reference/compact-runtime/interfaces/CompactType.md#tovalue) --- # ContractInterfaceMismatchError > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractInterfaceMismatchError # Class: ContractInterfaceMismatchError Thrown when a cross-contract call targets a contract whose deployed verifier key for the called circuit does not match the verifier key of the implementation the caller was compiled against. Under the current model every `contract T` interface resolves to exactly one implementation (its `T.compact`), and the caller's compiled bundle records that implementation's verifier-key fingerprint (`expectedVk`). A mismatch means the address passed for the `T` argument points at a different contract than the one the caller was linked to. ## Extends[​](#extends "Direct link to Extends") * [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractInterfaceMismatchError( calleeAddress, circuitId, expectedVerifierKeyHash, actualVerifierKeyHash): ContractInterfaceMismatchError; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### calleeAddress[​](#calleeaddress "Direct link to calleeAddress") `string` ##### circuitId[​](#circuitid "Direct link to circuitId") `string` ##### expectedVerifierKeyHash[​](#expectedverifierkeyhash "Direct link to expectedVerifierKeyHash") `string` ##### actualVerifierKeyHash[​](#actualverifierkeyhash "Direct link to actualVerifierKeyHash") `string` #### Returns[​](#returns "Direct link to Returns") `ContractInterfaceMismatchError` #### Overrides[​](#overrides "Direct link to Overrides") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`constructor`](/api-reference/compact-runtime/classes/CompactError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### actualVerifierKeyHash[​](#actualverifierkeyhash-1 "Direct link to actualVerifierKeyHash") ``` readonly actualVerifierKeyHash: string; ``` *** ### calleeAddress[​](#calleeaddress-1 "Direct link to calleeAddress") ``` readonly calleeAddress: string; ``` *** ### circuitId[​](#circuitid-1 "Direct link to circuitId") ``` readonly circuitId: string; ``` *** ### expectedVerifierKeyHash[​](#expectedverifierkeyhash-1 "Direct link to expectedVerifierKeyHash") ``` readonly expectedVerifierKeyHash: string; ``` *** ### isCompactError[​](#iscompacterror "Direct link to isCompactError") ``` readonly isCompactError: true = true; ``` #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`isCompactError`](/api-reference/compact-runtime/classes/CompactError.md#iscompacterror) *** ### message[​](#message "Direct link to message") ``` message: string; ``` #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`message`](/api-reference/compact-runtime/classes/CompactError.md#message) *** ### name[​](#name "Direct link to name") ``` name: string; ``` #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`name`](/api-reference/compact-runtime/classes/CompactError.md#name) *** ### stack?[​](#stack "Direct link to stack?") ``` optional stack: string; ``` #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`stack`](/api-reference/compact-runtime/classes/CompactError.md#stack) *** ### stackTraceLimit[​](#stacktracelimit "Direct link to stackTraceLimit") ``` static stackTraceLimit: number; ``` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured *after* the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. #### Inherited from[​](#inherited-from-4 "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`stackTraceLimit`](/api-reference/compact-runtime/classes/CompactError.md#stacktracelimit) ## Methods[​](#methods "Direct link to Methods") ### captureStackTrace()[​](#capturestacktrace "Direct link to captureStackTrace()") ``` static captureStackTrace(targetObject, constructorOpt?): void; ``` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ``` const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ``` function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### targetObject[​](#targetobject "Direct link to targetObject") `object` ##### constructorOpt?[​](#constructoropt "Direct link to constructorOpt?") `Function` #### Returns[​](#returns-1 "Direct link to Returns") `void` #### Inherited from[​](#inherited-from-5 "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`captureStackTrace`](/api-reference/compact-runtime/classes/CompactError.md#capturestacktrace) *** ### prepareStackTrace()[​](#preparestacktrace "Direct link to prepareStackTrace()") ``` static prepareStackTrace(err, stackTraces): any; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### err[​](#err "Direct link to err") `Error` ##### stackTraces[​](#stacktraces "Direct link to stackTraces") `CallSite`\[] #### Returns[​](#returns-2 "Direct link to Returns") `any` #### See[​](#see "Direct link to See") #### Inherited from[​](#inherited-from-6 "Direct link to Inherited from") [`CompactError`](/api-reference/compact-runtime/classes/CompactError.md).[`prepareStackTrace`](/api-reference/compact-runtime/classes/CompactError.md#preparestacktrace) --- # ContractMaintenanceAuthority > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractMaintenanceAuthority # Class: ContractMaintenanceAuthority A committee permitted to make changes to this contract. If a threshold of the public keys in this committee sign off, they can change the rules of this contract, or recompile it for a new version. If the threshold is greater than the number of committee members, it is impossible for them to sign anything. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractMaintenanceAuthority( committee, threshold, counter?): ContractMaintenanceAuthority; ``` Constructs a new authority from its components If not supplied, `counter` will default to `0n`. Values should be non-negative, and at most 2^32 - 1. At deployment, `counter` must be `0n`, and any subsequent update should set counter to exactly one greater than the current value. #### Parameters[​](#parameters "Direct link to Parameters") ##### committee[​](#committee "Direct link to committee") [`SignatureVerifyingKey`](/api-reference/compact-runtime/type-aliases/SignatureVerifyingKey.md)\[] ##### threshold[​](#threshold "Direct link to threshold") `number` ##### counter?[​](#counter "Direct link to counter?") `bigint` #### Returns[​](#returns "Direct link to Returns") `ContractMaintenanceAuthority` ## Properties[​](#properties "Direct link to Properties") ### committee[​](#committee-1 "Direct link to committee") ``` readonly committee: SignatureVerifyingKey[]; ``` The committee public keys *** ### counter[​](#counter-1 "Direct link to counter") ``` readonly counter: bigint; ``` The replay protection counter *** ### threshold[​](#threshold-1 "Direct link to threshold") ``` readonly threshold: number; ``` How many keys must sign rule changes ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractMaintenanceAuthority; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `ContractMaintenanceAuthority` --- # ContractOperation > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractOperation # Class: ContractOperation An individual operation, or entry point of a contract, consisting primarily of a ZK verifier keys, potentially for different versions of the proving system. Only the latest available version is exposed to this API. Note that the serialized form of the key is checked on initialization ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractOperation(): ContractOperation; ``` #### Returns[​](#returns "Direct link to Returns") `ContractOperation` ## Properties[​](#properties "Direct link to Properties") ### verifierKey[​](#verifierkey "Direct link to verifierKey") ``` verifierKey: Uint8Array; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractOperation; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `ContractOperation` --- # ContractState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractState # Class: ContractState The state of a contract, consisting primarily of the [data](#data) accessible directly to the contract, and the map of [ContractOperation](/api-reference/compact-runtime/classes/ContractOperation.md)s that can be called on it, the keys of which can be accessed with [operations](#operations), and the individual operations can be read with [operation](#operation) and written to with [setOperation](#setoperation). ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractState(): ContractState; ``` Creates a blank contract state #### Returns[​](#returns "Direct link to Returns") `ContractState` ## Properties[​](#properties "Direct link to Properties") ### balance[​](#balance "Direct link to balance") ``` balance: Map; ``` The public balances held by this contract *** ### data[​](#data "Direct link to data") ``` data: ChargedState; ``` The current value of the primary state of the contract *** ### maintenanceAuthority[​](#maintenanceauthority "Direct link to maintenanceAuthority") ``` maintenanceAuthority: ContractMaintenanceAuthority; ``` The maintenance authority associated with this contract ## Methods[​](#methods "Direct link to Methods") ### operation()[​](#operation "Direct link to operation()") ``` operation(operation): ContractOperation | undefined; ``` Get the operation at a specific entry point name #### Parameters[​](#parameters "Direct link to Parameters") ##### operation[​](#operation-1 "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> #### Returns[​](#returns-1 "Direct link to Returns") [`ContractOperation`](/api-reference/compact-runtime/classes/ContractOperation.md) | `undefined` *** ### operations()[​](#operations "Direct link to operations()") ``` operations(): (string | Uint8Array)[]; ``` Return a list of the entry points currently registered on this contract #### Returns[​](#returns-2 "Direct link to Returns") (`string` | `Uint8Array`<`ArrayBufferLike`>)\[] *** ### query()[​](#query "Direct link to query()") ``` query(query, cost_model): GatherResult[]; ``` Runs a series of operations against the current state, and returns the results #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### query[​](#query-1 "Direct link to query") [`Op`](/api-reference/compact-runtime/type-aliases/Op.md)<`null`>\[] ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/compact-runtime/classes/CostModel.md) #### Returns[​](#returns-3 "Direct link to Returns") [`GatherResult`](/api-reference/compact-runtime/type-aliases/GatherResult.md)\[] *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-4 "Direct link to Returns") `Uint8Array` *** ### setOperation()[​](#setoperation "Direct link to setOperation()") ``` setOperation(operation, value): void; ``` Set a specific entry point name to contain a given operation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### operation[​](#operation-2 "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> ##### value[​](#value "Direct link to value") [`ContractOperation`](/api-reference/compact-runtime/classes/ContractOperation.md) #### Returns[​](#returns-5 "Direct link to Returns") `void` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractState; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-7 "Direct link to Returns") `ContractState` --- # CostModel > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CostModel # Class: CostModel A cost model for calculating transaction fees ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` *** ### initialCostModel()[​](#initialcostmodel "Direct link to initialCostModel()") ``` static initialCostModel(): CostModel; ``` The initial cost model of Midnight #### Returns[​](#returns-1 "Direct link to Returns") `CostModel` --- # QueryContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / QueryContext # Class: QueryContext Provides the information needed to fully process a transaction, including information about the rest of the transaction, and the state of the chain at the time of execution. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new QueryContext(state, address): QueryContext; ``` Construct a basic context from a contract's address and current state value #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`ChargedState`](/api-reference/compact-runtime/classes/ChargedState.md) ##### address[​](#address "Direct link to address") `string` #### Returns[​](#returns "Direct link to Returns") `QueryContext` ## Properties[​](#properties "Direct link to Properties") ### address[​](#address-1 "Direct link to address") ``` readonly address: string; ``` The address of the contract *** ### block[​](#block "Direct link to block") ``` block: CallContext; ``` The block-level information accessible to the contract *** ### comIndices[​](#comindices "Direct link to comIndices") ``` readonly comIndices: Map; ``` The commitment indices map accessible to the contract, primarily via [qualify](#qualify) *** ### effects[​](#effects "Direct link to effects") ``` effects: Effects; ``` The effects that occurred during execution against this context, should match those declared in a [Transcript](/api-reference/compact-runtime/type-aliases/Transcript.md) *** ### state[​](#state-1 "Direct link to state") ``` readonly state: ChargedState; ``` The current contract state retained in the context ## Methods[​](#methods "Direct link to Methods") ### insertCommitment()[​](#insertcommitment "Direct link to insertCommitment()") ``` insertCommitment(comm, index): QueryContext; ``` Register a given coin commitment as being accessible at a specific index, for use when receiving coins in-contract, and needing to record their index to later spend them #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### comm[​](#comm "Direct link to comm") `string` ##### index[​](#index "Direct link to index") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `QueryContext` *** ### qualify()[​](#qualify "Direct link to qualify()") ``` qualify(coin): Value | undefined; ``` **`Internal`** Internal counterpart to [insertCommitment](#insertcommitment); upgrades an encoded [ShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) to an encoded [QualifiedShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md) using the inserted commitments #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) | `undefined` *** ### query()[​](#query "Direct link to query()") ``` query( ops, cost_model, gas_limit?): QueryResults; ``` Runs a sequence of operations in gather mode, returning the results of the gather. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### ops[​](#ops "Direct link to ops") [`Op`](/api-reference/compact-runtime/type-aliases/Op.md)<`null`>\[] ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/compact-runtime/classes/CostModel.md) ##### gas\_limit?[​](#gas_limit "Direct link to gas_limit?") [`RunningCost`](/api-reference/compact-runtime/type-aliases/RunningCost.md) #### Returns[​](#returns-3 "Direct link to Returns") [`QueryResults`](/api-reference/compact-runtime/classes/QueryResults.md) *** ### runTranscript()[​](#runtranscript "Direct link to runTranscript()") ``` runTranscript(transcript, cost_model): QueryContext; ``` Runs a transcript in verifying mode against the current query context, outputting a new query context, with the [state](#state) and [effects](#effects) from after the execution. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### transcript[​](#transcript "Direct link to transcript") [`Transcript`](/api-reference/compact-runtime/type-aliases/Transcript.md)<[`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md)> ##### cost\_model[​](#cost_model-1 "Direct link to cost_model") [`CostModel`](/api-reference/compact-runtime/classes/CostModel.md) #### Returns[​](#returns-4 "Direct link to Returns") `QueryContext` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` *** ### toVmStack()[​](#tovmstack "Direct link to toVmStack()") ``` toVmStack(): VmStack; ``` Converts the QueryContext to [VmStack](/api-reference/compact-runtime/classes/VmStack.md). #### Returns[​](#returns-6 "Direct link to Returns") [`VmStack`](/api-reference/compact-runtime/classes/VmStack.md) --- # QueryResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / QueryResults # Class: QueryResults The results of making a query against a specific state or context ## Properties[​](#properties "Direct link to Properties") ### context[​](#context "Direct link to context") ``` readonly context: QueryContext; ``` The context state after executing the query. This can be used to execute further queries *** ### events[​](#events "Direct link to events") ``` readonly events: GatherResult[]; ``` Any events/results that occurred during or from the query *** ### gasCost[​](#gascost "Direct link to gasCost") ``` readonly gasCost: RunningCost; ``` The measured cost of executing the query ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # StateBoundedMerkleTree > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / StateBoundedMerkleTree # Class: StateBoundedMerkleTree Represents a fixed-depth Merkle tree storing hashed data, whose preimages are unknown ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new StateBoundedMerkleTree(height): StateBoundedMerkleTree; ``` Create a blank tree with the given height #### Parameters[​](#parameters "Direct link to Parameters") ##### height[​](#height "Direct link to height") `number` #### Returns[​](#returns "Direct link to Returns") `StateBoundedMerkleTree` ## Properties[​](#properties "Direct link to Properties") ### height[​](#height-1 "Direct link to height") ``` readonly height: number; ``` ## Methods[​](#methods "Direct link to Methods") ### collapse()[​](#collapse "Direct link to collapse()") ``` collapse(start, end): StateBoundedMerkleTree; ``` **`Internal`** Erases all but necessary hashes between, and inclusive of, `start` and `end` inidices #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### start[​](#start "Direct link to start") `bigint` ##### end[​](#end "Direct link to end") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `StateBoundedMerkleTree` #### Throws[​](#throws "Direct link to Throws") If the indices are out-of-bounds for the tree, or `end < start` *** ### findPathForLeaf()[​](#findpathforleaf "Direct link to findPathForLeaf()") ``` findPathForLeaf( leaf, indexStart?, indexEnd?, alreadyHashed?): AlignedValue | undefined; ``` **`Internal`** Internal implementation of the finding path primitive. Returns undefined if the leaf is not in the tree. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### leaf[​](#leaf "Direct link to leaf") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ##### indexStart?[​](#indexstart "Direct link to indexStart?") `bigint` ##### indexEnd?[​](#indexend "Direct link to indexEnd?") `bigint` ##### alreadyHashed?[​](#alreadyhashed "Direct link to alreadyHashed?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) | `undefined` *** ### pathForLeaf()[​](#pathforleaf "Direct link to pathForLeaf()") ``` pathForLeaf(index, leaf): AlignedValue; ``` **`Internal`** Internal implementation of the path construction primitive #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### index[​](#index "Direct link to index") `bigint` ##### leaf[​](#leaf-1 "Direct link to leaf") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) #### Throws[​](#throws-1 "Direct link to Throws") If the index is out-of-bounds for the tree *** ### rehash()[​](#rehash "Direct link to rehash()") ``` rehash(): StateBoundedMerkleTree; ``` Rehashes the tree, updating all internal hashes and ensuring all node hashes are present. Necessary because the onchain runtime does not automatically rehash trees. #### Returns[​](#returns-4 "Direct link to Returns") `StateBoundedMerkleTree` *** ### root()[​](#root "Direct link to root()") ``` root(): AlignedValue | undefined; ``` **`Internal`** Internal implementation of the merkle tree root primitive. Returns undefined if the tree has not been fully hashed. #### Returns[​](#returns-5 "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) | `undefined` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### update()[​](#update "Direct link to update()") ``` update(index, leaf): StateBoundedMerkleTree; ``` Inserts a value into the Merkle tree, returning the updated tree #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### index[​](#index-1 "Direct link to index") `bigint` ##### leaf[​](#leaf-2 "Direct link to leaf") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-7 "Direct link to Returns") `StateBoundedMerkleTree` #### Throws[​](#throws-2 "Direct link to Throws") If the index is out-of-bounds for the tree --- # StateMap > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / StateMap # Class: StateMap Represents a key-value map, where keys are [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md)s, and values are [StateValue](/api-reference/compact-runtime/classes/StateValue.md)s. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new StateMap(): StateMap; ``` #### Returns[​](#returns "Direct link to Returns") `StateMap` ## Methods[​](#methods "Direct link to Methods") ### get()[​](#get "Direct link to get()") ``` get(key): StateValue | undefined; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### key[​](#key "Direct link to key") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-1 "Direct link to Returns") [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) | `undefined` *** ### insert()[​](#insert "Direct link to insert()") ``` insert(key, value): StateMap; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### key[​](#key-1 "Direct link to key") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) #### Returns[​](#returns-2 "Direct link to Returns") `StateMap` *** ### keys()[​](#keys "Direct link to keys()") ``` keys(): AlignedValue[]; ``` #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md)\[] *** ### remove()[​](#remove "Direct link to remove()") ``` remove(key): StateMap; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### key[​](#key-2 "Direct link to key") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-4 "Direct link to Returns") `StateMap` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` --- # StateValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / StateValue # Class: StateValue Represents the core of a contract's state, and recursively represents each of its components. There are different *classes* of state values: * `null` * Cells of [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md)s * Maps from [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md)s to state values * Bounded Merkle trees containing [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md) leaves * Short (<= 15 element) arrays of state values State values are *immutable*, any operations that mutate states will return a new state instead. ## Methods[​](#methods "Direct link to Methods") ### arrayPush()[​](#arraypush "Direct link to arrayPush()") ``` arrayPush(value): StateValue; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") `StateValue` #### Returns[​](#returns "Direct link to Returns") `StateValue` *** ### asArray()[​](#asarray "Direct link to asArray()") ``` asArray(): StateValue[] | undefined; ``` #### Returns[​](#returns-1 "Direct link to Returns") `StateValue`\[] | `undefined` *** ### asBoundedMerkleTree()[​](#asboundedmerkletree "Direct link to asBoundedMerkleTree()") ``` asBoundedMerkleTree(): StateBoundedMerkleTree | undefined; ``` #### Returns[​](#returns-2 "Direct link to Returns") [`StateBoundedMerkleTree`](/api-reference/compact-runtime/classes/StateBoundedMerkleTree.md) | `undefined` *** ### asCell()[​](#ascell "Direct link to asCell()") ``` asCell(): AlignedValue; ``` #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) *** ### asMap()[​](#asmap "Direct link to asMap()") ``` asMap(): StateMap | undefined; ``` #### Returns[​](#returns-4 "Direct link to Returns") [`StateMap`](/api-reference/compact-runtime/classes/StateMap.md) | `undefined` *** ### encode()[​](#encode "Direct link to encode()") ``` encode(): EncodedStateValue; ``` **`Internal`** #### Returns[​](#returns-5 "Direct link to Returns") [`EncodedStateValue`](/api-reference/compact-runtime/type-aliases/EncodedStateValue.md) *** ### logSize()[​](#logsize "Direct link to logSize()") ``` logSize(): number; ``` #### Returns[​](#returns-6 "Direct link to Returns") `number` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-7 "Direct link to Returns") `string` *** ### type()[​](#type "Direct link to type()") ``` type(): "cell" | "map" | "array" | "null" | "boundedMerkleTree"; ``` #### Returns[​](#returns-8 "Direct link to Returns") `"cell"` | `"map"` | `"array"` | `"null"` | `"boundedMerkleTree"` *** ### decode()[​](#decode "Direct link to decode()") ``` static decode(value): StateValue; ``` **`Internal`** #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`EncodedStateValue`](/api-reference/compact-runtime/type-aliases/EncodedStateValue.md) #### Returns[​](#returns-9 "Direct link to Returns") `StateValue` *** ### newArray()[​](#newarray "Direct link to newArray()") ``` static newArray(): StateValue; ``` #### Returns[​](#returns-10 "Direct link to Returns") `StateValue` *** ### newBoundedMerkleTree()[​](#newboundedmerkletree "Direct link to newBoundedMerkleTree()") ``` static newBoundedMerkleTree(tree): StateValue; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### tree[​](#tree "Direct link to tree") [`StateBoundedMerkleTree`](/api-reference/compact-runtime/classes/StateBoundedMerkleTree.md) #### Returns[​](#returns-11 "Direct link to Returns") `StateValue` *** ### newCell()[​](#newcell "Direct link to newCell()") ``` static newCell(value): StateValue; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### value[​](#value-2 "Direct link to value") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-12 "Direct link to Returns") `StateValue` *** ### newMap()[​](#newmap "Direct link to newMap()") ``` static newMap(map): StateValue; ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### map[​](#map "Direct link to map") [`StateMap`](/api-reference/compact-runtime/classes/StateMap.md) #### Returns[​](#returns-13 "Direct link to Returns") `StateValue` *** ### newNull()[​](#newnull "Direct link to newNull()") ``` static newNull(): StateValue; ``` #### Returns[​](#returns-14 "Direct link to Returns") `StateValue` --- # VmResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / VmResults # Class: VmResults Represents the results of a VM call ## Properties[​](#properties "Direct link to Properties") ### events[​](#events "Direct link to events") ``` readonly events: GatherResult[]; ``` The events that got emitted by this VM invocation *** ### gasCost[​](#gascost "Direct link to gasCost") ``` readonly gasCost: RunningCost; ``` The computed gas cost of running this VM invocation *** ### stack[​](#stack "Direct link to stack") ``` readonly stack: VmStack; ``` The VM stack at the end of the VM invocation ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # VmStack > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / VmStack # Class: VmStack Represents the state of the VM's stack at a specific point. The stack is an array of [StateValue](/api-reference/compact-runtime/classes/StateValue.md)s, each of which is also annotated with whether it is "strong" or "weak"; that is, whether it is permitted to be stored on-chain or not. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new VmStack(): VmStack; ``` #### Returns[​](#returns "Direct link to Returns") `VmStack` ## Methods[​](#methods "Direct link to Methods") ### get()[​](#get "Direct link to get()") ``` get(idx): StateValue | undefined; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### idx[​](#idx "Direct link to idx") `number` #### Returns[​](#returns-1 "Direct link to Returns") [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) | `undefined` *** ### isStrong()[​](#isstrong "Direct link to isStrong()") ``` isStrong(idx): boolean | undefined; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### idx[​](#idx-1 "Direct link to idx") `number` #### Returns[​](#returns-2 "Direct link to Returns") `boolean` | `undefined` *** ### length()[​](#length "Direct link to length()") ``` length(): number; ``` #### Returns[​](#returns-3 "Direct link to Returns") `number` *** ### push()[​](#push "Direct link to push()") ``` push(value, is_strong): void; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) ##### is\_strong[​](#is_strong "Direct link to is_strong") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `void` *** ### removeLast()[​](#removelast "Direct link to removeLast()") ``` removeLast(): void; ``` #### Returns[​](#returns-5 "Direct link to Returns") `void` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` --- # NetworkId > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / NetworkId # Enumeration: NetworkId The network currently being targeted ## Enumeration Members[​](#enumeration-members "Direct link to Enumeration Members") ### DevNet[​](#devnet "Direct link to DevNet") ``` DevNet: 1; ``` A developer network, not guaranteed to be persistent *** ### MainNet[​](#mainnet "Direct link to MainNet") ``` MainNet: 3; ``` The Midnight mainnet *** ### TestNet[​](#testnet "Direct link to TestNet") ``` TestNet: 2; ``` A persistent testnet *** ### Undeployed[​](#undeployed "Direct link to Undeployed") ``` Undeployed: 0; ``` A local test network --- # addField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / addField # Function: addField() ``` function addField(x, y): bigint; ``` Field addition returns the result of adding x and y, wrapping if necessary x and y are assumed to be values in the range \[0, FIELD\_MODULUS) ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # alignedConcat > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / alignedConcat # Function: alignedConcat() ``` function alignedConcat(...values): AlignedValue; ``` **`Internal`** Concatenates multiple [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md)s ## Parameters[​](#parameters "Direct link to Parameters") ### values[​](#values "Direct link to values") ...[`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md)\[] ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) --- # assert > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / assert # Function: assert() ``` function assert(b, s): void; ``` **`Internal`** Compiler internal for assertions ## Parameters[​](#parameters "Direct link to Parameters") ### b[​](#b "Direct link to b") `boolean` ### s[​](#s "Direct link to s") `string` ## Returns[​](#returns "Direct link to Returns") `void` --- # assertDefined > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / assertDefined # Function: assertDefined() ``` function assertDefined(t, name): asserts t is NonNullable; ``` **`Internal`** Compiler internal for asserting an object is non-nullable. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### T[​](#t "Direct link to T") `T` ## Parameters[​](#parameters "Direct link to Parameters") ### t[​](#t-1 "Direct link to t") `T` | `undefined` ### name[​](#name "Direct link to name") `string` ## Returns[​](#returns "Direct link to Returns") `asserts t is NonNullable` --- # assertIsContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / assertIsContractAddress # Function: assertIsContractAddress() ``` function assertIsContractAddress(x): asserts x is string; ``` ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `unknown` ## Returns[​](#returns "Direct link to Returns") `asserts x is string` --- # assertUndefined > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / assertUndefined # Function: assertUndefined() ``` function assertUndefined(t, name): void; ``` **`Internal`** Compiler internal for asserting an object is nullable. ## Parameters[​](#parameters "Direct link to Parameters") ### t[​](#t "Direct link to t") `any` ### name[​](#name "Direct link to name") `string` ## Returns[​](#returns "Direct link to Returns") `void` --- # bigIntModFr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / bigIntModFr # Function: bigIntModFr() ``` function bigIntModFr(x): bigint; ``` Takes a bigint modulus the proof systems scalar field ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # bigIntToValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / bigIntToValue # Function: bigIntToValue() ``` function bigIntToValue(x): Value; ``` **`Internal`** Internal conversion between bigints and their field-aligned binary representation ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # checkProofData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / checkProofData # Function: checkProofData() ``` function checkProofData(zkir, proofData): void; ``` Verifies a given [ProofData](/api-reference/compact-runtime/interfaces/ProofData.md) satisfies the constrains of a ZK circuit descripted by given IR ## Parameters[​](#parameters "Direct link to Parameters") ### zkir[​](#zkir "Direct link to zkir") `string` ### proofData[​](#proofdata "Direct link to proofData") [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md) ## Returns[​](#returns "Direct link to Returns") `void` ## Throws[​](#throws "Direct link to Throws") If the circuit is not satisfied --- # checkRuntimeVersion > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / checkRuntimeVersion # Function: checkRuntimeVersion() ``` function checkRuntimeVersion(expectedRuntimeVersionString): void; ``` ## Parameters[​](#parameters "Direct link to Parameters") ### expectedRuntimeVersionString[​](#expectedruntimeversionstring "Direct link to expectedRuntimeVersionString") `string` ## Returns[​](#returns "Direct link to Returns") `void` --- # coinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / coinCommitment # Function: coinCommitment() ``` function coinCommitment(coin, recipient): AlignedValue; ``` **`Internal`** Internal implementation of the coin commitment primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ### recipient[​](#recipient "Direct link to recipient") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) --- # communicationCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / communicationCommitment # Function: communicationCommitment() ``` function communicationCommitment( input, output, rand): string; ``` Computes the communication commitment corresponding to an input/output pair and randomness. ## Parameters[​](#parameters "Direct link to Parameters") ### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ### rand[​](#rand "Direct link to rand") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # communicationCommitmentRandomness > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / communicationCommitmentRandomness # Function: communicationCommitmentRandomness() ``` function communicationCommitmentRandomness(): string; ``` Samples a new [CommunicationCommitmentRand](/api-reference/compact-runtime/type-aliases/CommunicationCommitmentRand.md) uniformly ## Returns[​](#returns "Direct link to Returns") `string` --- # constructJubjubPoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / constructJubjubPoint # Function: constructJubjubPoint() ``` function constructJubjubPoint(x, y): JubjubPoint; ``` The Compact builtin `constructJubjubPoint` function This function constructs a Compact `JubjubPoint` from the x- and y-coordinates. NOTE that it does not check that the coordinates represent a valid point on the Jubjub curve. ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # constructorContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / constructorContext # Function: constructorContext() ``` function constructorContext(initialPrivateState, coinPublicKey): ConstructorContext; ``` Creates a new [ConstructorContext](/api-reference/compact-runtime/interfaces/ConstructorContext.md) with the given initial private state and an empty Zswap local state. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### T[​](#t "Direct link to T") `T` ## Parameters[​](#parameters "Direct link to Parameters") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") `T` The private state to use to execute the contract's constructor. ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") `string` The Zswap coin public key of the user executing the contract. ## Returns[​](#returns "Direct link to Returns") [`ConstructorContext`](/api-reference/compact-runtime/interfaces/ConstructorContext.md)<`T`> --- # contractDependencies > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / contractDependencies # Function: contractDependencies() ``` function contractDependencies(contractReferenceLocations, state): string[]; ``` // TODO: Remove compiler support for contract dependencies once CCCs land. Given a [StateValue](/api-reference/compact-runtime/classes/StateValue.md) representing the current ledger state of a contract, uses the [ContractReferenceLocations](/api-reference/compact-runtime/type-aliases/ContractReferenceLocations.md) object produced by the Compact compiler to extract the current contract addresses present in the given ledger state. The produced contract addresses represent the contracts on which the root contract depends. The dependencies are used in a multi-contract setting to fetch the ledger states of all contracts on which the root contract depends prior to execution. NOTE: The given [ContractReferenceLocations](/api-reference/compact-runtime/type-aliases/ContractReferenceLocations.md) must be from the contract executable containing the ledger state constructor that produced the given [StateValue](/api-reference/compact-runtime/classes/StateValue.md). ## Parameters[​](#parameters "Direct link to Parameters") ### contractReferenceLocations[​](#contractreferencelocations "Direct link to contractReferenceLocations") [`ContractReferenceLocations`](/api-reference/compact-runtime/type-aliases/ContractReferenceLocations.md) A data structure pointing to contract references in the ledger state of the root contract. ### state[​](#state "Direct link to state") [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) The current ledger state of the root contract. ## Returns[​](#returns "Direct link to Returns") `string`\[] A list of all contract addresses (references) present in the given ledger state. ## Remarks[​](#remarks "Direct link to Remarks") The algorithm has three main stages: 1. It unwraps the [PublicLedgerSegments](/api-reference/compact-runtime/type-aliases/PublicLedgerSegments.md) in the given [ContractReferenceLocations](/api-reference/compact-runtime/type-aliases/ContractReferenceLocations.md) until a [SparseCompactADT](/api-reference/compact-runtime/type-aliases/SparseCompactADT.md) is reached. Each time a [PublicLedgerSegments](/api-reference/compact-runtime/type-aliases/PublicLedgerSegments.md) is unwrapped, it casts the current state value to a state value array and proceeds recursively with each of the state values and unwrapped ledger segments. 2. It unwraps each [SparseCompactADT](/api-reference/compact-runtime/type-aliases/SparseCompactADT.md) in the current [PublicLedgerSegments](/api-reference/compact-runtime/type-aliases/PublicLedgerSegments.md) until a [SparseCompactType](/api-reference/compact-runtime/type-aliases/SparseCompactType.md) is reached. Each time a [SparseCompactADT](/api-reference/compact-runtime/type-aliases/SparseCompactADT.md) is unwrapped, it casts the current state value to a state representation indicated by the [SparseCompactADT](/api-reference/compact-runtime/type-aliases/SparseCompactADT.md). 3. Once the current state can no longer be reduced, it must represent a Compact contract address somewhere inside the state, and that contract address is added to the dependency set. --- # convert\_bigint\_to\_Uint8Array > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.8.1**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convert\_bigint\_to\_Uint8Array # Function: convert\_bigint\_to\_Uint8Array() ``` function convert_bigint_to_Uint8Array(n, x): Uint8Array; ``` **`Internal`** Compiler internal for typecasts ## Parameters[​](#parameters "Direct link to Parameters") ### n[​](#n "Direct link to n") `number` ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # convert\_Uint8Array\_to\_bigint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.8.1**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convert\_Uint8Array\_to\_bigint # Function: convert\_Uint8Array\_to\_bigint() ``` function convert_Uint8Array_to_bigint(n, a): bigint; ``` **`Internal`** Compiler internal for typecasts ## Parameters[​](#parameters "Direct link to Parameters") ### n[​](#n "Direct link to n") `number` ### a[​](#a "Direct link to a") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # convertBigintToBytes > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convertBigintToBytes # Function: convertBigintToBytes() ``` function convertBigintToBytes( n, x, src): Uint8Array; ``` **`Internal`** Compiler internal for typecasts ## Parameters[​](#parameters "Direct link to Parameters") ### n[​](#n "Direct link to n") `number` ### x[​](#x "Direct link to x") `bigint` ### src[​](#src "Direct link to src") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # convertBytesToField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convertBytesToField # Function: convertBytesToField() ``` function convertBytesToField( maxval, n, a, name, src): bigint; ``` **`Internal`** Compiler internal for typecasts ## Parameters[​](#parameters "Direct link to Parameters") ### maxval[​](#maxval "Direct link to maxval") `bigint` ### n[​](#n "Direct link to n") `number` ### a[​](#a "Direct link to a") `Uint8Array` ### name[​](#name "Direct link to name") `string` ### src[​](#src "Direct link to src") `string` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # convertBytesToUint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convertBytesToUint # Function: convertBytesToUint() ``` function convertBytesToUint( maxval, n, a, name, src): bigint; ``` **`Internal`** Compiler internal for typecasts ## Parameters[​](#parameters "Direct link to Parameters") ### maxval[​](#maxval "Direct link to maxval") `bigint` ### n[​](#n "Direct link to n") `number` ### a[​](#a "Direct link to a") `Uint8Array` ### name[​](#name "Direct link to name") `string` ### src[​](#src "Direct link to src") `string` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # convertFieldToBytes > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convertFieldToBytes # Function: convertFieldToBytes() ``` function convertFieldToBytes( n, x, src): Uint8Array; ``` **`Internal`** Compiler internal for typecasts ## Parameters[​](#parameters "Direct link to Parameters") ### n[​](#n "Direct link to n") `number` ### x[​](#x "Direct link to x") `bigint` ### src[​](#src "Direct link to src") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # convertNumericToJubjubScalar > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / convertNumericToJubjubScalar # Function: convertNumericToJubjubScalar() ``` function convertNumericToJubjubScalar(x): bigint; ``` Conversion of a native field or unsigned integer value to a JubjubScalar The native field is BLS12-381 scalar, which has a larger field modulus than the Jubjub scalar field. The value is converted modulo the Jubjub scalar field modulus. ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # copyCircuitContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / copyCircuitContext # Function: copyCircuitContext() ``` function copyCircuitContext(context): CircuitContext; ``` **`Internal`** ## Parameters[​](#parameters "Direct link to Parameters") ### context[​](#context "Direct link to context") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) ## Returns[​](#returns "Direct link to Returns") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) --- # createCallContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createCallContext # Function: createCallContext() ``` function createCallContext( circuitId, contractAddress, coinPublicKeyOrZswapState, contractState, privateState, maybeTime?, parentBlockHash?, caller?): CallContext; ``` ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` ## Parameters[​](#parameters "Direct link to Parameters") ### circuitId[​](#circuitid "Direct link to circuitId") `string` ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` ### coinPublicKeyOrZswapState[​](#coinpublickeyorzswapstate "Direct link to coinPublicKeyOrZswapState") `string` | [`EncodedZswapLocalState`](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) | [`EncodedCoinPublicKey`](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md) | [`ZswapLocalState`](/api-reference/compact-runtime/interfaces/ZswapLocalState.md) ### contractState[​](#contractstate "Direct link to contractState") [`ContractState`](/api-reference/compact-runtime/classes/ContractState.md) | [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) | [`ChargedState`](/api-reference/compact-runtime/classes/ChargedState.md) ### privateState[​](#privatestate "Direct link to privateState") `PS` ### maybeTime?[​](#maybetime "Direct link to maybeTime?") `number` ### parentBlockHash?[​](#parentblockhash "Direct link to parentBlockHash?") `string` ### caller?[​](#caller "Direct link to caller?") [`PublicAddress`](/api-reference/compact-runtime/type-aliases/PublicAddress.md) ## Returns[​](#returns "Direct link to Returns") `CallContext`<`PS`> --- # createCircuitContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createCircuitContext # Function: createCircuitContext() ``` function createCircuitContext( circuitId, contractAddress, coinPublicKeyOrZswapState, contractState, privateState, stateProvider?, gasLimit?, costModel?, time?, parentBlockHash?, reentrancyGuard?): CircuitContext; ``` Entry point for constructing the [CircuitContext](/api-reference/compact-runtime/interfaces/CircuitContext.md) to pass as an argument to a circuit. Always use this function to set up the initial circuit context. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` ## Parameters[​](#parameters "Direct link to Parameters") ### circuitId[​](#circuitid "Direct link to circuitId") `string` The name of the circuit being executed. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The address of the contract defining the circuit being executed. ### coinPublicKeyOrZswapState[​](#coinpublickeyorzswapstate "Direct link to coinPublicKeyOrZswapState") The initial Zswap local state information - used for tracking shielded coin transfers. `string` | [`EncodedZswapLocalState`](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) | [`EncodedCoinPublicKey`](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md) | [`ZswapLocalState`](/api-reference/compact-runtime/interfaces/ZswapLocalState.md) ### contractState[​](#contractstate "Direct link to contractState") The initial ledger state to execute the contract again - most often a snapshot fetched from the chain. [`ContractState`](/api-reference/compact-runtime/classes/ContractState.md) | [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) | [`ChargedState`](/api-reference/compact-runtime/classes/ChargedState.md) ### privateState[​](#privatestate "Direct link to privateState") `PS` The initial witness / private state to execute the contract again - most often a snapshot fetched from local storage. ### stateProvider?[​](#stateprovider "Direct link to stateProvider?") [`ContractStateProvider`](/api-reference/compact-runtime/interfaces/ContractStateProvider.md) The provider to use to dynamically fetch on-chain contract state. This is only used to execute cross-contract calls, and is not needed if the circuit being executed does not perform any cross-contract calls. ### gasLimit?[​](#gaslimit "Direct link to gasLimit?") [`RunningCost`](/api-reference/compact-runtime/type-aliases/RunningCost.md) The maximum gas this contract should consume. ### costModel?[​](#costmodel "Direct link to costModel?") [`CostModel`](/api-reference/compact-runtime/classes/CostModel.md) The model capturing how much ledger operations cost. ### time?[​](#time "Direct link to time?") `number` The current time. Used to execute the block time related kernel operations. ### parentBlockHash?[​](#parentblockhash "Direct link to parentBlockHash?") `string` The hash of the block the transaction is being built on. Also passed to [ContractStateProvider](/api-reference/compact-runtime/interfaces/ContractStateProvider.md) to fetch the correct contract states when executing cross-contract calls. ### reentrancyGuard?[​](#reentrancyguard "Direct link to reentrancyGuard?") `boolean` When `true`, cross-contract calls that re-enter a contract already executing on the call stack (`A -> A`, or `A -> B -> A`) throw instead of running. On by default; pass `false` to opt out. ## Returns[​](#returns "Direct link to Returns") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md)<`PS`> --- # createConstructorContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createConstructorContext # Function: createConstructorContext() ``` function createConstructorContext(initialPrivateState, coinPublicKey): ConstructorContext; ``` Creates a new [ConstructorContext](/api-reference/compact-runtime/interfaces/ConstructorContext.md) with the given initial private state and an empty Zswap local state. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` ## Parameters[​](#parameters "Direct link to Parameters") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") `PS` The private state to use to execute the contract's constructor. ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") The Zswap coin public key of the user executing the contract. `string` | [`EncodedCoinPublicKey`](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md) ## Returns[​](#returns "Direct link to Returns") [`ConstructorContext`](/api-reference/compact-runtime/interfaces/ConstructorContext.md)<`PS`> --- # createInitialQueryContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createInitialQueryContext # Function: createInitialQueryContext() ``` function createInitialQueryContext( contractState, contractAddress, time, parentBlockHash?, caller?): QueryContext; ``` **`Internal`** ## Parameters[​](#parameters "Direct link to Parameters") ### contractState[​](#contractstate "Direct link to contractState") [`ContractState`](/api-reference/compact-runtime/classes/ContractState.md) | [`StateValue`](/api-reference/compact-runtime/classes/StateValue.md) | [`ChargedState`](/api-reference/compact-runtime/classes/ChargedState.md) ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` ### time[​](#time "Direct link to time") `number` ### parentBlockHash?[​](#parentblockhash "Direct link to parentBlockHash?") `string` ### caller?[​](#caller "Direct link to caller?") [`PublicAddress`](/api-reference/compact-runtime/type-aliases/PublicAddress.md) ## Returns[​](#returns "Direct link to Returns") [`QueryContext`](/api-reference/compact-runtime/classes/QueryContext.md) --- # createWitnessContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createWitnessContext # Function: createWitnessContext() ``` function createWitnessContext( ledger, privateState, contractAddress): WitnessContext; ``` **`Internal`** Internal constructor for [WitnessContext](/api-reference/compact-runtime/interfaces/WitnessContext.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### L[​](#l "Direct link to L") `L` ### PS[​](#ps "Direct link to PS") `PS` ## Parameters[​](#parameters "Direct link to Parameters") ### ledger[​](#ledger "Direct link to ledger") `L` ### privateState[​](#privatestate "Direct link to privateState") `PS` ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` ## Returns[​](#returns "Direct link to Returns") [`WitnessContext`](/api-reference/compact-runtime/interfaces/WitnessContext.md)<`L`, `PS`> --- # createZswapInput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createZswapInput # Function: createZswapInput() ``` function createZswapInput(circuitContext, qualifiedShieldedCoinInfo): []; ``` Adds a coin to the list of inputs consumed by the circuit. ## Parameters[​](#parameters "Direct link to Parameters") ### circuitContext[​](#circuitcontext "Direct link to circuitContext") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) The current circuit context. ### qualifiedShieldedCoinInfo[​](#qualifiedshieldedcoininfo "Direct link to qualifiedShieldedCoinInfo") [`EncodedQualifiedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedQualifiedShieldedCoinInfo.md) The input to consume. ## Returns[​](#returns "Direct link to Returns") \[] --- # createZswapOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / createZswapOutput # Function: createZswapOutput() ``` function createZswapOutput( circuitContext, coinInfo, recipient): []; ``` Adds a coin to the list of outputs produced by the circuit. ## Parameters[​](#parameters "Direct link to Parameters") ### circuitContext[​](#circuitcontext "Direct link to circuitContext") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md)<`unknown`> The current circuit context. ### coinInfo[​](#coininfo "Direct link to coinInfo") [`EncodedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md) The coin to produce. ### recipient[​](#recipient "Direct link to recipient") [`EncodedRecipient`](/api-reference/compact-runtime/interfaces/EncodedRecipient.md) The coin recipient - either a coin public key representing an end user or a contract address representing a contract. ## Returns[​](#returns "Direct link to Returns") \[] --- # crossContractCall > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / crossContractCall # Function: crossContractCall() ``` function crossContractCall( circuitContext, calleeModule, calleeCircuitId, calleeAddress, calleeIsPure, callerProofData, ... args): Promise; ``` **`Internal`** Calls a circuit defined in another contract from the currently executing contract and returns the result. ## Parameters[​](#parameters "Direct link to Parameters") ### circuitContext[​](#circuitcontext "Direct link to circuitContext") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) The current circuit context. ### calleeModule[​](#calleemodule "Direct link to calleeModule") `Module` The callee module containing TS executables. ### calleeCircuitId[​](#calleecircuitid "Direct link to calleeCircuitId") `string` The name of the circuit to be called in the contract to be called. ### calleeAddress[​](#calleeaddress "Direct link to calleeAddress") `string` The address of the contract to be called. ### calleeIsPure[​](#calleeispure "Direct link to calleeIsPure") `boolean` A flag indicating whether the circuit being called is pure. ### callerProofData[​](#callerproofdata "Direct link to callerProofData") [`PartialProofData`](/api-reference/compact-runtime/interfaces/PartialProofData.md) The proof data instance created when the caller circuit was initialized. ### args[​](#args "Direct link to args") ...`any`\[] The arguments to the circuit to be called. ## Returns[​](#returns "Direct link to Returns") `Promise`<`any`> --- # decodeCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeCoinInfo # Function: decodeCoinInfo() ``` function decodeCoinInfo(coin): CoinInfo; ``` Decode a [CoinInfo](/api-reference/compact-runtime/type-aliases/CoinInfo.md) from Compact's `CoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`CoinInfo`](/api-reference/compact-runtime/type-aliases/CoinInfo.md) --- # decodeCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeCoinPublicKey # Function: decodeCoinPublicKey() ``` function decodeCoinPublicKey(pk): string; ``` Decode a [CoinPublicKey](/api-reference/compact-runtime/type-aliases/CoinPublicKey.md) from a `Uint8Array` originating from Compact's `CoinPublicKey` type ## Parameters[​](#parameters "Direct link to Parameters") ### pk[​](#pk "Direct link to pk") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeContractAddress # Function: decodeContractAddress() ``` function decodeContractAddress(addr): string; ``` Decode a [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md) from a `Uint8Array` originating from Compact's `ContractAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeQualifiedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeQualifiedCoinInfo # Function: decodeQualifiedCoinInfo() ``` function decodeQualifiedCoinInfo(coin): QualifiedCoinInfo; ``` Decode a [QualifiedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedCoinInfo.md) from Compact's `QualifiedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### mt\_index[​](#mt_index "Direct link to mt_index") `bigint` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`QualifiedCoinInfo`](/api-reference/compact-runtime/type-aliases/QualifiedCoinInfo.md) --- # decodeQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeQualifiedShieldedCoinInfo # Function: decodeQualifiedShieldedCoinInfo() ``` function decodeQualifiedShieldedCoinInfo(coin): QualifiedShieldedCoinInfo; ``` Decode a [QualifiedShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md) from Compact's `QualifiedShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### mt\_index[​](#mt_index "Direct link to mt_index") `bigint` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`QualifiedShieldedCoinInfo`](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md) --- # decodeRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeRawTokenType # Function: decodeRawTokenType() ``` function decodeRawTokenType(tt): string; ``` Decode a raw [RawTokenType](/api-reference/compact-runtime/type-aliases/RawTokenType.md) from a `Uint8Array` originating from Compact's `RawTokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeRecipient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeRecipient # Function: decodeRecipient() ``` function decodeRecipient(__namedParameters): Recipient; ``` Converts an [EncodedRecipient](/api-reference/compact-runtime/interfaces/EncodedRecipient.md) to a [Recipient](/api-reference/compact-runtime/interfaces/Recipient.md). ## Parameters[​](#parameters "Direct link to Parameters") ### \_\_namedParameters[​](#__namedparameters "Direct link to __namedParameters") [`EncodedRecipient`](/api-reference/compact-runtime/interfaces/EncodedRecipient.md) ## Returns[​](#returns "Direct link to Returns") [`Recipient`](/api-reference/compact-runtime/interfaces/Recipient.md) --- # decodeShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeShieldedCoinInfo # Function: decodeShieldedCoinInfo() ``` function decodeShieldedCoinInfo(coin): ShieldedCoinInfo; ``` Decode a [ShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) from Compact's `ShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`ShieldedCoinInfo`](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) --- # decodeTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeTokenType # Function: decodeTokenType() ``` function decodeTokenType(tt): string; ``` Decode a [TokenType](/api-reference/compact-runtime/type-aliases/TokenType.md) from a `Uint8Array` originating from Compact's `TokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeUserAddress # Function: decodeUserAddress() ``` function decodeUserAddress(addr): string; ``` Decode a [UserAddress](/api-reference/compact-runtime/type-aliases/UserAddress.md) from a `Uint8Array` originating from Compact's `UserAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeZswapLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / decodeZswapLocalState # Function: decodeZswapLocalState() ``` function decodeZswapLocalState(state): ZswapLocalState; ``` Converts an [EncodedZswapLocalState](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) to a [ZswapLocalState](/api-reference/compact-runtime/interfaces/ZswapLocalState.md). Used when we need to use data from contract execution to construct transactions. ## Parameters[​](#parameters "Direct link to Parameters") ### state[​](#state "Direct link to state") [`EncodedZswapLocalState`](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) The encoded Zswap local state. ## Returns[​](#returns "Direct link to Returns") [`ZswapLocalState`](/api-reference/compact-runtime/interfaces/ZswapLocalState.md) --- # degradeToTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / degradeToTransient # Function: degradeToTransient() ``` function degradeToTransient(x): bigint; ``` The Compact builtin `degradeToTransient` function This function "degrades" the output of a [persistentHash](/api-reference/compact-runtime/functions/persistentHash.md) or [persistentCommit](/api-reference/compact-runtime/functions/persistentCommit.md) to a field element, which can then be used in [transientHash](/api-reference/compact-runtime/functions/transientHash.md) or [transientCommit](/api-reference/compact-runtime/functions/transientCommit.md). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `bigint` ## Throws[​](#throws "Direct link to Throws") If `x` is not 32 bytes long --- # dummyContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / dummyContractAddress # Function: dummyContractAddress() ``` function dummyContractAddress(): string; ``` A sample contract address ## Returns[​](#returns "Direct link to Returns") `string` --- # dummyUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / dummyUserAddress # Function: dummyUserAddress() ``` function dummyUserAddress(): string; ``` A sample user address ## Returns[​](#returns "Direct link to Returns") `string` --- # ecAdd > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ecAdd # Function: ecAdd() ``` function ecAdd(a, b): JubjubPoint; ``` The Compact builtin `ecAdd` function This function add two elliptic curve points (in multiplicative notation) ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ### b[​](#b "Direct link to b") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # ecMul > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ecMul # Function: ecMul() ``` function ecMul(a, b): JubjubPoint; ``` The Compact builtin `ecMul` function This function multiplies an elliptic curve point by a scalar (in multiplicative notation) ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ### b[​](#b "Direct link to b") `bigint` ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # ecMulGenerator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ecMulGenerator # Function: ecMulGenerator() ``` function ecMulGenerator(b): JubjubPoint; ``` The Compact builtin `ecMulGenerator` function This function multiplies the primary group generator of the embedded curve by a scalar (in multiplicative notation) ## Parameters[​](#parameters "Direct link to Parameters") ### b[​](#b "Direct link to b") `bigint` ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # ecNeg > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ecNeg # Function: ecNeg() ``` function ecNeg(a): JubjubPoint; ``` The Compact builtin `ecNeg` function This function negates an elliptic curve point. On the JubJub twisted Edwards curve, the negation of (x, y) is (-x, y). ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # emptyRunningCost > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / emptyRunningCost # Function: emptyRunningCost() ``` function emptyRunningCost(): RunningCost; ``` **`Internal`** ## Returns[​](#returns "Direct link to Returns") [`RunningCost`](/api-reference/compact-runtime/type-aliases/RunningCost.md) --- # emptyZswapLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / emptyZswapLocalState # Function: emptyZswapLocalState() ``` function emptyZswapLocalState(coinPublicKey): EncodedZswapLocalState; ``` Constructs a new [EncodedZswapLocalState](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) with the given coin public key. The result can be used to create a [ConstructorContext](/api-reference/compact-runtime/interfaces/ConstructorContext.md). ## Parameters[​](#parameters "Direct link to Parameters") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") The Zswap coin public key of the user executing the circuit. `string` | [`EncodedCoinPublicKey`](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md) ## Returns[​](#returns "Direct link to Returns") [`EncodedZswapLocalState`](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) --- # encodeCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeCoinInfo # Function: encodeCoinInfo() ``` function encodeCoinInfo(coin): { color: Uint8Array; nonce: Uint8Array; value: bigint; }; ``` Encode a [CoinInfo](/api-reference/compact-runtime/type-aliases/CoinInfo.md) into a Compact's `CoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`CoinInfo`](/api-reference/compact-runtime/type-aliases/CoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeCoinPublicKey # Function: encodeCoinPublicKey() ``` function encodeCoinPublicKey(pk): Uint8Array; ``` Encode a [CoinPublicKey](/api-reference/compact-runtime/type-aliases/CoinPublicKey.md) into a `Uint8Array` for use in Compact's `CoinPublicKey` type ## Parameters[​](#parameters "Direct link to Parameters") ### pk[​](#pk "Direct link to pk") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeContractAddress # Function: encodeContractAddress() ``` function encodeContractAddress(addr): Uint8Array; ``` Encode a [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md) into a `Uint8Array` for use in Compact's `ContractAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeQualifiedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeQualifiedCoinInfo # Function: encodeQualifiedCoinInfo() ``` function encodeQualifiedCoinInfo(coin): { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; }; ``` Encode a [QualifiedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedCoinInfo.md) into a Compact's `QualifiedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`QualifiedCoinInfo`](/api-reference/compact-runtime/type-aliases/QualifiedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeQualifiedShieldedCoinInfo # Function: encodeQualifiedShieldedCoinInfo() ``` function encodeQualifiedShieldedCoinInfo(coin): { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; }; ``` Encode a [QualifiedShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md) into a Compact's `QualifiedShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeRawTokenType # Function: encodeRawTokenType() ``` function encodeRawTokenType(tt): Uint8Array; ``` Encode a raw [RawTokenType](/api-reference/compact-runtime/type-aliases/RawTokenType.md) into a `Uint8Array` for use in Compact's `RawTokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeRecipient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeRecipient # Function: encodeRecipient() ``` function encodeRecipient(__namedParameters): EncodedRecipient; ``` Converts an [Recipient](/api-reference/compact-runtime/interfaces/Recipient.md) to an [EncodedRecipient](/api-reference/compact-runtime/interfaces/EncodedRecipient.md). Useful for testing. ## Parameters[​](#parameters "Direct link to Parameters") ### \_\_namedParameters[​](#__namedparameters "Direct link to __namedParameters") [`Recipient`](/api-reference/compact-runtime/interfaces/Recipient.md) ## Returns[​](#returns "Direct link to Returns") [`EncodedRecipient`](/api-reference/compact-runtime/interfaces/EncodedRecipient.md) --- # encodeShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeShieldedCoinInfo # Function: encodeShieldedCoinInfo() ``` function encodeShieldedCoinInfo(coin): { color: Uint8Array; nonce: Uint8Array; value: bigint; }; ``` Encode a [ShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) into a Compact's `ShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeTokenType # Function: encodeTokenType() ``` function encodeTokenType(tt): Uint8Array; ``` Encode a [TokenType](/api-reference/compact-runtime/type-aliases/TokenType.md) into a `Uint8Array` for use in Compact's `TokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeUserAddress # Function: encodeUserAddress() ``` function encodeUserAddress(addr): Uint8Array; ``` Encode a [UserAddress](/api-reference/compact-runtime/type-aliases/UserAddress.md) into a `Uint8Array` for use in Compact's `UserAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeZswapLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / encodeZswapLocalState # Function: encodeZswapLocalState() ``` function encodeZswapLocalState(state): EncodedZswapLocalState; ``` Converts a [ZswapLocalState](/api-reference/compact-runtime/interfaces/ZswapLocalState.md) to an [EncodedZswapLocalState](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md). Useful for testing. ## Parameters[​](#parameters "Direct link to Parameters") ### state[​](#state "Direct link to state") [`ZswapLocalState`](/api-reference/compact-runtime/interfaces/ZswapLocalState.md) The decoded Zswap local state. ## Returns[​](#returns "Direct link to Returns") [`EncodedZswapLocalState`](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) --- # entryPointHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / entryPointHash # Function: entryPointHash() ``` function entryPointHash(entryPoint): string; ``` Computes the (hex-encoded) hash of a given contract entry point. Used in composable contracts to reference the called contract's entry point ID in-circuit. ## Parameters[​](#parameters "Direct link to Parameters") ### entryPoint[​](#entrypoint "Direct link to entryPoint") `string` | `Uint8Array`<`ArrayBufferLike`> ## Returns[​](#returns "Direct link to Returns") `string` --- # finalizeCallProofData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / finalizeCallProofData # Function: finalizeCallProofData() ``` function finalizeCallProofData(circuitContext, proofData): void; ``` **`Internal`** ## Parameters[​](#parameters "Direct link to Parameters") ### circuitContext[​](#circuitcontext "Direct link to circuitContext") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) ### proofData[​](#proofdata "Direct link to proofData") [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md) ## Returns[​](#returns "Direct link to Returns") `void` --- # fromHex > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / fromHex # Function: fromHex() ``` function fromHex(s): Uint8Array; ``` ## Parameters[​](#parameters "Direct link to Parameters") ### s[​](#s "Direct link to s") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # hasCoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / hasCoinCommitment # Function: hasCoinCommitment() ``` function hasCoinCommitment( context, coinInfo, recipient): boolean; ``` Checks whether a coin commitment has already been added to the current query context. ## Parameters[​](#parameters "Direct link to Parameters") ### context[​](#context "Direct link to context") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) The current circuit context. ### coinInfo[​](#coininfo "Direct link to coinInfo") [`EncodedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md) The coin information to check. ### recipient[​](#recipient "Direct link to recipient") [`EncodedRecipient`](/api-reference/compact-runtime/interfaces/EncodedRecipient.md) The coin recipient to check. ## Returns[​](#returns "Direct link to Returns") `boolean` --- # hashToCurve > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / hashToCurve # Function: hashToCurve() ``` function hashToCurve(rtType, x): JubjubPoint; ``` The Compact builtin `hashToCurve` function This function maps arbitrary values representable in Compact to elliptic curve points in the proof system's embedded curve. Outputs are guaranteed to have unknown discrete logarithm with respect to the group base, and any other output, but are not guaranteed to be unique (a given input can be proven correct for multiple outputs). Inputs of different types may have the same output, if they have the same field-aligned binary representation. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### x[​](#x "Direct link to x") `A` ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # isContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / isContractAddress # Function: isContractAddress() ``` function isContractAddress(x): x is string; ``` Tests whether the input value is a [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md), i.e., string. ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `unknown` The value that is tested to be a [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md). ## Returns[​](#returns "Direct link to Returns") `x is string` --- # isEncodedContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / isEncodedContractAddress # Function: isEncodedContractAddress() ``` function isEncodedContractAddress(x): x is EncodedContractAddress; ``` ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `unknown` ## Returns[​](#returns "Direct link to Returns") `x is EncodedContractAddress` --- # jubjubPointX > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / jubjubPointX # Function: jubjubPointX() ``` function jubjubPointX(pt): bigint; ``` The Compact builtin `jubjubPointX` function This function extracts the x-coordinate of a Compact `JubjubPoint`. ## Parameters[​](#parameters "Direct link to Parameters") ### pt[​](#pt "Direct link to pt") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # jubjubPointY > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / jubjubPointY # Function: jubjubPointY() ``` function jubjubPointY(pt): bigint; ``` The Compact builtin `jubjubPointY` function This function extracts the y-coordinate of a Compact `JubjubPoint`. ## Parameters[​](#parameters "Direct link to Parameters") ### pt[​](#pt "Direct link to pt") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # jubjubSampleScalar > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / jubjubSampleScalar # Function: jubjubSampleScalar() ``` function jubjubSampleScalar(): bigint; ``` Samples a random JubJub scalar. The returned value is in the range \[0, JUBJUB\_SCALAR\_MODULUS). ## Returns[​](#returns "Direct link to Returns") `bigint` --- # jubjubSchnorrSign > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / jubjubSchnorrSign # Function: jubjubSchnorrSign() ``` function jubjubSchnorrSign( rtType, msg, signingKey): JubjubSchnorrSignature; ``` Produces a Schnorr signature over the JubJub curve. * `rtType` / `msg`: the message as a typed Compact value * `sk`: signing key as a JubJub scalar (e.g. as returned by [jubjubSampleScalar](/api-reference/compact-runtime/functions/jubjubSampleScalar.md)) The signature scheme: * Nonce `r` sampled uniformly at random * Announcement `R = r·G` * Challenge `c = PoseidonHash(R.x, R.y, pk.x, pk.y, msg...)` * Response `s = r + c·sk` (in the JubJub scalar field) ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### msg[​](#msg "Direct link to msg") `A` ### signingKey[​](#signingkey "Direct link to signingKey") `bigint` ## Returns[​](#returns "Direct link to Returns") [`JubjubSchnorrSignature`](/api-reference/compact-runtime/interfaces/JubjubSchnorrSignature.md) --- # jubjubSchnorrVerify > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / jubjubSchnorrVerify # Function: jubjubSchnorrVerify() ``` function jubjubSchnorrVerify( rtType, msg, verifyingKey, sig): boolean; ``` Verifies a Schnorr signature over the JubJub curve. * `rtType` / `msg`: the message as a typed Compact value * `pk`: verifying key (a JubJubPoint / EmbeddedGroupAffine) * `sig`: signature as returned by [jubjubSchnorrSign](/api-reference/compact-runtime/functions/jubjubSchnorrSign.md) Returns `true` if the signature is valid (i.e. `s·G == R + c·pk`). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### msg[​](#msg "Direct link to msg") `A` ### verifyingKey[​](#verifyingkey "Direct link to verifyingKey") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) ### sig[​](#sig "Direct link to sig") [`JubjubSchnorrSignature`](/api-reference/compact-runtime/interfaces/JubjubSchnorrSignature.md) ## Returns[​](#returns "Direct link to Returns") `boolean` --- # jubjubSchnorrVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / jubjubSchnorrVerifyingKey # Function: jubjubSchnorrVerifyingKey() ``` function jubjubSchnorrVerifyingKey(signingKey): JubjubPoint; ``` Derives the Schnorr verifying key (public key) from a signing key. Equivalent to [ecMulGenerator](/api-reference/compact-runtime/functions/ecMulGenerator.md)(signingKey). ## Parameters[​](#parameters "Direct link to Parameters") ### signingKey[​](#signingkey "Direct link to signingKey") `bigint` ## Returns[​](#returns "Direct link to Returns") [`JubjubPoint`](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # keccak256 > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / keccak256 # Function: keccak256() ``` function keccak256(rtType, value): Uint8Array; ``` The Compact builtin `keccak256` function Hashes `value` using Keccak-256 and returns the 32-byte digest. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### value[​](#value "Direct link to value") `A` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` ## Throws[​](#throws "Direct link to Throws") If `rtType` encodes a type containing Compact 'Opaque' types --- # leafHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / leafHash # Function: leafHash() ``` function leafHash(value): AlignedValue; ``` **`Internal`** Internal implementation of the Merkle tree leaf hash primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### value[​](#value "Direct link to value") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) --- # maxAlignedSize > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / maxAlignedSize # Function: maxAlignedSize() ``` function maxAlignedSize(alignment): bigint; ``` **`Internal`** Internal implementation of the max aligned size primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### alignment[​](#alignment "Direct link to alignment") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # maxField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / maxField # Function: maxField() ``` function maxField(): bigint; ``` Returns the maximum representable value in the proof systems scalar field (that is, 1 less than the prime modulus) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # mulField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / mulField # Function: mulField() ``` function mulField(x, y): bigint; ``` Field multiplication returns the result of multipying x and y, wrapping if necessary x and y are assumed to be values in the range \[0, FIELD\_MODULUS) ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # ownPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ownPublicKey # Function: ownPublicKey() ``` function ownPublicKey(circuitContext): EncodedCoinPublicKey; ``` Retrieves the Zswap coin public key of the user executing the circuit. ## Parameters[​](#parameters "Direct link to Parameters") ### circuitContext[​](#circuitcontext "Direct link to circuitContext") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md)<`unknown`> The current circuit context. ## Returns[​](#returns "Direct link to Returns") [`EncodedCoinPublicKey`](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md) --- # persistentCommit > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / persistentCommit # Function: persistentCommit() ``` function persistentCommit( rtType, value, opening): Uint8Array; ``` The Compact builtin `persistentCommit` function This function is a non-circuit-optimised commitment function from arbitrary values representable in Compact, and a 256-bit bytestring opening, to a 256-bit bytestring. It is guaranteed to persist between upgrades. It *should* be used to derive state data, and not for consistency checks where avoidable. Note that data containing `Opaque` elements *may* throw runtime errors, and cannot be relied upon as a consistent representation. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### value[​](#value "Direct link to value") `A` ### opening[​](#opening "Direct link to opening") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` ## Throws[​](#throws "Direct link to Throws") If `rtType` encodes a type containing Compact 'Opaque' types, or `opening` is not 32 bytes long --- # persistentHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / persistentHash # Function: persistentHash() ``` function persistentHash(rtType, value): Uint8Array; ``` The Compact builtin `persistentHash` function This function is a non-circuit-optimised hash function for mostly arbitrary data. It is guaranteed to persist between upgrades, with the exception of devnet. It *should* be used to derive state data, and not for consistency checks where avoidable. Note that data containing `Opaque` elements *may* throw runtime errors, and cannot be relied upon as a consistent representation. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### value[​](#value "Direct link to value") `A` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` ## Throws[​](#throws "Direct link to Throws") If `rtType` encodes a type containing Compact 'Opaque' types --- # proofDataIntoSerializedPreimage > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / proofDataIntoSerializedPreimage # Function: proofDataIntoSerializedPreimage() ``` function proofDataIntoSerializedPreimage( input, output, public_transcript, private_transcript_outputs, key_location?): Uint8Array; ``` Converts input, output, and transcript information into a proof preimage suitable to pass to a `ProvingProvider`. The `key_location` parameter is a string used to identify the circuit by proving machinery, for backwards-compatibility, if unset it defaults to `'dummy'`. ## Parameters[​](#parameters "Direct link to Parameters") ### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ### public\_transcript[​](#public_transcript "Direct link to public_transcript") [`Op`](/api-reference/compact-runtime/type-aliases/Op.md)<[`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md)>\[] ### private\_transcript\_outputs[​](#private_transcript_outputs "Direct link to private_transcript_outputs") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md)\[] ### key\_location?[​](#key_location "Direct link to key_location?") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # queryLedgerState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / queryLedgerState # Function: queryLedgerState() ``` function queryLedgerState( circuitContext, partialProofData, program): AlignedValue | undefined; ``` Runs a program (query) against the current ledger state in the given circuit context. Records the transcript in the given partial proof data. ## Parameters[​](#parameters "Direct link to Parameters") ### circuitContext[​](#circuitcontext "Direct link to circuitContext") [`CircuitContext`](/api-reference/compact-runtime/interfaces/CircuitContext.md) The context for the currently executing circuit. ### partialProofData[​](#partialproofdata "Direct link to partialProofData") [`PartialProofData`](/api-reference/compact-runtime/interfaces/PartialProofData.md) The partial proof data to insert the query results into. ### program[​](#program "Direct link to program") [`Op`](/api-reference/compact-runtime/type-aliases/Op.md)<`null`>\[] The query to run. ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) | `undefined` --- # rawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / rawTokenType # Function: rawTokenType() ``` function rawTokenType(domain_sep, contract): string; ``` Derives the raw [RawTokenType](/api-reference/compact-runtime/type-aliases/RawTokenType.md) associated with a particular [DomainSeparator](/api-reference/compact-runtime/type-aliases/DomainSeparator.md) and contract. ## Parameters[​](#parameters "Direct link to Parameters") ### domain\_sep[​](#domain_sep "Direct link to domain_sep") [`DomainSeparator`](/api-reference/compact-runtime/type-aliases/DomainSeparator.md) ### contract[​](#contract "Direct link to contract") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # runProgram > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / runProgram # Function: runProgram() ``` function runProgram( initial, ops, cost_model, gas_limit?): VmResults; ``` Runs a VM program against an initial stack, with an optional gas limit ## Parameters[​](#parameters "Direct link to Parameters") ### initial[​](#initial "Direct link to initial") [`VmStack`](/api-reference/compact-runtime/classes/VmStack.md) ### ops[​](#ops "Direct link to ops") [`Op`](/api-reference/compact-runtime/type-aliases/Op.md)<`null`>\[] ### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/compact-runtime/classes/CostModel.md) ### gas\_limit?[​](#gas_limit "Direct link to gas_limit?") [`RunningCost`](/api-reference/compact-runtime/type-aliases/RunningCost.md) ## Returns[​](#returns "Direct link to Returns") [`VmResults`](/api-reference/compact-runtime/classes/VmResults.md) --- # runtimeCoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / runtimeCoinCommitment # Function: runtimeCoinCommitment() ``` function runtimeCoinCommitment(coin, recipient): AlignedValue; ``` **`Internal`** Internal implementation of the runtime's coin commitment primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ### recipient[​](#recipient "Direct link to recipient") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/compact-runtime/type-aliases/AlignedValue.md) --- # sampleContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / sampleContractAddress # Function: sampleContractAddress() ``` function sampleContractAddress(): string; ``` Samples a uniform contract address, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / sampleRawTokenType # Function: sampleRawTokenType() ``` function sampleRawTokenType(): string; ``` Samples a uniform raw token type, for use in testing to construct both the shielded and unshielded token types. ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleSigningKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / sampleSigningKey # Function: sampleSigningKey() ``` function sampleSigningKey(kind?): SigningKey; ``` Randomly samples a [SigningKey](/api-reference/compact-runtime/type-aliases/SigningKey.md). If `kind` is not supplied, assumes `schnorr`. ## Parameters[​](#parameters "Direct link to Parameters") ### kind?[​](#kind "Direct link to kind?") `SignatureKind` ## Returns[​](#returns "Direct link to Returns") [`SigningKey`](/api-reference/compact-runtime/type-aliases/SigningKey.md) --- # sampleTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / sampleTokenType # Function: sampleTokenType() ``` function sampleTokenType(): string; ``` Samples a uniform token type, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / sampleUserAddress # Function: sampleUserAddress() ``` function sampleUserAddress(): string; ``` Samples a uniform user address, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # secp256k1Add > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1Add # Function: secp256k1Add() ``` function secp256k1Add(a, b): Secp256k1Point; ``` The Compact builtin `ecAdd` function for secp256k1 points. This function adds two elliptic curve points. ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) ### b[​](#b "Direct link to b") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) ## Returns[​](#returns "Direct link to Returns") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) --- # secp256k1BaseAdd > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1BaseAdd # Function: secp256k1BaseAdd() ``` function secp256k1BaseAdd(x, y): bigint; ``` Secp256k1 base field addition This function returns x + y in the secp256k1 base field (modulo SECP256K1\_BASE\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1BaseInv > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1BaseInv # Function: secp256k1BaseInv() ``` function secp256k1BaseInv(x): bigint; ``` Secp256k1 base field inverse This function returns the multiplicative inverse of x in the secp256k1 base field. That is, a value y such that x \* y = 1 (modulo SECP256K1\_BASE\_MODULUS). x is assumed to be in the range (0, SECP256K1\_BASE\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1BaseMul > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1BaseMul # Function: secp256k1BaseMul() ``` function secp256k1BaseMul(x, y): bigint; ``` Secp256k1 base field multiplication This function returns x \* y in the secp256k1 base field (modulo SECP256K1\_BASE\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1BaseNeg > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1BaseNeg # Function: secp256k1BaseNeg() ``` function secp256k1BaseNeg(x): bigint; ``` Secp256k1 base field negation This function returns the negation of x in the secp256k1 base field. That is, a value y such that x + y = 0 (modulo SECP256K1\_BASE\_MODULUS). x is assumed to be in the range \[0, SECP256K1\_BASE\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1BaseSub > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1BaseSub # Function: secp256k1BaseSub() ``` function secp256k1BaseSub(x, y): bigint; ``` Secp256k1 base field subtraction This function returns x - y in the secp256k1 base field (modulo SECP256K1\_BASE\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1EcdsaRecover > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1EcdsaRecover # Function: secp256k1EcdsaRecover() ``` function secp256k1EcdsaRecover( msgHash, sig, recoveryId): Secp256k1Point; ``` Recover the secp256k1 public key from an ECDSA signature and a message hash. ## Recovery ID[​](#recovery-id "Direct link to Recovery ID") * bit 0 (`recoveryId & 1`) is the parity of `R.y`: 0 for even, 1 for odd. * bit 1 (`recoveryId >= 2`) says whether the reduction wrapped, i.e. whether `R.x` is `r` (0, 1) or `r + n` (2, 3). * 0: `R = (r, y)` with `y` even — the common case. * 1: `R = (r, y)` with `y` odd — the other common case. * 2: `R = (r + n, y)` with `y` even. * 3: `R = (r + n, y)` with `y` odd. ## Parameters[​](#parameters "Direct link to Parameters") ### msgHash[​](#msghash "Direct link to msgHash") `Uint8Array` ### sig[​](#sig "Direct link to sig") #### r[​](#r "Direct link to r") `bigint` #### s[​](#s "Direct link to s") `bigint` ### recoveryId[​](#recoveryid "Direct link to recoveryId") `number` ## Returns[​](#returns "Direct link to Returns") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) --- # secp256k1FromProjective > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1FromProjective # Function: secp256k1FromProjective() ``` function secp256k1FromProjective(p): Secp256k1Point; ``` Project a noble-curves point back down to the simple affine `Secp256k1Point` representation. ## Parameters[​](#parameters "Direct link to Parameters") ### p[​](#p "Direct link to p") `WeierstrassPoint`<`bigint`> ## Returns[​](#returns "Direct link to Returns") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) --- # secp256k1Mul > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1Mul # Function: secp256k1Mul() ``` function secp256k1Mul(a, b): Secp256k1Point; ``` The Compact builtin `ecMul` function for secp256k1 points. `multiplyUnsafe` is used, instead of `multiply`, because the latter rejects a zero scalar; the "unsafe" (variable-time) is due to non-constant time operations, which we don't guarantee anyways. ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) ### b[​](#b "Direct link to b") `bigint` ## Returns[​](#returns "Direct link to Returns") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) --- # secp256k1MulGenerator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1MulGenerator # Function: secp256k1MulGenerator() ``` function secp256k1MulGenerator(b): Secp256k1Point; ``` The Compact builtin `ecMulGenerator` function for secp256k1 points. `multiplyUnsafe` is used, instead of `multiply`, because the latter rejects a zero scalar; the "unsafe" (variable-time) is due to non-constant time operations, which we don't guarantee anyways. ## Parameters[​](#parameters "Direct link to Parameters") ### b[​](#b "Direct link to b") `bigint` ## Returns[​](#returns "Direct link to Returns") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) --- # secp256k1PointX > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1PointX # Function: secp256k1PointX() ``` function secp256k1PointX(pt): bigint; ``` The Compact builtin `secp256k1PointX` function This function extracts the affine x-coordinate of a Compact `Secp256k1Point`. ## Parameters[​](#parameters "Direct link to Parameters") ### pt[​](#pt "Direct link to pt") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1PointY > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1PointY # Function: secp256k1PointY() ``` function secp256k1PointY(pt): bigint; ``` The Compact builtin `secp256k1PointY` function This function extracts the affine y-coordinate of a Compact `Secp256k1Point`. ## Parameters[​](#parameters "Direct link to Parameters") ### pt[​](#pt "Direct link to pt") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1ScalarAdd > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1ScalarAdd # Function: secp256k1ScalarAdd() ``` function secp256k1ScalarAdd(x, y): bigint; ``` Secp256k1 scalar field addition This function returns x + y in the secp256k1 scalar field (modulo SECP256K1\_SCALAR\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1ScalarInv > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1ScalarInv # Function: secp256k1ScalarInv() ``` function secp256k1ScalarInv(x): bigint; ``` Secp256k1 scalar field inverse This function returns the multiplicative inverse of x in the secp256k1 scalar field. That is, a value y such that x \* y = 1 (modulo SECP256K1\_SCALAR\_MODULUS). x is assumed to be in the range (0, SECP256K1\_SCALAR\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1ScalarMul > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1ScalarMul # Function: secp256k1ScalarMul() ``` function secp256k1ScalarMul(x, y): bigint; ``` Secp256k1 scalar field multiplication This function returns x \* y in the secp256k1 scalar field (modulo SECP256K1\_SCALAR\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1ScalarNeg > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1ScalarNeg # Function: secp256k1ScalarNeg() ``` function secp256k1ScalarNeg(x): bigint; ``` Secp256k1 scalar field negation This function returns the negation of x in the secp256k1 scalar field. That is, a value y such that x + y = 0 (modulo SECP256K1\_SCALAR\_MODULUS). x is assumed to be in the range \[0, SECP256K1\_SCALAR\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1ScalarSub > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1ScalarSub # Function: secp256k1ScalarSub() ``` function secp256k1ScalarSub(x, y): bigint; ``` Secp256k1 scalar field subtraction This function returns x - y in the secp256k1 scalar field (modulo SECP256K1\_SCALAR\_MODULUS). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # secp256k1ToProjective > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / secp256k1ToProjective # Function: secp256k1ToProjective() ``` function secp256k1ToProjective(p): WeierstrassPoint; ``` Lift the simple affine `Secp256k1Point` representation into a noble-curves projective point. Identity maps to `Point.ZERO`; every other input is validated to lie on the curve by `fromAffine`. ## Parameters[​](#parameters "Direct link to Parameters") ### p[​](#p "Direct link to p") [`Secp256k1Point`](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) ## Returns[​](#returns "Direct link to Returns") `WeierstrassPoint`<`bigint`> --- # signatureVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / signatureVerifyingKey # Function: signatureVerifyingKey() ``` function signatureVerifyingKey(sk): SignatureVerifyingKey; ``` Returns the verifying key for a given signing key ## Parameters[​](#parameters "Direct link to Parameters") ### sk[​](#sk "Direct link to sk") [`SigningKey`](/api-reference/compact-runtime/type-aliases/SigningKey.md) ## Returns[​](#returns "Direct link to Returns") [`SignatureVerifyingKey`](/api-reference/compact-runtime/type-aliases/SignatureVerifyingKey.md) --- # signData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / signData # Function: signData() ``` function signData(key, data): Signature; ``` Signs arbitrary data with the given signing key. WARNING: Do not expose access to this function for valuable keys for data that is not strictly controlled! ## Parameters[​](#parameters "Direct link to Parameters") ### key[​](#key "Direct link to key") [`SigningKey`](/api-reference/compact-runtime/type-aliases/SigningKey.md) ### data[​](#data "Direct link to data") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") [`Signature`](/api-reference/compact-runtime/type-aliases/Signature.md) --- # signingKeyFromBip340 > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / signingKeyFromBip340 # Function: signingKeyFromBip340() ``` function signingKeyFromBip340(data): SigningKey; ``` Creates a [SigningKey](/api-reference/compact-runtime/type-aliases/SigningKey.md) from provided Bip340 private key. ## Parameters[​](#parameters "Direct link to Parameters") ### data[​](#data "Direct link to data") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") [`SigningKey`](/api-reference/compact-runtime/type-aliases/SigningKey.md) --- # subField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / subField # Function: subField() ``` function subField(x, y): bigint; ``` Field subtraction returns the result of subtracting y from x, wrapping if necessary x and y are assumed to be values in the range \[0, FIELD\_MODULUS) ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ### y[​](#y "Direct link to y") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # toBinaryRepr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / toBinaryRepr # Function: toBinaryRepr() ``` function toBinaryRepr(rtType, value): Uint8Array; ``` ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### value[​](#value "Direct link to value") `A` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # toHex > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / toHex # Function: toHex() ``` function toHex(s): string; ``` ## Parameters[​](#parameters "Direct link to Parameters") ### s[​](#s "Direct link to s") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # tokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / tokenType # Function: tokenType() ``` function tokenType(domain_sep, contract): string; ``` Derives the [TokenType](/api-reference/compact-runtime/type-aliases/TokenType.md) associated with a particular [DomainSeperator](/api-reference/compact-runtime/type-aliases/DomainSeperator.md) and contract. ## Parameters[​](#parameters "Direct link to Parameters") ### domain\_sep[​](#domain_sep "Direct link to domain_sep") [`DomainSeperator`](/api-reference/compact-runtime/type-aliases/DomainSeperator.md) ### contract[​](#contract "Direct link to contract") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # transientCommit > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / transientCommit # Function: transientCommit() ``` function transientCommit( rtType, value, opening): bigint; ``` The Compact builtin `transientCommit` function This function is a circuit-efficient commitment function from arbitrary values representable in Compact, and a field element commitment opening, to field elements, which is not guaranteed to persist between upgrades. It should not be used to derive state data, but can be used for consistency checks. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### value[​](#value "Direct link to value") `A` ### opening[​](#opening "Direct link to opening") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` ## Throws[​](#throws "Direct link to Throws") If `opening` is out of range for field elements --- # transientHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / transientHash # Function: transientHash() ``` function transientHash(rtType, value): bigint; ``` The Compact builtin `transientHash` function This function is a circuit-efficient compression function from arbitrary data to field elements, which is not guaranteed to persist between upgrades. It should not be used to derive state data, but can be used for consistency checks. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### rtType[​](#rttype "Direct link to rtType") [`CompactType`](/api-reference/compact-runtime/interfaces/CompactType.md)<`A`> ### value[​](#value "Direct link to value") `A` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # type\_error > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / type\_error # Function: type\_error() ``` function type_error( who, what, where, type, x): never; ``` **`Internal`** Compiler internal for type errors ## Parameters[​](#parameters "Direct link to Parameters") ### who[​](#who "Direct link to who") `string` ### what[​](#what "Direct link to what") `string` ### where[​](#where "Direct link to where") `string` ### type[​](#type "Direct link to type") `string` ### x[​](#x "Direct link to x") `any` ## Returns[​](#returns "Direct link to Returns") `never` --- # typeError > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / typeError # Function: typeError() ``` function typeError( who, what, where, type, x): never; ``` **`Internal`** Compiler internal for type errors ## Parameters[​](#parameters "Direct link to Parameters") ### who[​](#who "Direct link to who") `string` ### what[​](#what "Direct link to what") `string` ### where[​](#where "Direct link to where") `string` ### type[​](#type "Direct link to type") `string` ### x[​](#x "Direct link to x") `any` ## Returns[​](#returns "Direct link to Returns") `never` --- # upgradeFromTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / upgradeFromTransient # Function: upgradeFromTransient() ``` function upgradeFromTransient(x): Uint8Array; ``` The Compact builtin `upgradeFromTransient` function This function "upgrades" the output of a [transientHash](/api-reference/compact-runtime/functions/transientHash.md) or [transientCommit](/api-reference/compact-runtime/functions/transientCommit.md) to 256-bit byte string, which can then be used in [persistentHash](/api-reference/compact-runtime/functions/persistentHash.md) or [persistentCommit](/api-reference/compact-runtime/functions/persistentCommit.md). ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` ## Throws[​](#throws "Direct link to Throws") If `x` is not a valid field element --- # valueToBigInt > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / valueToBigInt # Function: valueToBigInt() ``` function valueToBigInt(x): bigint; ``` **`Internal`** Internal conversion between field-aligned binary values and bigints within the scalar field ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") `bigint` ## Throws[​](#throws "Direct link to Throws") If the value does not encode a field element --- # verifySignature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / verifySignature # Function: verifySignature() ``` function verifySignature( vk, data, signature): boolean; ``` Verifies if a signature is correct ## Parameters[​](#parameters "Direct link to Parameters") ### vk[​](#vk "Direct link to vk") [`SignatureVerifyingKey`](/api-reference/compact-runtime/type-aliases/SignatureVerifyingKey.md) ### data[​](#data "Direct link to data") `Uint8Array` ### signature[​](#signature "Direct link to signature") [`Signature`](/api-reference/compact-runtime/type-aliases/Signature.md) ## Returns[​](#returns "Direct link to Returns") `boolean` --- # witnessContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / witnessContext # Function: witnessContext() ``` function witnessContext( ledger, privateState, contractAddress): WitnessContext; ``` **`Internal`** Internal constructor for [WitnessContext](/api-reference/compact-runtime/interfaces/WitnessContext.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### L[​](#l "Direct link to L") `L` ### T[​](#t "Direct link to T") `T` ## Parameters[​](#parameters "Direct link to Parameters") ### ledger[​](#ledger "Direct link to ledger") `L` ### privateState[​](#privatestate "Direct link to privateState") `T` ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` ## Returns[​](#returns "Direct link to Returns") [`WitnessContext`](/api-reference/compact-runtime/interfaces/WitnessContext.md)<`L`, `T`> --- # globals > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** # @midnight-ntwrk/compact-runtime v0.19.0 ## Classes[​](#classes "Direct link to Classes") * [ChargedState](/api-reference/compact-runtime/classes/ChargedState.md) * [CompactError](/api-reference/compact-runtime/classes/CompactError.md) * [CompactTypeBytes](/api-reference/compact-runtime/classes/CompactTypeBytes.md) * [CompactTypeEnum](/api-reference/compact-runtime/classes/CompactTypeEnum.md) * [CompactTypeMerkleTreePath](/api-reference/compact-runtime/classes/CompactTypeMerkleTreePath.md) * [CompactTypeUnsignedInteger](/api-reference/compact-runtime/classes/CompactTypeUnsignedInteger.md) * [CompactTypeVector](/api-reference/compact-runtime/classes/CompactTypeVector.md) * [ContractInterfaceMismatchError](/api-reference/compact-runtime/classes/ContractInterfaceMismatchError.md) * [ContractMaintenanceAuthority](/api-reference/compact-runtime/classes/ContractMaintenanceAuthority.md) * [ContractOperation](/api-reference/compact-runtime/classes/ContractOperation.md) * [ContractState](/api-reference/compact-runtime/classes/ContractState.md) * [CostModel](/api-reference/compact-runtime/classes/CostModel.md) * [QueryContext](/api-reference/compact-runtime/classes/QueryContext.md) * [QueryResults](/api-reference/compact-runtime/classes/QueryResults.md) * [StateBoundedMerkleTree](/api-reference/compact-runtime/classes/StateBoundedMerkleTree.md) * [StateMap](/api-reference/compact-runtime/classes/StateMap.md) * [StateValue](/api-reference/compact-runtime/classes/StateValue.md) * [VmResults](/api-reference/compact-runtime/classes/VmResults.md) * [VmStack](/api-reference/compact-runtime/classes/VmStack.md) ## Interfaces[​](#interfaces "Direct link to Interfaces") * [CallProofData](/api-reference/compact-runtime/interfaces/CallProofData.md) * [CircuitContext](/api-reference/compact-runtime/interfaces/CircuitContext.md) * [CircuitResults](/api-reference/compact-runtime/interfaces/CircuitResults.md) * [CommunicationCommitmentData](/api-reference/compact-runtime/interfaces/CommunicationCommitmentData.md) * [CompactType](/api-reference/compact-runtime/interfaces/CompactType.md) * [ConstructorContext](/api-reference/compact-runtime/interfaces/ConstructorContext.md) * [ConstructorResult](/api-reference/compact-runtime/interfaces/ConstructorResult.md) * [ContractStateProvider](/api-reference/compact-runtime/interfaces/ContractStateProvider.md) * [EncodedCoinPublicKey](/api-reference/compact-runtime/interfaces/EncodedCoinPublicKey.md) * [EncodedContractAddress](/api-reference/compact-runtime/interfaces/EncodedContractAddress.md) * [EncodedQualifiedShieldedCoinInfo](/api-reference/compact-runtime/interfaces/EncodedQualifiedShieldedCoinInfo.md) * [EncodedRecipient](/api-reference/compact-runtime/interfaces/EncodedRecipient.md) * [EncodedShieldedCoinInfo](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md) * [EncodedZswapLocalState](/api-reference/compact-runtime/interfaces/EncodedZswapLocalState.md) * [JubjubPoint](/api-reference/compact-runtime/interfaces/JubjubPoint.md) * [JubjubSchnorrSignature](/api-reference/compact-runtime/interfaces/JubjubSchnorrSignature.md) * [MerkleTreeDigest](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md) * [MerkleTreePath](/api-reference/compact-runtime/interfaces/MerkleTreePath.md) * [MerkleTreePathEntry](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md) * [PartialProofData](/api-reference/compact-runtime/interfaces/PartialProofData.md) * [ProofData](/api-reference/compact-runtime/interfaces/ProofData.md) * [Recipient](/api-reference/compact-runtime/interfaces/Recipient.md) * [Secp256k1Point](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) * [WitnessContext](/api-reference/compact-runtime/interfaces/WitnessContext.md) * [ZswapLocalState](/api-reference/compact-runtime/interfaces/ZswapLocalState.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md) * [Alignment](/api-reference/compact-runtime/type-aliases/Alignment.md) * [AlignmentAtom](/api-reference/compact-runtime/type-aliases/AlignmentAtom.md) * [AlignmentSegment](/api-reference/compact-runtime/type-aliases/AlignmentSegment.md) * [BlockContext](/api-reference/compact-runtime/type-aliases/BlockContext.md) * [CallContext](/api-reference/compact-runtime/type-aliases/CallContext.md) * [CallProofDataTrace](/api-reference/compact-runtime/type-aliases/CallProofDataTrace.md) * [CircuitId](/api-reference/compact-runtime/type-aliases/CircuitId.md) * [CoinCommitment](/api-reference/compact-runtime/type-aliases/CoinCommitment.md) * [CoinPublicKey](/api-reference/compact-runtime/type-aliases/CoinPublicKey.md) * [CommunicationCommitment](/api-reference/compact-runtime/type-aliases/CommunicationCommitment.md) * [CommunicationCommitmentRand](/api-reference/compact-runtime/type-aliases/CommunicationCommitmentRand.md) * [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md) * [ContractReferenceLocations](/api-reference/compact-runtime/type-aliases/ContractReferenceLocations.md) * [DomainSeparator](/api-reference/compact-runtime/type-aliases/DomainSeparator.md) * [DustTokenType](/api-reference/compact-runtime/type-aliases/DustTokenType.md) * [Effects](/api-reference/compact-runtime/type-aliases/Effects.md) * [EmptyPublicLedger](/api-reference/compact-runtime/type-aliases/EmptyPublicLedger.md) * [EncodedStateValue](/api-reference/compact-runtime/type-aliases/EncodedStateValue.md) * [Fr](/api-reference/compact-runtime/type-aliases/Fr.md) * [GatherResult](/api-reference/compact-runtime/type-aliases/GatherResult.md) * [Key](/api-reference/compact-runtime/type-aliases/Key.md) * [LogEvent](/api-reference/compact-runtime/type-aliases/LogEvent.md) * [Nonce](/api-reference/compact-runtime/type-aliases/Nonce.md) * [Nullifier](/api-reference/compact-runtime/type-aliases/Nullifier.md) * [Op](/api-reference/compact-runtime/type-aliases/Op.md) * [PublicAddress](/api-reference/compact-runtime/type-aliases/PublicAddress.md) * [PublicLedgerSegments](/api-reference/compact-runtime/type-aliases/PublicLedgerSegments.md) * [QualifiedShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedShieldedCoinInfo.md) * [RawTokenType](/api-reference/compact-runtime/type-aliases/RawTokenType.md) * [RunningCost](/api-reference/compact-runtime/type-aliases/RunningCost.md) * [ShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) * [ShieldedTokenType](/api-reference/compact-runtime/type-aliases/ShieldedTokenType.md) * [Signature](/api-reference/compact-runtime/type-aliases/Signature.md) * [SignatureVerifyingKey](/api-reference/compact-runtime/type-aliases/SignatureVerifyingKey.md) * [SigningKey](/api-reference/compact-runtime/type-aliases/SigningKey.md) * [SparseCompactADT](/api-reference/compact-runtime/type-aliases/SparseCompactADT.md) * [SparseCompactArrayLikeADT](/api-reference/compact-runtime/type-aliases/SparseCompactArrayLikeADT.md) * [SparseCompactCellADT](/api-reference/compact-runtime/type-aliases/SparseCompactCellADT.md) * [SparseCompactContractAddress](/api-reference/compact-runtime/type-aliases/SparseCompactContractAddress.md) * [SparseCompactListADT](/api-reference/compact-runtime/type-aliases/SparseCompactListADT.md) * [SparseCompactMapADT](/api-reference/compact-runtime/type-aliases/SparseCompactMapADT.md) * [SparseCompactSetADT](/api-reference/compact-runtime/type-aliases/SparseCompactSetADT.md) * [SparseCompactStruct](/api-reference/compact-runtime/type-aliases/SparseCompactStruct.md) * [SparseCompactType](/api-reference/compact-runtime/type-aliases/SparseCompactType.md) * [SparseCompactValue](/api-reference/compact-runtime/type-aliases/SparseCompactValue.md) * [SparseCompactVector](/api-reference/compact-runtime/type-aliases/SparseCompactVector.md) * [TokenType](/api-reference/compact-runtime/type-aliases/TokenType.md) * [Transcript](/api-reference/compact-runtime/type-aliases/Transcript.md) * [UnshieldedTokenType](/api-reference/compact-runtime/type-aliases/UnshieldedTokenType.md) * [UserAddress](/api-reference/compact-runtime/type-aliases/UserAddress.md) * [Value](/api-reference/compact-runtime/type-aliases/Value.md) ## Variables[​](#variables "Direct link to Variables") * [CompactTypeBoolean](/api-reference/compact-runtime/variables/CompactTypeBoolean.md) * [CompactTypeField](/api-reference/compact-runtime/variables/CompactTypeField.md) * [CompactTypeJubjubPoint](/api-reference/compact-runtime/variables/CompactTypeJubjubPoint.md) * [CompactTypeMerkleTreeDigest](/api-reference/compact-runtime/variables/CompactTypeMerkleTreeDigest.md) * [CompactTypeMerkleTreePathEntry](/api-reference/compact-runtime/variables/CompactTypeMerkleTreePathEntry.md) * [CompactTypeOpaqueString](/api-reference/compact-runtime/variables/CompactTypeOpaqueString.md) * [CompactTypeOpaqueUint8Array](/api-reference/compact-runtime/variables/CompactTypeOpaqueUint8Array.md) * [CompactTypeSecp256k1Base](/api-reference/compact-runtime/variables/CompactTypeSecp256k1Base.md) * [CompactTypeSecp256k1Point](/api-reference/compact-runtime/variables/CompactTypeSecp256k1Point.md) * [CompactTypeSecp256k1Scalar](/api-reference/compact-runtime/variables/CompactTypeSecp256k1Scalar.md) * [CONTRACT\_ADDRESS\_BYTE\_LENGTH](/api-reference/compact-runtime/variables/CONTRACT_ADDRESS_BYTE_LENGTH.md) * [~~DUMMY\_ADDRESS~~](/api-reference/compact-runtime/variables/DUMMY_ADDRESS.md) * [FIELD\_MODULUS](/api-reference/compact-runtime/variables/FIELD_MODULUS.md) * [HEX\_REGEX\_NO\_PREFIX](/api-reference/compact-runtime/variables/HEX_REGEX_NO_PREFIX.md) * [JUBJUB\_SCALAR\_MODULUS](/api-reference/compact-runtime/variables/JUBJUB_SCALAR_MODULUS.md) * [MAX\_FIELD](/api-reference/compact-runtime/variables/MAX_FIELD.md) * [MAX\_JUBJUB\_SCALAR](/api-reference/compact-runtime/variables/MAX_JUBJUB_SCALAR.md) * [MAX\_SECP256K1\_BASE](/api-reference/compact-runtime/variables/MAX_SECP256K1_BASE.md) * [MAX\_SECP256K1\_SCALAR](/api-reference/compact-runtime/variables/MAX_SECP256K1_SCALAR.md) * [sampleJubjubSchnorrSk](/api-reference/compact-runtime/variables/sampleJubjubSchnorrSk.md) * [SECP256K1\_BASE\_MODULUS](/api-reference/compact-runtime/variables/SECP256K1_BASE_MODULUS.md) * [SECP256K1\_SCALAR\_MODULUS](/api-reference/compact-runtime/variables/SECP256K1_SCALAR_MODULUS.md) * [versionString](/api-reference/compact-runtime/variables/versionString.md) ## Functions[​](#functions "Direct link to Functions") * [addField](/api-reference/compact-runtime/functions/addField.md) * [alignedConcat](/api-reference/compact-runtime/functions/alignedConcat.md) * [assert](/api-reference/compact-runtime/functions/assert.md) * [assertDefined](/api-reference/compact-runtime/functions/assertDefined.md) * [assertIsContractAddress](/api-reference/compact-runtime/functions/assertIsContractAddress.md) * [assertUndefined](/api-reference/compact-runtime/functions/assertUndefined.md) * [bigIntModFr](/api-reference/compact-runtime/functions/bigIntModFr.md) * [bigIntToValue](/api-reference/compact-runtime/functions/bigIntToValue.md) * [checkRuntimeVersion](/api-reference/compact-runtime/functions/checkRuntimeVersion.md) * [communicationCommitment](/api-reference/compact-runtime/functions/communicationCommitment.md) * [communicationCommitmentRandomness](/api-reference/compact-runtime/functions/communicationCommitmentRandomness.md) * [constructJubjubPoint](/api-reference/compact-runtime/functions/constructJubjubPoint.md) * [contractDependencies](/api-reference/compact-runtime/functions/contractDependencies.md) * [convertBigintToBytes](/api-reference/compact-runtime/functions/convertBigintToBytes.md) * [convertBytesToField](/api-reference/compact-runtime/functions/convertBytesToField.md) * [convertBytesToUint](/api-reference/compact-runtime/functions/convertBytesToUint.md) * [convertNumericToJubjubScalar](/api-reference/compact-runtime/functions/convertNumericToJubjubScalar.md) * [copyCircuitContext](/api-reference/compact-runtime/functions/copyCircuitContext.md) * [createCallContext](/api-reference/compact-runtime/functions/createCallContext.md) * [createCircuitContext](/api-reference/compact-runtime/functions/createCircuitContext.md) * [createConstructorContext](/api-reference/compact-runtime/functions/createConstructorContext.md) * [createInitialQueryContext](/api-reference/compact-runtime/functions/createInitialQueryContext.md) * [createWitnessContext](/api-reference/compact-runtime/functions/createWitnessContext.md) * [createZswapInput](/api-reference/compact-runtime/functions/createZswapInput.md) * [createZswapOutput](/api-reference/compact-runtime/functions/createZswapOutput.md) * [crossContractCall](/api-reference/compact-runtime/functions/crossContractCall.md) * [decodeCoinPublicKey](/api-reference/compact-runtime/functions/decodeCoinPublicKey.md) * [decodeContractAddress](/api-reference/compact-runtime/functions/decodeContractAddress.md) * [decodeQualifiedShieldedCoinInfo](/api-reference/compact-runtime/functions/decodeQualifiedShieldedCoinInfo.md) * [decodeRawTokenType](/api-reference/compact-runtime/functions/decodeRawTokenType.md) * [decodeRecipient](/api-reference/compact-runtime/functions/decodeRecipient.md) * [decodeShieldedCoinInfo](/api-reference/compact-runtime/functions/decodeShieldedCoinInfo.md) * [decodeUserAddress](/api-reference/compact-runtime/functions/decodeUserAddress.md) * [decodeZswapLocalState](/api-reference/compact-runtime/functions/decodeZswapLocalState.md) * [degradeToTransient](/api-reference/compact-runtime/functions/degradeToTransient.md) * [dummyContractAddress](/api-reference/compact-runtime/functions/dummyContractAddress.md) * [dummyUserAddress](/api-reference/compact-runtime/functions/dummyUserAddress.md) * [ecAdd](/api-reference/compact-runtime/functions/ecAdd.md) * [ecMul](/api-reference/compact-runtime/functions/ecMul.md) * [ecMulGenerator](/api-reference/compact-runtime/functions/ecMulGenerator.md) * [ecNeg](/api-reference/compact-runtime/functions/ecNeg.md) * [emptyRunningCost](/api-reference/compact-runtime/functions/emptyRunningCost.md) * [emptyZswapLocalState](/api-reference/compact-runtime/functions/emptyZswapLocalState.md) * [encodeCoinPublicKey](/api-reference/compact-runtime/functions/encodeCoinPublicKey.md) * [encodeContractAddress](/api-reference/compact-runtime/functions/encodeContractAddress.md) * [encodeQualifiedShieldedCoinInfo](/api-reference/compact-runtime/functions/encodeQualifiedShieldedCoinInfo.md) * [encodeRawTokenType](/api-reference/compact-runtime/functions/encodeRawTokenType.md) * [encodeRecipient](/api-reference/compact-runtime/functions/encodeRecipient.md) * [encodeShieldedCoinInfo](/api-reference/compact-runtime/functions/encodeShieldedCoinInfo.md) * [encodeUserAddress](/api-reference/compact-runtime/functions/encodeUserAddress.md) * [encodeZswapLocalState](/api-reference/compact-runtime/functions/encodeZswapLocalState.md) * [entryPointHash](/api-reference/compact-runtime/functions/entryPointHash.md) * [finalizeCallProofData](/api-reference/compact-runtime/functions/finalizeCallProofData.md) * [fromHex](/api-reference/compact-runtime/functions/fromHex.md) * [hasCoinCommitment](/api-reference/compact-runtime/functions/hasCoinCommitment.md) * [hashToCurve](/api-reference/compact-runtime/functions/hashToCurve.md) * [isContractAddress](/api-reference/compact-runtime/functions/isContractAddress.md) * [isEncodedContractAddress](/api-reference/compact-runtime/functions/isEncodedContractAddress.md) * [jubjubPointX](/api-reference/compact-runtime/functions/jubjubPointX.md) * [jubjubPointY](/api-reference/compact-runtime/functions/jubjubPointY.md) * [jubjubSampleScalar](/api-reference/compact-runtime/functions/jubjubSampleScalar.md) * [jubjubSchnorrSign](/api-reference/compact-runtime/functions/jubjubSchnorrSign.md) * [jubjubSchnorrVerify](/api-reference/compact-runtime/functions/jubjubSchnorrVerify.md) * [jubjubSchnorrVerifyingKey](/api-reference/compact-runtime/functions/jubjubSchnorrVerifyingKey.md) * [keccak256](/api-reference/compact-runtime/functions/keccak256.md) * [leafHash](/api-reference/compact-runtime/functions/leafHash.md) * [maxAlignedSize](/api-reference/compact-runtime/functions/maxAlignedSize.md) * [maxField](/api-reference/compact-runtime/functions/maxField.md) * [mulField](/api-reference/compact-runtime/functions/mulField.md) * [ownPublicKey](/api-reference/compact-runtime/functions/ownPublicKey.md) * [persistentCommit](/api-reference/compact-runtime/functions/persistentCommit.md) * [persistentHash](/api-reference/compact-runtime/functions/persistentHash.md) * [proofDataIntoSerializedPreimage](/api-reference/compact-runtime/functions/proofDataIntoSerializedPreimage.md) * [queryLedgerState](/api-reference/compact-runtime/functions/queryLedgerState.md) * [rawTokenType](/api-reference/compact-runtime/functions/rawTokenType.md) * [runProgram](/api-reference/compact-runtime/functions/runProgram.md) * [runtimeCoinCommitment](/api-reference/compact-runtime/functions/runtimeCoinCommitment.md) * [sampleContractAddress](/api-reference/compact-runtime/functions/sampleContractAddress.md) * [sampleRawTokenType](/api-reference/compact-runtime/functions/sampleRawTokenType.md) * [sampleSigningKey](/api-reference/compact-runtime/functions/sampleSigningKey.md) * [sampleUserAddress](/api-reference/compact-runtime/functions/sampleUserAddress.md) * [secp256k1Add](/api-reference/compact-runtime/functions/secp256k1Add.md) * [secp256k1BaseAdd](/api-reference/compact-runtime/functions/secp256k1BaseAdd.md) * [secp256k1BaseInv](/api-reference/compact-runtime/functions/secp256k1BaseInv.md) * [secp256k1BaseMul](/api-reference/compact-runtime/functions/secp256k1BaseMul.md) * [secp256k1BaseNeg](/api-reference/compact-runtime/functions/secp256k1BaseNeg.md) * [secp256k1BaseSub](/api-reference/compact-runtime/functions/secp256k1BaseSub.md) * [secp256k1EcdsaRecover](/api-reference/compact-runtime/functions/secp256k1EcdsaRecover.md) * [secp256k1FromProjective](/api-reference/compact-runtime/functions/secp256k1FromProjective.md) * [secp256k1Mul](/api-reference/compact-runtime/functions/secp256k1Mul.md) * [secp256k1MulGenerator](/api-reference/compact-runtime/functions/secp256k1MulGenerator.md) * [secp256k1PointX](/api-reference/compact-runtime/functions/secp256k1PointX.md) * [secp256k1PointY](/api-reference/compact-runtime/functions/secp256k1PointY.md) * [secp256k1ScalarAdd](/api-reference/compact-runtime/functions/secp256k1ScalarAdd.md) * [secp256k1ScalarInv](/api-reference/compact-runtime/functions/secp256k1ScalarInv.md) * [secp256k1ScalarMul](/api-reference/compact-runtime/functions/secp256k1ScalarMul.md) * [secp256k1ScalarNeg](/api-reference/compact-runtime/functions/secp256k1ScalarNeg.md) * [secp256k1ScalarSub](/api-reference/compact-runtime/functions/secp256k1ScalarSub.md) * [secp256k1ToProjective](/api-reference/compact-runtime/functions/secp256k1ToProjective.md) * [signatureVerifyingKey](/api-reference/compact-runtime/functions/signatureVerifyingKey.md) * [signData](/api-reference/compact-runtime/functions/signData.md) * [signingKeyFromBip340](/api-reference/compact-runtime/functions/signingKeyFromBip340.md) * [subField](/api-reference/compact-runtime/functions/subField.md) * [toBinaryRepr](/api-reference/compact-runtime/functions/toBinaryRepr.md) * [toHex](/api-reference/compact-runtime/functions/toHex.md) * [transientCommit](/api-reference/compact-runtime/functions/transientCommit.md) * [transientHash](/api-reference/compact-runtime/functions/transientHash.md) * [typeError](/api-reference/compact-runtime/functions/typeError.md) * [upgradeFromTransient](/api-reference/compact-runtime/functions/upgradeFromTransient.md) * [valueToBigInt](/api-reference/compact-runtime/functions/valueToBigInt.md) * [verifySignature](/api-reference/compact-runtime/functions/verifySignature.md) --- # CallProofData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CallProofData # Interface: CallProofData Encapsulates the data required to produce a zero-knowledge proof ## Extends[​](#extends "Direct link to Extends") * [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md) ## Properties[​](#properties "Direct link to Properties") ### circuitId[​](#circuitid "Direct link to circuitId") ``` circuitId: string; ``` The ID of the circuit that was called. *** ### commCommData?[​](#commcommdata "Direct link to commCommData?") ``` optional commCommData: CommunicationCommitmentData; ``` Data included by the parent call only if this was a sub-call *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` contractAddress: string; ``` The address of the contract defining the circuit for which this proof data is pertinent. *** ### finalQueryContext[​](#finalquerycontext "Direct link to finalQueryContext") ``` finalQueryContext: QueryContext; ``` The ledger state of the contract when the circuit finished. *** ### initialQueryContext[​](#initialquerycontext "Direct link to initialQueryContext") ``` initialQueryContext: QueryContext; ``` The ledger state of the contract before the circuit was called. *** ### input[​](#input "Direct link to input") ``` input: AlignedValue; ``` The inputs to a circuit #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md).[`input`](/api-reference/compact-runtime/interfaces/ProofData.md#input) *** ### output[​](#output "Direct link to output") ``` output: AlignedValue; ``` The outputs from a circuit #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md).[`output`](/api-reference/compact-runtime/interfaces/ProofData.md#output) *** ### privateTranscriptOutputs[​](#privatetranscriptoutputs "Direct link to privateTranscriptOutputs") ``` privateTranscriptOutputs: AlignedValue[]; ``` The transcript of the witness call outputs #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md).[`privateTranscriptOutputs`](/api-reference/compact-runtime/interfaces/ProofData.md#privatetranscriptoutputs) *** ### publicTranscript[​](#publictranscript "Direct link to publicTranscript") ``` publicTranscript: Op[]; ``` The public transcript of operations #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md).[`publicTranscript`](/api-reference/compact-runtime/interfaces/ProofData.md#publictranscript) *** ### zswapLocalState[​](#zswaplocalstate "Direct link to zswapLocalState") ``` zswapLocalState: EncodedZswapLocalState; ``` The Zswap local state this contract accumulated during the call — the shielded coins it consumed and produced. Recorded per call, not just for the root, so transaction assembly can build one offer contribution per call and bind each contract-owned input and output to the contract that actually made it. --- # CircuitContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CircuitContext # Interface: CircuitContext\ The external information accessible from within a Compact circuit call ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` = `any` ## Properties[​](#properties "Direct link to Properties") ### activeContracts?[​](#activecontracts "Direct link to activeContracts?") ``` optional activeContracts: Set; ``` The set of contract addresses currently executing on the cross-contract call stack: the entry contract plus every callee whose call has not yet returned. Maintained by [crossContractCall](/api-reference/compact-runtime/functions/crossContractCall.md) and shared by reference across the call tree (via [copyCircuitContext](/api-reference/compact-runtime/functions/copyCircuitContext.md)). Only consulted when [reentrancyGuard](#reentrancyguard) is set. *** ### callContext[​](#callcontext "Direct link to callContext") ``` callContext: CallContext; ``` The context for the current call. *** ### callProofDataTrace[​](#callproofdatatrace "Direct link to callProofDataTrace") ``` callProofDataTrace: CallProofDataTrace; ``` Sequence of calls made during the execution of the circuit (including the call for the root circuit). *** ### contractStates?[​](#contractstates "Direct link to contractStates?") ``` optional contractStates: Record; ``` The deployed [ocrt.ContractState](/api-reference/compact-runtime/classes/ContractState.md) of every cross-contract callee resolved during the execution, keyed by address. Populated by [crossContractCall](/api-reference/compact-runtime/functions/crossContractCall.md) (via the state provider) the first time a callee is reached. Retained — unlike the cached query context, which keeps only ledger data — so the implementation-binding guard can read a callee's deployed verifier key for *any* of its circuits on *every* call, including later calls to a different circuit of an already-resolved callee. The entry contract is not recorded here; only fetched callees are. *** ### costModel[​](#costmodel "Direct link to costModel") ``` costModel: CostModel; ``` The cost model to use for the execution. *** ### events[​](#events "Direct link to events") ``` events: LogEvent[]; ``` Events emitted by the on-chain VM during circuit execution from `log` operations, each tagged with the address of the emitting contract. A single global list shared across the whole call tree (threaded like [callProofDataTrace](#callproofdatatrace)); a per-contract view is a filter over the `address` tag. Surfaced via `CircuitResults.context.events`. *** ### gasCosts[​](#gascosts "Direct link to gasCosts") ``` gasCosts: Record; ``` The current gas costs for every contract in the call tree. *** ### gasLimit?[​](#gaslimit "Direct link to gasLimit?") ``` optional gasLimit: RunningCost; ``` The gas limit for this circuit. *** ### queryContexts[​](#querycontexts "Direct link to queryContexts") ``` queryContexts: Record; ``` The current query context of every contract in the call tree. *** ### reentrancyGuard?[​](#reentrancyguard "Direct link to reentrancyGuard?") ``` optional reentrancyGuard: boolean; ``` When `true`, [crossContractCall](/api-reference/compact-runtime/functions/crossContractCall.md) refuses to enter a contract that is already executing on the current call stack — i.e. a re-entrant cross-contract call (`A -> A`, or `A -> B -> A`) — and throws instead. On by default (the upstream ledger can mis-apply transcripts on re-entry). Pass `false` to [createCircuitContext](/api-reference/compact-runtime/functions/createCircuitContext.md) to opt out, e.g. for tests that deliberately exercise recursion. *** ### stateProvider?[​](#stateprovider "Direct link to stateProvider?") ``` optional stateProvider: ContractStateProvider; ``` Can fetch the current state of a contract from the blockchain. *** ### zswapLocalStates[​](#zswaplocalstates "Direct link to zswapLocalStates") ``` zswapLocalStates: Record; ``` The current Zswap local state of every contract in the call tree — the shielded-coin counterpart of [queryContexts](#querycontexts) and [gasCosts](#gascosts), and keyed the same way. Each contract keeps its own state, with its own `currentIndex`, `inputs` and `outputs`; only the transaction submitter's `coinPublicKey` is shared, since one wallet pays for the whole transaction. Threaded across cross-contract calls (see `restoreCircuitContext`) so a callee's coin operations survive its return, and mirrored onto each [CallProofData](/api-reference/compact-runtime/interfaces/CallProofData.md) so transaction assembly can attribute every input and output to the contract that made it. --- # CircuitResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CircuitResults # Interface: CircuitResults\ The results of the call to a Compact circuit ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` = `any` ### R[​](#r "Direct link to R") `R` = `any` ## Properties[​](#properties "Direct link to Properties") ### context[​](#context "Direct link to context") ``` context: CircuitContext; ``` The updated context after the circuit execution, that can be used to inform further runs *** ### gasCost[​](#gascost "Direct link to gasCost") ``` gasCost: RunningCost; ``` The gas consumption of the circuit execution *** ### result[​](#result "Direct link to result") ``` result: R; ``` The primary result, as returned from Compact --- # CommunicationCommitmentData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CommunicationCommitmentData # Interface: CommunicationCommitmentData ## Properties[​](#properties "Direct link to Properties") ### commComm[​](#commcomm "Direct link to commComm") ``` commComm: string; ``` Communication commitment computed by the parent. *** ### commCommRand[​](#commcommrand "Direct link to commCommRand") ``` commCommRand: string; ``` Randomness used by the parent in the commitment. --- # CompactType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactType # Interface: CompactType\ A runtime representation of a type in Compact ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Methods[​](#methods "Direct link to Methods") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` The field-aligned binary alignment of this type. #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) *** ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): A; ``` Converts this type's field-aligned binary representation to its TypeScript representation destructively; (partially) consuming the input, and ignoring superflous data for chaining. #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") `A` *** ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` Converts this type's TypeScript representation to its field-aligned binary representation #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") `A` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # ConstructorContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ConstructorContext # Interface: ConstructorContext\ Passed to the constructor of a contract. Used to compute the contract's initial ledger state. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` = `any` ## Properties[​](#properties "Direct link to Properties") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") ``` initialPrivateState: PS; ``` The private state we would like to use to execute the contract's constructor. *** ### initialZswapLocalState[​](#initialzswaplocalstate "Direct link to initialZswapLocalState") ``` initialZswapLocalState: EncodedZswapLocalState; ``` An initial (usually empty) Zswap local state to use to execute the contract's constructor. --- # ConstructorResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ConstructorResult # Interface: ConstructorResult\ The result of executing a contract constructor. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` = `any` ## Properties[​](#properties "Direct link to Properties") ### currentContractState[​](#currentcontractstate "Direct link to currentContractState") ``` currentContractState: ContractState; ``` The contract's initial ledger (public state). *** ### currentPrivateState[​](#currentprivatestate "Direct link to currentPrivateState") ``` currentPrivateState: PS; ``` The contract's initial private state. Potentially different from the private state passed in [ConstructorContext](/api-reference/compact-runtime/interfaces/ConstructorContext.md). *** ### currentZswapLocalState[​](#currentzswaplocalstate "Direct link to currentZswapLocalState") ``` currentZswapLocalState: EncodedZswapLocalState; ``` The contract's initial Zswap local state. Potentially includes outputs created in the contract's constructor. --- # ContractStateProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractStateProvider # Interface: ContractStateProvider A user-provided interface for fetching the public state of a contract at a given block hash. Used exclusively to retrieve the state of cross-contract call targets at runtime. Assumes state returned is the post-block evaluation contract state. The `parentBlockHash` value in [CircuitContext](/api-reference/compact-runtime/interfaces/CircuitContext.md) is used for as the `blockHash` argument. ## Methods[​](#methods "Direct link to Methods") ### getContractState()[​](#getcontractstate "Direct link to getContractState()") ``` getContractState(blockHash, address): Promise; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### blockHash[​](#blockhash "Direct link to blockHash") `string` ##### address[​](#address "Direct link to address") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<[`ContractState`](/api-reference/compact-runtime/classes/ContractState.md) | `undefined`> --- # CurvePoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CurvePoint # Interface: CurvePoint A point in the embedded elliptic curve. TypeScript representation of the Compact type of the same name ## Properties[​](#properties "Direct link to Properties") ### x[​](#x "Direct link to x") ``` readonly x: bigint; ``` *** ### y[​](#y "Direct link to y") ``` readonly y: bigint; ``` --- # EncodedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedCoinInfo # Interface: EncodedCoinInfo A [CoinInfo](/api-reference/compact-runtime/type-aliases/CoinInfo.md) with its fields encoded as byte strings. This representation is used internally by the contract executable. ## Properties[​](#properties "Direct link to Properties") ### color[​](#color "Direct link to color") ``` readonly color: Uint8Array; ``` The coin's type, identifying the currency it represents. *** ### nonce[​](#nonce "Direct link to nonce") ``` readonly nonce: Uint8Array; ``` The coin's randomness, preventing it from colliding with other coins. *** ### value[​](#value "Direct link to value") ``` readonly value: bigint; ``` The coin's value, in atomic units dependent on the currency. Bounded to be a non-negative 64-bit integer. --- # EncodedCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedCoinPublicKey # Interface: EncodedCoinPublicKey A [CoinPublicKey](/api-reference/compact-runtime/type-aliases/CoinPublicKey.md) encoded as a byte string. This representation is used internally by the contract executable. ## Properties[​](#properties "Direct link to Properties") ### bytes[​](#bytes "Direct link to bytes") ``` readonly bytes: Uint8Array; ``` The coin public key's bytes. --- # EncodedContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedContractAddress # Interface: EncodedContractAddress A [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md) encoded as a byte string. This representation is used internally by the contract executable. ## Properties[​](#properties "Direct link to Properties") ### bytes[​](#bytes "Direct link to bytes") ``` readonly bytes: Uint8Array; ``` The contract address's bytes. --- # EncodedQualifiedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedQualifiedCoinInfo # Interface: EncodedQualifiedCoinInfo A [QualifiedCoinInfo](/api-reference/compact-runtime/type-aliases/QualifiedCoinInfo.md) with its fields encoded as byte strings. This representation is used internally by the contract executable. ## Properties[​](#properties "Direct link to Properties") ### color[​](#color "Direct link to color") ``` readonly color: Uint8Array; ``` The coin's type, identifying the currency it represents. *** ### mt\_index[​](#mt_index "Direct link to mt_index") ``` readonly mt_index: bigint; ``` The coin's location in the chain's Merkle tree of coin commitments. Bounded to be a non-negative 64-bit integer. *** ### nonce[​](#nonce "Direct link to nonce") ``` readonly nonce: Uint8Array; ``` The coin's randomness, preventing it from colliding with other coins. *** ### value[​](#value "Direct link to value") ``` readonly value: bigint; ``` The coin's value, in atomic units dependent on the currency. Bounded to be a non-negative 64-bit integer. --- # EncodedQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedQualifiedShieldedCoinInfo # Interface: EncodedQualifiedShieldedCoinInfo A QualifiedCoinInfo with its fields encoded as byte strings. This representation is used internally by the contract executable. ## Extends[​](#extends "Direct link to Extends") * [`EncodedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md) ## Properties[​](#properties "Direct link to Properties") ### color[​](#color "Direct link to color") ``` readonly color: Uint8Array; ``` The coin's type, identifying the currency it represents. #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`EncodedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md).[`color`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md#color) *** ### mt\_index[​](#mt_index "Direct link to mt_index") ``` readonly mt_index: bigint; ``` The coin's location in the chain's Merkle tree of coin commitments. Bounded to be a non-negative 64-bit integer. *** ### nonce[​](#nonce "Direct link to nonce") ``` readonly nonce: Uint8Array; ``` The coin's randomness, preventing it from colliding with other coins. #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`EncodedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md).[`nonce`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md#nonce) *** ### value[​](#value "Direct link to value") ``` readonly value: bigint; ``` The coin's value, in atomic units dependent on the currency. Bounded to be a non-negative 64-bit integer. #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`EncodedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md).[`value`](/api-reference/compact-runtime/interfaces/EncodedShieldedCoinInfo.md#value) --- # EncodedRecipient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedRecipient # Interface: EncodedRecipient A [Recipient](/api-reference/compact-runtime/interfaces/Recipient.md) with its fields encoded as byte strings. This representation is used internally by the contract executable. ## Properties[​](#properties "Direct link to Properties") ### is\_left[​](#is_left "Direct link to is_left") ``` readonly is_left: boolean; ``` Whether the recipient is a user or a contract. *** ### left[​](#left "Direct link to left") ``` readonly left: EncodedCoinPublicKey; ``` The recipient's public key, if the recipient is a user. *** ### right[​](#right "Direct link to right") ``` readonly right: EncodedContractAddress; ``` The recipient's contract address, if the recipient is a contract. --- # EncodedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedShieldedCoinInfo # Interface: EncodedShieldedCoinInfo A [ShieldedCoinInfo](/api-reference/compact-runtime/type-aliases/ShieldedCoinInfo.md) with its fields encoded as byte strings. This representation is used internally by the contract executable. ## Extended by[​](#extended-by "Direct link to Extended by") * [`EncodedQualifiedShieldedCoinInfo`](/api-reference/compact-runtime/interfaces/EncodedQualifiedShieldedCoinInfo.md) ## Properties[​](#properties "Direct link to Properties") ### color[​](#color "Direct link to color") ``` readonly color: Uint8Array; ``` The coin's type, identifying the currency it represents. *** ### nonce[​](#nonce "Direct link to nonce") ``` readonly nonce: Uint8Array; ``` The coin's randomness, preventing it from colliding with other coins. *** ### value[​](#value "Direct link to value") ``` readonly value: bigint; ``` The coin's value, in atomic units dependent on the currency. Bounded to be a non-negative 64-bit integer. --- # EncodedZswapLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedZswapLocalState # Interface: EncodedZswapLocalState Tracks the coins consumed and produced throughout circuit execution. ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") ``` coinPublicKey: EncodedCoinPublicKey; ``` The Zswap coin public key of the user executing the circuit. *** ### currentIndex[​](#currentindex "Direct link to currentIndex") ``` currentIndex: bigint; ``` The Merkle tree index of the next coin produced. *** ### inputs[​](#inputs "Direct link to inputs") ``` inputs: EncodedQualifiedShieldedCoinInfo[]; ``` The coins consumed as inputs to the circuit. *** ### outputs[​](#outputs "Direct link to outputs") ``` outputs: { coinInfo: EncodedShieldedCoinInfo; recipient: EncodedRecipient; }[]; ``` The coins produced as outputs from the circuit. #### coinInfo[​](#coininfo "Direct link to coinInfo") ``` coinInfo: EncodedShieldedCoinInfo; ``` #### recipient[​](#recipient "Direct link to recipient") ``` recipient: EncodedRecipient; ``` --- # JubjubPoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / JubjubPoint # Interface: JubjubPoint A point in the embedded elliptic curve. TypeScript representation of the Compact type of the same name ## Properties[​](#properties "Direct link to Properties") ### x[​](#x "Direct link to x") ``` readonly x: bigint; ``` *** ### y[​](#y "Direct link to y") ``` readonly y: bigint; ``` --- # JubjubSchnorrSignature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / JubjubSchnorrSignature # Interface: JubjubSchnorrSignature A Schnorr signature over the JubJub curve. TypeScript representation of the Compact type of the same name. ## Properties[​](#properties "Direct link to Properties") ### announcement[​](#announcement "Direct link to announcement") ``` readonly announcement: JubjubPoint; ``` *** ### response[​](#response "Direct link to response") ``` readonly response: bigint; ``` --- # MerkleTreeDigest > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MerkleTreeDigest # Interface: MerkleTreeDigest The hash value of a Merkle tree. TypeScript representation of the Compact type of the same name ## Properties[​](#properties "Direct link to Properties") ### field[​](#field "Direct link to field") ``` readonly field: bigint; ``` --- # MerkleTreePath > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MerkleTreePath # Interface: MerkleTreePath\ A path demonstrating inclusion in a Merkle tree. TypeScript representation of the Compact type of the same name. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Properties[​](#properties "Direct link to Properties") ### leaf[​](#leaf "Direct link to leaf") ``` readonly leaf: A; ``` *** ### path[​](#path "Direct link to path") ``` readonly path: MerkleTreePathEntry[]; ``` --- # MerkleTreePathEntry > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MerkleTreePathEntry # Interface: MerkleTreePathEntry An entry in a Merkle path. TypeScript representation of the Compact type of the same name. ## Properties[​](#properties "Direct link to Properties") ### goes\_left[​](#goes_left "Direct link to goes_left") ``` readonly goes_left: boolean; ``` *** ### sibling[​](#sibling "Direct link to sibling") ``` readonly sibling: MerkleTreeDigest; ``` --- # NativePoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.14.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / NativePoint # Interface: NativePoint A point in the embedded elliptic curve. TypeScript representation of the Compact type of the same name ## Properties[​](#properties "Direct link to Properties") ### x[​](#x "Direct link to x") ``` readonly x: bigint; ``` *** ### y[​](#y "Direct link to y") ``` readonly y: bigint; ``` --- # PartialProofData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / PartialProofData # Interface: PartialProofData Encapsulates the data required to produce a zero-knowledge proof except the circuit output ## Extended by[​](#extended-by "Direct link to Extended by") * [`ProofData`](/api-reference/compact-runtime/interfaces/ProofData.md) ## Properties[​](#properties "Direct link to Properties") ### input[​](#input "Direct link to input") ``` input: AlignedValue; ``` The inputs to a circuit *** ### privateTranscriptOutputs[​](#privatetranscriptoutputs "Direct link to privateTranscriptOutputs") ``` privateTranscriptOutputs: AlignedValue[]; ``` The transcript of the witness call outputs *** ### publicTranscript[​](#publictranscript "Direct link to publicTranscript") ``` publicTranscript: Op[]; ``` The public transcript of operations --- # ProofData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ProofData # Interface: ProofData Encapsulates the data required to produce a zero-knowledge proof ## Extends[​](#extends "Direct link to Extends") * [`PartialProofData`](/api-reference/compact-runtime/interfaces/PartialProofData.md) ## Extended by[​](#extended-by "Direct link to Extended by") * [`CallProofData`](/api-reference/compact-runtime/interfaces/CallProofData.md) ## Properties[​](#properties "Direct link to Properties") ### input[​](#input "Direct link to input") ``` input: AlignedValue; ``` The inputs to a circuit #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`PartialProofData`](/api-reference/compact-runtime/interfaces/PartialProofData.md).[`input`](/api-reference/compact-runtime/interfaces/PartialProofData.md#input) *** ### output[​](#output "Direct link to output") ``` output: AlignedValue; ``` The outputs from a circuit *** ### privateTranscriptOutputs[​](#privatetranscriptoutputs "Direct link to privateTranscriptOutputs") ``` privateTranscriptOutputs: AlignedValue[]; ``` The transcript of the witness call outputs #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`PartialProofData`](/api-reference/compact-runtime/interfaces/PartialProofData.md).[`privateTranscriptOutputs`](/api-reference/compact-runtime/interfaces/PartialProofData.md#privatetranscriptoutputs) *** ### publicTranscript[​](#publictranscript "Direct link to publicTranscript") ``` publicTranscript: Op[]; ``` The public transcript of operations #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`PartialProofData`](/api-reference/compact-runtime/interfaces/PartialProofData.md).[`publicTranscript`](/api-reference/compact-runtime/interfaces/PartialProofData.md#publictranscript) --- # Recipient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Recipient # Interface: Recipient The recipient of a coin produced by a circuit. ## Properties[​](#properties "Direct link to Properties") ### is\_left[​](#is_left "Direct link to is_left") ``` readonly is_left: boolean; ``` Whether the recipient is a user or a contract. *** ### left[​](#left "Direct link to left") ``` readonly left: string; ``` The recipient's public key, if the recipient is a user. *** ### right[​](#right "Direct link to right") ``` readonly right: string; ``` The recipient's contract address, if the recipient is a contract. --- # Secp256k1Point > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Secp256k1Point # Interface: Secp256k1Point A point in the foreign secp256k1 elliptic curve. TypeScript representation of the Compact type of the same name. When identity = true, x and y should be 0. ## Properties[​](#properties "Direct link to Properties") ### identity[​](#identity "Direct link to identity") ``` readonly identity: boolean; ``` *** ### x[​](#x "Direct link to x") ``` readonly x: bigint; ``` *** ### y[​](#y "Direct link to y") ``` readonly y: bigint; ``` --- # WitnessContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / WitnessContext # Interface: WitnessContext\ The external information accessible from within a Compact witness call ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### L[​](#l "Direct link to L") `L` = `any` ### PS[​](#ps "Direct link to PS") `PS` = `any` ## Properties[​](#properties "Direct link to Properties") ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: string; ``` The address of the contract being called *** ### ledger[​](#ledger "Direct link to ledger") ``` readonly ledger: L; ``` The projected ledger state, if the transaction were to run against the ledger state as you locally see it currently *** ### privateState[​](#privatestate "Direct link to privateState") ``` readonly privateState: PS; ``` The current private state for the contract --- # ZswapLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ZswapLocalState # Interface: ZswapLocalState Tracks the coins consumed and produced throughout circuit execution. ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") ``` coinPublicKey: string; ``` The Zswap coin public key of the user executing the circuit. *** ### currentIndex[​](#currentindex "Direct link to currentIndex") ``` currentIndex: bigint; ``` The Merkle tree index of the next coin produced. *** ### inputs[​](#inputs "Direct link to inputs") ``` inputs: QualifiedShieldedCoinInfo[]; ``` The coins consumed as inputs to the circuit. *** ### outputs[​](#outputs "Direct link to outputs") ``` outputs: { coinInfo: ShieldedCoinInfo; recipient: Recipient; }[]; ``` The coins produced as outputs from the circuit. #### coinInfo[​](#coininfo "Direct link to coinInfo") ``` coinInfo: ShieldedCoinInfo; ``` #### recipient[​](#recipient "Direct link to recipient") ``` recipient: Recipient; ``` --- # AlignedValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / AlignedValue # Type Alias: AlignedValue ``` type AlignedValue = { alignment: Alignment; value: Value; }; ``` An onchain data value, in field-aligned binary format, annotated with its alignment. ## Properties[​](#properties "Direct link to Properties") ### alignment[​](#alignment "Direct link to alignment") ``` alignment: Alignment; ``` *** ### value[​](#value "Direct link to value") ``` value: Value; ``` --- # Alignment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Alignment # Type Alias: Alignment ``` type Alignment = AlignmentSegment[]; ``` The alignment of an onchain field-aligned binary data value. --- # AlignmentAtom > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / AlignmentAtom # Type Alias: AlignmentAtom ``` type AlignmentAtom = | { tag: "compress"; } | { tag: "field"; } | { length: number; tag: "bytes"; }; ``` A atom in a larger [Alignment](/api-reference/compact-runtime/type-aliases/Alignment.md). --- # AlignmentSegment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / AlignmentSegment # Type Alias: AlignmentSegment ``` type AlignmentSegment = | { tag: "option"; value: Alignment[]; } | { tag: "atom"; value: AlignmentAtom; }; ``` A segment in a larger [Alignment](/api-reference/compact-runtime/type-aliases/Alignment.md). --- # BlockContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / BlockContext # Type Alias: BlockContext ``` type BlockContext = { lastBlockTime: bigint; parentBlockHash: string; secondsSinceEpoch: bigint; secondsSinceEpochErr: number; }; ``` Context information about the block forwarded to [CallContext](/api-reference/compact-runtime/type-aliases/CallContext.md). ## Properties[​](#properties "Direct link to Properties") ### lastBlockTime[​](#lastblocktime "Direct link to lastBlockTime") ``` lastBlockTime: bigint; ``` The [secondsSinceEpoch](#secondssinceepoch) of the previous block *** ### parentBlockHash[​](#parentblockhash "Direct link to parentBlockHash") ``` parentBlockHash: string; ``` The hash of the block prior to this transaction, as a hex-encoded string *** ### secondsSinceEpoch[​](#secondssinceepoch "Direct link to secondsSinceEpoch") ``` secondsSinceEpoch: bigint; ``` The seconds since the UNIX epoch that have elapsed *** ### secondsSinceEpochErr[​](#secondssinceepocherr "Direct link to secondsSinceEpochErr") ``` secondsSinceEpochErr: number; ``` The maximum error on [secondsSinceEpoch](#secondssinceepoch) that should occur, as a positive seconds value --- # CallContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CallContext # Type Alias: CallContext ``` type CallContext = { balance: Map; caller?: PublicAddress; comIndices: Map; lastBlockTime: bigint; ownAddress: ContractAddress; parentBlockHash: string; secondsSinceEpoch: bigint; secondsSinceEpochErr: number; }; ``` The context information of a call provided to the VM. ## Properties[​](#properties "Direct link to Properties") ### balance[​](#balance "Direct link to balance") ``` balance: Map; ``` The balances held by the called contract at the time it was called. *** ### caller?[​](#caller "Direct link to caller?") ``` optional caller: PublicAddress; ``` A public address identifying an entity. *** ### comIndices[​](#comindices "Direct link to comIndices") ``` comIndices: Map; ``` The commitment indices map accessible to the contract. *** ### lastBlockTime[​](#lastblocktime "Direct link to lastBlockTime") ``` lastBlockTime: bigint; ``` The [secondsSinceEpoch](#secondssinceepoch) of the previous block *** ### ownAddress[​](#ownaddress "Direct link to ownAddress") ``` ownAddress: ContractAddress; ``` *** ### parentBlockHash[​](#parentblockhash "Direct link to parentBlockHash") ``` parentBlockHash: string; ``` The hash of the block prior to this transaction, as a hex-encoded string *** ### secondsSinceEpoch[​](#secondssinceepoch "Direct link to secondsSinceEpoch") ``` secondsSinceEpoch: bigint; ``` The seconds since the UNIX epoch that have elapsed *** ### secondsSinceEpochErr[​](#secondssinceepocherr "Direct link to secondsSinceEpochErr") ``` secondsSinceEpochErr: number; ``` The maximum error on [secondsSinceEpoch](#secondssinceepoch) that should occur, as a positive seconds value --- # CallProofDataTrace > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CallProofDataTrace # Type Alias: CallProofDataTrace ``` type CallProofDataTrace = CallProofData[]; ``` List of data needed to construct proofs and transactions for all circuit calls resulting from executing a root circuit. The calls are in depth-first traversal order. In other words, the first circuit to complete execution is first, and the last circuit to complete execution (the root circuit) is last. --- # CircuitId > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CircuitId # Type Alias: CircuitId ``` type CircuitId = string; ``` --- # CoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CoinCommitment # Type Alias: CoinCommitment ``` type CoinCommitment = string; ``` A Zswap coin commitment, as a hex-encoded 256-bit bitstring --- # CoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CoinInfo # Type Alias: CoinInfo ``` type CoinInfo = { nonce: Nonce; type: TokenType; value: bigint; }; ``` Information required to create a new coin, alongside details about the recipient ## Properties[​](#properties "Direct link to Properties") ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins *** ### type[​](#type "Direct link to type") ``` type: TokenType; ``` The coin's type, identifying the currency it represents *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # CoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CoinPublicKey # Type Alias: CoinPublicKey ``` type CoinPublicKey = string; ``` A user public key capable of receiving Zswap coins, as a hex-encoded 32-byte string --- # CommunicationCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CommunicationCommitment # Type Alias: CommunicationCommitment ``` type CommunicationCommitment = string; ``` A hex-encoded commitment of data shared between two contracts in a call --- # CommunicationCommitmentRand > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CommunicationCommitmentRand # Type Alias: CommunicationCommitmentRand ``` type CommunicationCommitmentRand = string; ``` The hex-encoded randomness to [CommunicationCommitment](/api-reference/compact-runtime/type-aliases/CommunicationCommitment.md) --- # ContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractAddress # Type Alias: ContractAddress ``` type ContractAddress = string; ``` A contract address, as a hex-encoded 32-byte string --- # ContractReferenceLocations > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractReferenceLocations # Type Alias: ContractReferenceLocations ``` type ContractReferenceLocations = | EmptyPublicLedger | PublicLedgerSegments; ``` A data structure indicating the locations of all contract references in a given ledger state. If it is a [EmptyPublicLedger](/api-reference/compact-runtime/type-aliases/EmptyPublicLedger.md), then no contract references are present in the ledger state. If it is a [PublicLedgerSegments](/api-reference/compact-runtime/type-aliases/PublicLedgerSegments.md), then contract references are present and can be extracted using [contractDependencies](/api-reference/compact-runtime/functions/contractDependencies.md). --- # DomainSeparator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / DomainSeparator # Type Alias: DomainSeparator ``` type DomainSeparator = Uint8Array; ``` A token domain seperator, the pre-stage of `TokenType`, as 32-byte bytearray --- # DomainSeperator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / DomainSeperator # Type Alias: DomainSeperator ``` type DomainSeperator = Uint8Array; ``` A token domain seperator, the pre-stage of `TokenType`, as 32-byte bytearray --- # DustTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / DustTokenType # Type Alias: DustTokenType ``` type DustTokenType = { tag: "dust"; }; ``` Dust token type ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: "dust"; ``` --- # Effects > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Effects # Type Alias: Effects ``` type Effects = { claimedContractCalls: [bigint, ContractAddress, string, Fr][]; claimedNullifiers: Nullifier[]; claimedShieldedReceives: CoinCommitment[]; claimedShieldedSpends: CoinCommitment[]; claimedUnshieldedSpends: Map<[TokenType, PublicAddress], bigint>; shieldedMints: Map; unshieldedInputs: Map; unshieldedMints: Map; unshieldedOutputs: Map; }; ``` The contract-external effects of a transcript. ## Properties[​](#properties "Direct link to Properties") ### claimedContractCalls[​](#claimedcontractcalls "Direct link to claimedContractCalls") ``` claimedContractCalls: [bigint, ContractAddress, string, Fr][]; ``` The contracts called from this contract. The values are, in order: * The sequence number of this call * The contract being called * The entry point being called * The communications commitment *** ### claimedNullifiers[​](#claimednullifiers "Direct link to claimedNullifiers") ``` claimedNullifiers: Nullifier[]; ``` The nullifiers (spends) this contract call requires *** ### claimedShieldedReceives[​](#claimedshieldedreceives "Direct link to claimedShieldedReceives") ``` claimedShieldedReceives: CoinCommitment[]; ``` The coin commitments (outputs) this contract call requires, as coins received *** ### claimedShieldedSpends[​](#claimedshieldedspends "Direct link to claimedShieldedSpends") ``` claimedShieldedSpends: CoinCommitment[]; ``` The coin commitments (outputs) this contract call requires, as coins sent *** ### claimedUnshieldedSpends[​](#claimedunshieldedspends "Direct link to claimedUnshieldedSpends") ``` claimedUnshieldedSpends: Map<[TokenType, PublicAddress], bigint>; ``` The unshielded UTXO outputs this contract expects to be present. *** ### shieldedMints[​](#shieldedmints "Direct link to shieldedMints") ``` shieldedMints: Map; ``` The shielded tokens minted in this call, as a map from hex-encoded 256-bit domain separators to unsigned 64-bit integers. *** ### unshieldedInputs[​](#unshieldedinputs "Direct link to unshieldedInputs") ``` unshieldedInputs: Map; ``` The unshielded inputs this contract expects. *** ### unshieldedMints[​](#unshieldedmints "Direct link to unshieldedMints") ``` unshieldedMints: Map; ``` The unshielded tokens minted in this call, as a map from hex-encoded 256-bit domain separators to unsigned 64-bit integers. *** ### unshieldedOutputs[​](#unshieldedoutputs "Direct link to unshieldedOutputs") ``` unshieldedOutputs: Map; ``` The unshielded outputs this contract authorizes. --- # EmptyPublicLedger > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EmptyPublicLedger # Type Alias: EmptyPublicLedger ``` type EmptyPublicLedger = { indices: undefined; tag: "publicLedgerArray"; }; ``` A type indicating that no contract references are present in a contract's ledger state. ## Properties[​](#properties "Direct link to Properties") ### indices[​](#indices "Direct link to indices") ``` indices: undefined; ``` *** ### tag[​](#tag "Direct link to tag") ``` tag: "publicLedgerArray"; ``` --- # EncodedStateValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / EncodedStateValue # Type Alias: EncodedStateValue ``` type EncodedStateValue = | { tag: "null"; } | { content: AlignedValue; tag: "cell"; } | { content: Map; tag: "map"; } | { content: EncodedStateValue[]; tag: "array"; } | { content: [number, Map]; tag: "boundedMerkleTree"; }; ``` An alternative encoding of [StateValue](/api-reference/compact-runtime/classes/StateValue.md) for use in [Op](/api-reference/compact-runtime/type-aliases/Op.md) for technical reasons --- # Fr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Fr # Type Alias: Fr ``` type Fr = Uint8Array; ``` An internal encoding of a value of the proof systems scalar field --- # GatherResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / GatherResult # Type Alias: GatherResult ``` type GatherResult = | { content: AlignedValue; tag: "read"; } | { content: { data: EncodedStateValue; eventType: LogEventType; version: number; }; tag: "log"; }; ``` An individual result of observing the results of a non-verifying VM program execution --- # Key > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Key # Type Alias: Key ``` type Key = | { tag: "value"; value: AlignedValue; } | { tag: "stack"; }; ``` A key used to index into an array or map in the onchain VM --- # LogEvent > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / LogEvent # Type Alias: LogEvent ``` type LogEvent = Extract["content"] & { address: ContractAddress; }; ``` A `GatherResult` narrowed to log emissions, tagged with the address of the contract that emitted it; `content` is the encoded `VersionedLogItem` array. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### address[​](#address "Direct link to address") ``` address: ContractAddress; ``` --- # Nonce > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Nonce # Type Alias: Nonce ``` type Nonce = string; ``` A Zswap nonce, as a hex-encoded 256-bit string --- # Nullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Nullifier # Type Alias: Nullifier ``` type Nullifier = string; ``` A Zswap nullifier, as a hex-encoded 256-bit bitstring --- # Op > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Op # Type Alias: Op\ ``` type Op = | { noop: { n: number; }; } | "lt" | "eq" | "type" | "size" | "new" | "and" | "or" | "neg" | "log" | "root" | "pop" | { popeq: { cached: boolean; result: R; }; } | { addi: { immediate: number; }; } | { subi: { immediate: number; }; } | { push: { storage: boolean; value: EncodedStateValue; }; } | { branch: { skip: number; }; } | { jmp: { skip: number; }; } | "add" | "sub" | { concat: { cached: boolean; n: number; }; } | "member" | { rem: { cached: boolean; }; } | { dup: { n: number; }; } | { swap: { n: number; }; } | { idx: { cached: boolean; path: Key[]; pushPath: boolean; }; } | { ins: { cached: boolean; n: number; }; } | "ckpt"; ``` An individual operation in the onchain VM ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### R[​](#r "Direct link to R") `R` `null` or [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md), for gathering and verifying mode respectively --- # PublicAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / PublicAddress # Type Alias: PublicAddress ``` type PublicAddress = | { address: UserAddress; tag: "user"; } | { address: ContractAddress; tag: "contract"; }; ``` A public address that an entity can be identified by --- # PublicLedgerSegments > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / PublicLedgerSegments # Type Alias: PublicLedgerSegments ``` type PublicLedgerSegments = { indices: Record; tag: "publicLedgerArray"; }; ``` A data structure indicating the locations of all contract references in a given ledger state. ## Properties[​](#properties "Direct link to Properties") ### indices[​](#indices "Direct link to indices") ``` indices: Record; ``` For reasonably small ledger states, the keys of the record identify locations of ADTs in the ledger state. For example, if a Compact source file contains ``` contract C {}; struct Struct1 { a: Field; b: C; } ledger ls1: List[Field]; ledger ls2: List[C]; ledger ls3: Set[Struct1]; ``` then the indices record will contain keys `1` and `2`, since ledger declarations `1` and `2` contain contract references while ledger declaration `0` (`List[Field]`) does not. However, the ledger implementation has a fixed maximum length on the state arrays produced by StateValue.toArray. When the number of entries in a given state exceeds the maximum, StateValue.toArray produces nested state arrays, where each inner state array is within the maximum. For each nested state array, there will be a key in the indices record pointing to a PublicLedgerSegments object. *** ### tag[​](#tag "Direct link to tag") ``` tag: "publicLedgerArray"; ``` --- # QualifiedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / QualifiedCoinInfo # Type Alias: QualifiedCoinInfo ``` type QualifiedCoinInfo = { mt_index: bigint; nonce: Nonce; type: TokenType; value: bigint; }; ``` Information required to spend an existing coin, alongside authorization of the owner ## Properties[​](#properties "Direct link to Properties") ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` The coin's location in the chain's Merkle tree of coin commitments Bounded to be a non-negative 64-bit integer *** ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins *** ### type[​](#type "Direct link to type") ``` type: TokenType; ``` The coin's type, identifying the currency it represents *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # QualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / QualifiedShieldedCoinInfo # Type Alias: QualifiedShieldedCoinInfo ``` type QualifiedShieldedCoinInfo = { mt_index: bigint; nonce: Nonce; type: RawTokenType; value: bigint; }; ``` Information required to spend an existing coin, alongside authorization of the owner ## Properties[​](#properties "Direct link to Properties") ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` The coin's location in the chain's Merkle tree of coin commitments Bounded to be a non-negative 64-bit integer *** ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The coin's type, identifying the currency it represents *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # RawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / RawTokenType # Type Alias: RawTokenType ``` type RawTokenType = string; ``` The internal identifier attached to a [TokenType](/api-reference/compact-runtime/type-aliases/TokenType.md), as a hex-encoded string. --- # RunningCost > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / RunningCost # Type Alias: RunningCost ``` type RunningCost = { bytesDeleted: bigint; bytesWritten: bigint; computeTime: bigint; readTime: bigint; }; ``` A running tally of synthetic resource costs. ## Properties[​](#properties "Direct link to Properties") ### bytesDeleted[​](#bytesdeleted "Direct link to bytesDeleted") ``` bytesDeleted: bigint; ``` The number of (modelled) bytes deleted. *** ### bytesWritten[​](#byteswritten "Direct link to bytesWritten") ``` bytesWritten: bigint; ``` The number of (modelled) bytes written. *** ### computeTime[​](#computetime "Direct link to computeTime") ``` computeTime: bigint; ``` The amount of (modelled) time spent in single-threaded compute, measured in picoseconds. *** ### readTime[​](#readtime "Direct link to readTime") ``` readTime: bigint; ``` The amount of (modelled) time spent reading from disk, measured in picoseconds. --- # ShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ShieldedCoinInfo # Type Alias: ShieldedCoinInfo ``` type ShieldedCoinInfo = { nonce: Nonce; type: RawTokenType; value: bigint; }; ``` Information required to create a new coin, alongside details about the recipient ## Properties[​](#properties "Direct link to Properties") ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The coin's type, identifying the currency it represents *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # ShieldedTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ShieldedTokenType # Type Alias: ShieldedTokenType ``` type ShieldedTokenType = { raw: RawTokenType; tag: "shielded"; }; ``` Shielded token type (or color), as a hex-encoded 32-byte string ## Properties[​](#properties "Direct link to Properties") ### raw[​](#raw "Direct link to raw") ``` raw: RawTokenType; ``` *** ### tag[​](#tag "Direct link to tag") ``` tag: "shielded"; ``` --- # Signature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Signature # Type Alias: Signature ``` type Signature = { tag: SignatureKind; value: string; }; ``` A hex-encoded signature annotated with its kind ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: SignatureKind; ``` *** ### value[​](#value "Direct link to value") ``` value: string; ``` --- # SignatureVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SignatureVerifyingKey # Type Alias: SignatureVerifyingKey ``` type SignatureVerifyingKey = { tag: SignatureKind; value: string; }; ``` A hex-encoded signature verifying key annotated with its kind ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: SignatureKind; ``` *** ### value[​](#value "Direct link to value") ``` value: string; ``` --- # SigningKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SigningKey # Type Alias: SigningKey ``` type SigningKey = { tag: SignatureKind; value: string; }; ``` A hex-encoded signing key annotated with its kind ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: SignatureKind; ``` *** ### value[​](#value "Direct link to value") ``` value: string; ``` --- # SparseCompactADT > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactADT # Type Alias: SparseCompactADT ``` type SparseCompactADT = | SparseCompactCellADT | SparseCompactArrayLikeADT | SparseCompactMapADT; ``` A discriminated union describing the locations of contract references in either a Compact `Cell`, `List`, `Set`, or `Map` ADT. --- # SparseCompactArrayLikeADT > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactArrayLikeADT # Type Alias: SparseCompactArrayLikeADT ``` type SparseCompactArrayLikeADT = | SparseCompactSetADT | SparseCompactListADT; ``` A data structure indicating the locations of all contract references in a Compact `Set` or `List` ADT. --- # SparseCompactCellADT > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactCellADT # Type Alias: SparseCompactCellADT ``` type SparseCompactCellADT = { tag: "cell"; valueType: SparseCompactValue; }; ``` A data structure indicating the locations of all contract references in a Compact `Cell` ADT. ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: "cell"; ``` *** ### valueType[​](#valuetype "Direct link to valueType") ``` valueType: SparseCompactValue; ``` A data structure indicating the locations of all contract references in the Compact value contained in the outer `Cell` ADT. --- # SparseCompactContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactContractAddress # Type Alias: SparseCompactContractAddress ``` type SparseCompactContractAddress = { tag: "contractAddress"; }; ``` A data structure indicating that the current CompactValue being explored is a contract reference. When this type is recognized, the current CompactValue should be a [ContractAddress](/api-reference/compact-runtime/type-aliases/ContractAddress.md), and the address is added to the dependency set. ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: "contractAddress"; ``` --- # SparseCompactListADT > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactListADT # Type Alias: SparseCompactListADT ``` type SparseCompactListADT = { tag: "list"; valueType: SparseCompactValue; }; ``` A data structure indicating the locations of all contract references in a Compact `List` ADT. ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: "list"; ``` *** ### valueType[​](#valuetype "Direct link to valueType") ``` valueType: SparseCompactValue; ``` A data structure indicating the locations of all contract references in a Compact value in the outer `List` ADT. --- # SparseCompactMapADT > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactMapADT # Type Alias: SparseCompactMapADT ``` type SparseCompactMapADT = { keyType?: SparseCompactValue; tag: "map"; valueType?: | SparseCompactADT | SparseCompactValue; }; ``` A data structure indicating the locations of all contract references in a Compact `Map` ADT. ## Properties[​](#properties "Direct link to Properties") ### keyType?[​](#keytype "Direct link to keyType?") ``` optional keyType: SparseCompactValue; ``` A data structure indicating the locations of all contract references in the Compact values that are the keys of the outer `Map` ADT. *** ### tag[​](#tag "Direct link to tag") ``` tag: "map"; ``` *** ### valueType?[​](#valuetype "Direct link to valueType?") ``` optional valueType: | SparseCompactADT | SparseCompactValue; ``` A data structure indicating the locations of all contract references in the Compact entities that are the values of the outer `Map` ADT. Since the values of a `Map` ADT may be either Compact values or other `Map` ADTs, we take the union of the corresponding data structures. --- # SparseCompactSetADT > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactSetADT # Type Alias: SparseCompactSetADT ``` type SparseCompactSetADT = { tag: "set"; valueType: SparseCompactValue; }; ``` A data structure indicating the locations of all contract references in a Compact `Set` ADT. ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: "set"; ``` *** ### valueType[​](#valuetype "Direct link to valueType") ``` valueType: SparseCompactValue; ``` A data structure indicating the locations of all contract references in a Compact value in the outer `Set` ADT. --- # SparseCompactStruct > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactStruct # Type Alias: SparseCompactStruct ``` type SparseCompactStruct = { elements: Record; tag: "struct"; }; ``` A data structure indicating the locations of contract references in a Compact struct. ## Properties[​](#properties "Direct link to Properties") ### elements[​](#elements "Direct link to elements") ``` elements: Record; ``` A data structure indicating the locations of contract references in the elements of a Compact struct. The keys of the record correspond to fields of the Compact struct that contain contract references. We use the keys of the record to explore the elements of the corresponding CompactStruct. *** ### tag[​](#tag "Direct link to tag") ``` tag: "struct"; ``` --- # SparseCompactType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactType # Type Alias: SparseCompactType ``` type SparseCompactType = | SparseCompactVector | SparseCompactStruct | SparseCompactContractAddress; ``` A data structure indicating the locations of contract references in a Compact struct, vector, or (the terminating case) a contract address. --- # SparseCompactValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactValue # Type Alias: SparseCompactValue ``` type SparseCompactValue = { descriptor: CompactType; sparseType: SparseCompactType; tag: "compactValue"; }; ``` A data structure indicating the locations of all contract references in a Compact value. ## Properties[​](#properties "Direct link to Properties") ### descriptor[​](#descriptor "Direct link to descriptor") ``` descriptor: CompactType; ``` A descriptor that can be used to convert an [AlignedValue](/api-reference/compact-runtime/type-aliases/AlignedValue.md) into a TypeScript representation of the same value. This descriptor will only ever decode `struct`s or `Vector`s that contain contract addresses. *** ### sparseType[​](#sparsetype "Direct link to sparseType") ``` sparseType: SparseCompactType; ``` A data structure indicating how to navigate to the contract addresses present in the output of the above `descriptor`. *** ### tag[​](#tag "Direct link to tag") ``` tag: "compactValue"; ``` --- # SparseCompactVector > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SparseCompactVector # Type Alias: SparseCompactVector ``` type SparseCompactVector = { sparseType: SparseCompactType; tag: "vector"; }; ``` A data structure indicating the locations of contract references in a Compact vector. ## Properties[​](#properties "Direct link to Properties") ### sparseType[​](#sparsetype "Direct link to sparseType") ``` sparseType: SparseCompactType; ``` A data structure indicating the locations of contract references in the elements of a Compact vector. *** ### tag[​](#tag "Direct link to tag") ``` tag: "vector"; ``` --- # TokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / TokenType # Type Alias: TokenType ``` type TokenType = | UnshieldedTokenType | ShieldedTokenType | DustTokenType; ``` A token type (or color), as a hex-encoded 32-byte string, shielded, unshielded, or Dust --- # Transcript > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Transcript # Type Alias: Transcript\ ``` type Transcript = { effects: Effects; gas: RunningCost; program: Op[]; }; ``` A transcript of operations, to be recorded in a transaction ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### R[​](#r "Direct link to R") `R` ## Properties[​](#properties "Direct link to Properties") ### effects[​](#effects "Direct link to effects") ``` effects: Effects; ``` The effects of the transcript, which are checked before execution, and must match those constructed by [program](#program) *** ### gas[​](#gas "Direct link to gas") ``` gas: RunningCost; ``` The execution budget for this transcript, which [program](#program) must not exceed *** ### program[​](#program "Direct link to program") ``` program: Op[]; ``` The sequence of operations that this transcript captured --- # UnshieldedTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / UnshieldedTokenType # Type Alias: UnshieldedTokenType ``` type UnshieldedTokenType = { raw: RawTokenType; tag: "unshielded"; }; ``` Unshielded token type (or color), as a hex-encoded 32-byte string ## Properties[​](#properties "Direct link to Properties") ### raw[​](#raw "Direct link to raw") ``` raw: RawTokenType; ``` *** ### tag[​](#tag "Direct link to tag") ``` tag: "unshielded"; ``` --- # UserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / UserAddress # Type Alias: UserAddress ``` type UserAddress = string; ``` A user public key address, as a hex-encoded 32-byte string --- # Value > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Value # Type Alias: Value ``` type Value = Uint8Array[]; ``` An onchain data value, in field-aligned binary format. --- # BooleanDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / BooleanDescriptor # Variable: BooleanDescriptor ``` const BooleanDescriptor: CompactTypeBoolean; ``` --- # Bytes32Descriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / Bytes32Descriptor # Variable: Bytes32Descriptor ``` const Bytes32Descriptor: CompactTypeBytes; ``` The following are type descriptors used to implement createCoinCommitment. They are not intended for direct consumption. --- # CoinInfoDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CoinInfoDescriptor # Variable: CoinInfoDescriptor ``` const CoinInfoDescriptor: { alignment: Alignment; fromValue: { color: Uint8Array; nonce: Uint8Array; value: bigint; }; toValue: Value; }; ``` ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): { color: Uint8Array; nonce: Uint8Array; value: bigint; }; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") ``` { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` ##### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ##### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ##### value[​](#value-1 "Direct link to value") ``` value: bigint; ``` ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-2 "Direct link to value") ###### color[​](#color-1 "Direct link to color") `Uint8Array` ###### nonce[​](#nonce-1 "Direct link to nonce") `Uint8Array` ###### value[​](#value-3 "Direct link to value") `bigint` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # CoinRecipientDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.9.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CoinRecipientDescriptor # Variable: CoinRecipientDescriptor ``` const CoinRecipientDescriptor: { alignment: Alignment; fromValue: { is_left: boolean; left: { bytes: Uint8Array; }; right: { bytes: Uint8Array; }; }; toValue: Value; }; ``` ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): { is_left: boolean; left: { bytes: Uint8Array; }; right: { bytes: Uint8Array; }; }; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") ``` { is_left: boolean; left: { bytes: Uint8Array; }; right: { bytes: Uint8Array; }; } ``` ##### is\_left[​](#is_left "Direct link to is_left") ``` is_left: boolean; ``` ##### left[​](#left "Direct link to left") ``` left: { bytes: Uint8Array; }; ``` ###### left.bytes[​](#leftbytes "Direct link to left.bytes") ``` bytes: Uint8Array; ``` ##### right[​](#right "Direct link to right") ``` right: { bytes: Uint8Array; }; ``` ###### right.bytes[​](#rightbytes "Direct link to right.bytes") ``` bytes: Uint8Array; ``` ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") ###### is\_left[​](#is_left-1 "Direct link to is_left") `boolean` ###### left[​](#left-1 "Direct link to left") { `bytes`: `Uint8Array`; } ###### left.bytes[​](#leftbytes-1 "Direct link to left.bytes") `Uint8Array` ###### right[​](#right-1 "Direct link to right") { `bytes`: `Uint8Array`; } ###### right.bytes[​](#rightbytes-1 "Direct link to right.bytes") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # CompactTypeBoolean > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeBoolean # Variable: CompactTypeBoolean ``` const CompactTypeBoolean: CompactType; ``` Runtime type of the builtin `Boolean` type --- # CompactTypeField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeField # Variable: CompactTypeField ``` const CompactTypeField: CompactType; ``` Runtime type of the builtin `Field` type --- # CompactTypeJubjubPoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeJubjubPoint # Variable: CompactTypeJubjubPoint ``` const CompactTypeJubjubPoint: CompactType; ``` Runtime type of [JubjubPoint](/api-reference/compact-runtime/interfaces/JubjubPoint.md) --- # CompactTypeMerkleTreeDigest > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeMerkleTreeDigest # Variable: CompactTypeMerkleTreeDigest ``` const CompactTypeMerkleTreeDigest: CompactType; ``` Runtime type of [MerkleTreeDigest](/api-reference/compact-runtime/interfaces/MerkleTreeDigest.md) --- # CompactTypeMerkleTreePathEntry > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeMerkleTreePathEntry # Variable: CompactTypeMerkleTreePathEntry ``` const CompactTypeMerkleTreePathEntry: CompactType; ``` Runtime type of [MerkleTreePathEntry](/api-reference/compact-runtime/interfaces/MerkleTreePathEntry.md) --- # CompactTypeNativePoint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.14.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeNativePoint # Variable: CompactTypeNativePoint ``` const CompactTypeNativePoint: CompactType; ``` Runtime type of [NativePoint](/api-reference/compact-runtime/interfaces/NativePoint.md) --- # CompactTypeOpaqueString > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeOpaqueString # Variable: CompactTypeOpaqueString ``` const CompactTypeOpaqueString: CompactType; ``` Runtime type of `Opaque["string"]` --- # CompactTypeOpaqueUint8Array > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeOpaqueUint8Array # Variable: CompactTypeOpaqueUint8Array ``` const CompactTypeOpaqueUint8Array: CompactType; ``` Runtime type of `Opaque["Uint8Array"]` --- # CompactTypeSecp256k1Base > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeSecp256k1Base # Variable: CompactTypeSecp256k1Base ``` const CompactTypeSecp256k1Base: CompactType; ``` Runtime type of the builtin `Secp256k1Base` type --- # CompactTypeSecp256k1Point > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeSecp256k1Point # Variable: CompactTypeSecp256k1Point ``` const CompactTypeSecp256k1Point: CompactType; ``` Runtime type of [Secp256k1Point](/api-reference/compact-runtime/interfaces/Secp256k1Point.md) --- # CompactTypeSecp256k1Scalar > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CompactTypeSecp256k1Scalar # Variable: CompactTypeSecp256k1Scalar ``` const CompactTypeSecp256k1Scalar: CompactType; ``` Runtime type of the builtin `Secp256k1Scalar` type --- # CONTRACT\_ADDRESS\_BYTE\_LENGTH > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / CONTRACT\_ADDRESS\_BYTE\_LENGTH # Variable: CONTRACT\_ADDRESS\_BYTE\_LENGTH ``` const CONTRACT_ADDRESS_BYTE_LENGTH: 32 = 32; ``` The expected length (in bytes) of a contract address. --- # ContractAddressDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ContractAddressDescriptor # Variable: ContractAddressDescriptor ``` const ContractAddressDescriptor: { alignment: Alignment; fromValue: { bytes: Uint8Array; }; toValue: Value; }; ``` ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): { bytes: Uint8Array; }; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") ``` { bytes: Uint8Array; } ``` ##### bytes[​](#bytes "Direct link to bytes") ``` bytes: Uint8Array; ``` ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") ###### bytes[​](#bytes-1 "Direct link to bytes") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # DUMMY\_ADDRESS > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / DUMMY\_ADDRESS # Variable: ~~DUMMY\_ADDRESS~~ ``` const DUMMY_ADDRESS: string; ``` A valid placeholder contract address ## Deprecated[​](#deprecated "Direct link to Deprecated") Cannot handle NetworkIds, use [dummyContractAddress](/api-reference/compact-runtime/functions/dummyContractAddress.md) instead. --- # FIELD\_MODULUS > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / FIELD\_MODULUS # Variable: FIELD\_MODULUS ``` const FIELD_MODULUS: bigint; ``` The order of Compact's native `Field` type --- # HEX\_REGEX\_NO\_PREFIX > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / HEX\_REGEX\_NO\_PREFIX # Variable: HEX\_REGEX\_NO\_PREFIX ``` const HEX_REGEX_NO_PREFIX: RegExp; ``` Regex matching hex strings of even length. --- # JUBJUB\_SCALAR\_MODULUS > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / JUBJUB\_SCALAR\_MODULUS # Variable: JUBJUB\_SCALAR\_MODULUS ``` const JUBJUB_SCALAR_MODULUS: bigint = 0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7n; ``` The order of the JubJub scalar field --- # MAX\_FIELD > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MAX\_FIELD # Variable: MAX\_FIELD ``` const MAX_FIELD: bigint; ``` The maximum value representable in Compact's `Field` type One less than the prime modulus of the proof system's scalar field. --- # MAX\_JUBJUB\_SCALAR > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MAX\_JUBJUB\_SCALAR # Variable: MAX\_JUBJUB\_SCALAR ``` const MAX_JUBJUB_SCALAR: bigint; ``` The maximum value of a `JubjubScalar` foreign field value --- # MAX\_SECP256K1\_BASE > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MAX\_SECP256K1\_BASE # Variable: MAX\_SECP256K1\_BASE ``` const MAX_SECP256K1_BASE: bigint; ``` The maximum value of a `Secp256k1Base` foreign field value --- # MAX\_SECP256K1\_SCALAR > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MAX\_SECP256K1\_SCALAR # Variable: MAX\_SECP256K1\_SCALAR ``` const MAX_SECP256K1_SCALAR: bigint; ``` The maximum value of a `Secp256k1Scalar` foreign field value --- # MaxUint8Descriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / MaxUint8Descriptor # Variable: MaxUint8Descriptor ``` const MaxUint8Descriptor: CompactTypeUnsignedInteger; ``` --- # sampleJubjubSchnorrSk > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / sampleJubjubSchnorrSk # Variable: sampleJubjubSchnorrSk() ``` const sampleJubjubSchnorrSk: () => bigint = jubjubSampleScalar; ``` Alias for [jubjubSampleScalar](/api-reference/compact-runtime/functions/jubjubSampleScalar.md). Samples a random JubJub Schnorr signing key. Samples a random JubJub scalar. The returned value is in the range \[0, JUBJUB\_SCALAR\_MODULUS). ## Returns[​](#returns "Direct link to Returns") `bigint` --- # SECP256K1\_BASE\_MODULUS > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SECP256K1\_BASE\_MODULUS # Variable: SECP256K1\_BASE\_MODULUS ``` const SECP256K1_BASE_MODULUS: bigint; ``` The order of the secp256k1 base field --- # SECP256K1\_SCALAR\_MODULUS > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / SECP256K1\_SCALAR\_MODULUS # Variable: SECP256K1\_SCALAR\_MODULUS ``` const SECP256K1_SCALAR_MODULUS: bigint = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n; ``` The order of the secp256k1 scalar field --- # ShieldedCoinInfoDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ShieldedCoinInfoDescriptor # Variable: ShieldedCoinInfoDescriptor ``` const ShieldedCoinInfoDescriptor: { alignment: Alignment; fromValue: { color: Uint8Array; nonce: Uint8Array; value: bigint; }; toValue: Value; }; ``` ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): { color: Uint8Array; nonce: Uint8Array; value: bigint; }; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") ``` { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` ##### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ##### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ##### value[​](#value-1 "Direct link to value") ``` value: bigint; ``` ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-2 "Direct link to value") ###### color[​](#color-1 "Direct link to color") `Uint8Array` ###### nonce[​](#nonce-1 "Direct link to nonce") `Uint8Array` ###### value[​](#value-3 "Direct link to value") `bigint` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # ShieldedCoinRecipientDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ShieldedCoinRecipientDescriptor # Variable: ShieldedCoinRecipientDescriptor ``` const ShieldedCoinRecipientDescriptor: { alignment: Alignment; fromValue: { is_left: boolean; left: { bytes: Uint8Array; }; right: { bytes: Uint8Array; }; }; toValue: Value; }; ``` ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): { is_left: boolean; left: { bytes: Uint8Array; }; right: { bytes: Uint8Array; }; }; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") ``` { is_left: boolean; left: { bytes: Uint8Array; }; right: { bytes: Uint8Array; }; } ``` ##### is\_left[​](#is_left "Direct link to is_left") ``` is_left: boolean; ``` ##### left[​](#left "Direct link to left") ``` left: { bytes: Uint8Array; }; ``` ###### left.bytes[​](#leftbytes "Direct link to left.bytes") ``` bytes: Uint8Array; ``` ##### right[​](#right "Direct link to right") ``` right: { bytes: Uint8Array; }; ``` ###### right.bytes[​](#rightbytes "Direct link to right.bytes") ``` bytes: Uint8Array; ``` ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") ###### is\_left[​](#is_left-1 "Direct link to is_left") `boolean` ###### left[​](#left-1 "Direct link to left") { `bytes`: `Uint8Array`; } ###### left.bytes[​](#leftbytes-1 "Direct link to left.bytes") `Uint8Array` ###### right[​](#right-1 "Direct link to right") { `bytes`: `Uint8Array`; } ###### right.bytes[​](#rightbytes-1 "Direct link to right.bytes") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- # versionString > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.19.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / versionString # Variable: versionString ``` const versionString: string = "0.19.0"; ``` --- # ZswapCoinPublicKeyDescriptor > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/compact-runtime v0.16.0**](/api-reference/compact-runtime.md) *** [@midnight-ntwrk/compact-runtime](/api-reference/compact-runtime/globals.md) / ZswapCoinPublicKeyDescriptor # Variable: ZswapCoinPublicKeyDescriptor ``` const ZswapCoinPublicKeyDescriptor: { alignment: Alignment; fromValue: { bytes: Uint8Array; }; toValue: Value; }; ``` ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### alignment()[​](#alignment "Direct link to alignment()") ``` alignment(): Alignment; ``` #### Returns[​](#returns "Direct link to Returns") [`Alignment`](/api-reference/compact-runtime/type-aliases/Alignment.md) ### fromValue()[​](#fromvalue "Direct link to fromValue()") ``` fromValue(value): { bytes: Uint8Array; }; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) #### Returns[​](#returns-1 "Direct link to Returns") ``` { bytes: Uint8Array; } ``` ##### bytes[​](#bytes "Direct link to bytes") ``` bytes: Uint8Array; ``` ### toValue()[​](#tovalue "Direct link to toValue()") ``` toValue(value): Value; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") ###### bytes[​](#bytes-1 "Direct link to bytes") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") [`Value`](/api-reference/compact-runtime/type-aliases/Value.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight DApp connector API **@midnight-ntwrk/dapp-connector-api v4.0.1** *** This API provides a comprehensive interface for connecting Decentralized Applications (DApps) to Midnight wallets. It defines the methods, data structures, and operations that enable DApps to request wallet information, create transactions, and interact with the Midnight Network. ## Installation[​](#installation "Direct link to Installation") The Midnight DApp connector API is available as an NPM package with the namespace `@midnight-ntwrk/dapp-connector-api`. It can be installed using any node package manager, such as Yarn. To install the package using Yarn, execute the following command: ``` yarn add @midnight-ntwrk/dapp-connector-api ``` ## Package usage[​](#package-usage "Direct link to Package usage") The package provides the type declarations that are documented in the [documentation](/api-reference/dapp-connector/type-aliases/InitialAPI.md) of this package. The DApp connector API should be exposed through the global variable as follows: ``` window.midnight.{someWalletIdString} ``` In this way multiple wallets can inject their API without causing conflicts, and a DApp can select/ask the user to which wallet connection should be established. ## Initial API data and methods[​](#initial-api-data-and-methods "Direct link to Initial API data and methods") | Name | Description | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **name** | Wallet name, expected to be displayed to the user. | | **icon** | Wallet icon, as an URL, either reference to a hosted resource, or a base64 encoded data URL. | | **apiVersion** | Version of the API implemented by this instance of the API. For example, wallet implementing version 3.1.5 provides apiVersion with value '3.1.5'. This value lets DApps to differentiate between different versions of the API and implement appropriate logic for each version or not use some versions at all. | | **connect** | Connect to wallet, passing the desired network ID as a parameter. Upon successful connection returns a promise with [ConnectedAPI](/api-reference/dapp-connector/type-aliases/ConnectedAPI.md). | ## Connect to a wallet[​](#connect-to-a-wallet "Direct link to Connect to a wallet") A DApp needs to select the wallet it wants to connect to and call the `connect(networkId)` method, then wait for the returned promise. The promise may resolve with a significant delay, as most wallets might want to display a dialog asking the user for authorization. ``` try { const desiredNetworkId = 'mainnet' const api = await window.midnight.{selectedWalletId}.connect('mainnet'); // api is available here } catch (error) { console.log('an error occurred', error); } ``` ## Retrieve wallet details before connection[​](#retrieve-wallet-details-before-connection "Direct link to Retrieve wallet details before connection") Before establishing a connection, you can access basic wallet information such as the wallet name, icon, and API version. ### Name and icon[​](#name-and-icon "Direct link to Name and icon") To get the name and icon of the wallet, use the `name` and `icon` properties in the implemented DApp connector API: ``` const name = window.midnight.{walletName}.name; const iconURL = window.midnight.{walletName}.icon; console.log('Wallet name', name); console.log('Wallet icon URL', iconURL); ``` Both fields are meant to be displayed to the user to help with wallet selection. To prevent XSS vulnerabilities, the DApp must ensure proper escaping. For example, display the icon only through an `img` tag and display the name using a `Text` node. ### Get API version[​](#get-api-version "Direct link to Get API version") To get the API version, use the `apiVersion` property as follows: ``` const apiVersion = window.midnight.{walletName}.apiVersion; console.log('API version', apiVersion); ``` The DApp needs to verify whether the version reported by the wallet matches the DApp's expectations. Use a semver check to validate compatibility. ## Query wallet state and initiate transactions[​](#query-wallet-state-and-initiate-transactions "Direct link to Query wallet state and initiate transactions") Once connected, the DApp can issue many different requests to the wallet as defined by the [ConnectedAPI](/api-reference/dapp-connector/type-aliases/ConnectedAPI.md) type. The most important operations are: * Query the wallet for information, like balances or addresses. * Query the wallet for configuration, so that the DApp can connect to the same instance of Indexer, Midnight Node, or Proof Server. * Ask the wallet to make a transfer, balance a transaction, make an unbalanced intent (for example, for a swap), or sign data. * Ask the wallet to submit a transaction. ### Get the configuration[​](#get-the-configuration "Direct link to Get the configuration") Midnight wallet users can configure the node, indexer, and proving server URIs in the wallet settings. DApps are expected to follow these configurations to respect user preferences. This is important from a privacy standpoint. The returned object has the following properties: | Name | Description | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | **indexerUri** | Indexer HTTP URI | | **indexerWsUri** | Indexer WebSocket URI | | **proverServerUri** | Prover Server URI | | **substrateNodeUri** | Substrate URI | | **networkId** | Network ID connected to - present here mostly for completeness and to allow the DApp to validate it is connected to the network it wishes to. | To get the service URI config, use the API as follows: ``` try { const connected = await window.midnight.{selectedWalletId}.connect(); const serviceUriConfig = await connected.getConfiguration(); console.log('serviceUriConfig', serviceUriConfig); } catch (error) { console.log('an error occurred', error); } ``` ### Read wallet information[​](#read-wallet-information "Direct link to Read wallet information") Several methods are available for querying wallet state. The most important ones are `getShieldedBalances`, `getUnshieldedBalances`, `getDustBalance`, `getShieldedAddresses`, `getUnshieldedAddress`, and `getDustAddress`. Keys and addresses are provided in Bech32m format. Shielded and unshielded balances return a record whose keys are token types. ``` try { const connected = await window.midnight.{selectedWalletId}.connect(); const addressesAndBalances = { shieldedBalances: await connected.getShieldedBalances(), unshieldedBalances: await connected.getUnshieldedBalances(), dustBalance: await connected.getDustBalance(), shieldedAddresses: await connected.getShieldedAddresses(), unshieldedAddress: await connected.getUnshieldedAddress(), dustAddress: await connected.getDustAddress(), } console.log('addressesAndBalances', addressesAndBalances); } catch (error) { console.log('an error occurred', error); } ``` ### Initiate a payment[​](#initiate-a-payment "Direct link to Initiate a payment") If a DApp needs to initiate a payment, `makeTransfer` is the right method to use. It takes an array of outputs that need to be present in the final transaction. For more details, see the [InitActions type documentation](/api-reference/type-aliases/InitActions.md). ``` import {nativeToken} from '@midnight-ntwrk/ledger-v8' try { const connected = await window.midnight.{selectedWalletId}.connect(); const transaction = await connected.makeTransfer([{ kind: 'unshielded', tokenType: nativeToken().raw, value: 10n**6n, recipient: 'mn_addr1abcdef.....' }]); } catch (error) { console.log('an error occurred', error); } ``` ### Balance a transaction[​](#balance-a-transaction "Direct link to Balance a transaction") To balance a transaction, begin by creating a transaction in your DApp. For transaction creation, see the [Wallet Developer Guide](/sdks/official/wallet-developer-guide.md). This method is particularly useful for DApps calling contracts. It's the best way to use native tokens in a DApp or make the user pay the fees for a contract call. Depending on the use case and state of the transaction to be balanced, there are two methods available: `balanceSealedTransaction` and `balanceUnsealedTransaction`. They indicate different methods the wallet will use to deserialize the transaction and try to balance it. A transaction that is the result of a contract call will most likely need a call to `balanceUnsealedTransaction`. Completing a swap (for example, initiated by a `makeIntent` call) will require a call to `balanceSealedTransaction`. ``` try { // assuming we have a transaction at hand here const transaction; const result = await connected.balanceUnsealedTransaction(transaction); const resultTransaction = result.tx; } catch (error) { console.log('an error occurred', error); } ``` ### Submit a transaction[​](#submit-a-transaction "Direct link to Submit a transaction") With the balanced and proven transaction from above, you can now submit it. ``` try { const submittedTransaction = await connected.submitTransaction(resultTransaction); } catch (error) { console.log('an error occurred', error); } ``` ## Examples[​](#examples "Direct link to Examples") The following examples demonstrate common usage patterns for the DApp connector API. ### Connect[​](#connect "Direct link to Connect") This example shows how to connect to a compatible wallet on a specific network. It filters wallets by API version, prompts the user to select one, and establishes a connection. ``` import { NetworkId } from '@midnight-ntwrk/midnight-js-network-id'; declare function semverMatch(version, expectedRange); declare function askUserToSelect(wallets: InitialAPI[]): Promise; async function connect(): Promise { const networkId = NetworkId('preprod'); const compatibleWallets = Object.values(window.midnight ?? {}) .filter((wallet) => semverMatch(wallet.apiVersion, '^1.0')); const selectedWallet = await askUserToSelect(compatibleWallets); const connectedWallet = await selectedWallet.connect(networkId); const connectionStatus = await connectedWallet.getConnectionStatus(); assert(connectionStatus.networkId === networkId); return connectedWallet; } ``` ### Initiate a Night payment to an address[​](#initiate-a-night-payment-to-an-address "Direct link to Initiate a Night payment to an address") This example demonstrates how to initiate a transfer of 10 Night tokens to a specific unshielded address. The transaction is created using `makeTransfer` and then submitted to the network. ``` import { nativeToken } from '@midnight-ntwrk/ledger-v8'; const connectedWallet = await connect(); const tx = await connectedWallet.makeTransfer([{ kind: "unshielded", type: nativeToken().raw, value: 10_000_000, //10 Night recipient: "mn_addr1asujt0dayj4pelgq97wv75hjhscqv9epmzzpapkf8sy8c87jhh9s6e0fs3" }]); await connectedWallet.submitTransaction(tx); ``` ### Initiate and complement a swap of Night into a shielded token[​](#initiate-and-complement-a-swap-of-night-into-a-shielded-token "Direct link to Initiate and complement a swap of Night into a shielded token") This example shows a two-party swap where Party #1 creates an unbalanced transaction offering 10 Night tokens, and Party #2 completes it by providing 50,000 Foo tokens. The transaction is balanced and submitted by Party #2. ``` // Party #1 import { nativeToken } from '@midnight-ntwrk/ledger-v8'; declare function getFooTokenType(): TokenType; const connectedWallet = await connect(); const shieldedAddress = (await connectedWallet.getShieldedAddresses()).shieldedAddress; // This call will create a transaction with inputs and outputs structured so that there is: // - surplus of 10 Night (inputs cover 10 Night, there might be some change output of Night created) // - shortage of 50_000 Foo tokens (there is an output for 50_000 Foo tokens, but no inputs) const tx = await connectedWallet.makeIntent([{ kind: "unshielded", type: nativeToken().raw, value: 10_000_000, //10 Night }], [{ kind: "shielded", type: getFooTokenType(), value: 50_000, recipient: shieldedAddress }]); // Here, the `tx` can be submitted to some service, so that it becomes available to the other party // Party #2 const tx = await fetchTransactionToMatch(); const connectedWallet = await connect(); // Then party #2 provides the 50_000 Foo tokens and creates self outputs for the surplus of 10 Night const balancedTx = await connectedWallet.balanceSealedTransaction(tx); await connectedWallet.submitTransaction(balancedTx); ``` ### Delegate proving[​](#delegate-proving "Direct link to Delegate proving") This example demonstrates how to delegate Zero Knowledge (ZK) proof generation to the wallet's proving provider. It prepares an unproven transaction, generates the proof, balances the transaction, and submits it. ``` import { FetchZkConfigProvider } from '@midnight-ntwrk/midnight-js-fetch-zk-config-provider'; import { Transaction } from '@midnight-ntwrk/ledger-v8'; const keyMaterialProvider = new FetchZkConfigProvider('https://example.com'); const connectedAPI = await connect(); const provingProvider = connectedAPI.getProvingProvider(keyMaterialProvider); // Let's prepare the transaction and their inputs const costModel = await fetchCostModel(); // For example, from Indexer, using `Block.ledgerParameters`: https://github.com/midnightntwrk/midnight-indexer/blob/main/indexer-api/graphql/schema-v3.graphql#L36 const unprovedTx = prepareUnprovenTransaction(costModel); // For example, make a contract call // Now the proving itself: const provenTx = await unprovenTx.prove(provingProvider, costModel); // Now the transaction can be, for instance, balanced (to pay fees) and submitted: const finalTx = await connectedAPI.balanceUnsealedTransaction(provenTx); await connectedAPI.submitTransaction(finalTx); ``` ## Reference[​](#reference "Direct link to Reference") For the complete technical specification of the DApp Connector API, see the [DApp Connector API Specification](https://github.com/midnightntwrk/midnight-dapp-connector-api/blob/main/docs/api/_media/SPECIFICATION.md) on GitHub. --- # globals > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** # @midnight-ntwrk/dapp-connector-api v4.0.1 ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [APIError](/api-reference/dapp-connector/type-aliases/APIError.md) * [Configuration](/api-reference/dapp-connector/type-aliases/Configuration.md) * [ConnectedAPI](/api-reference/dapp-connector/type-aliases/ConnectedAPI.md) * [ConnectionStatus](/api-reference/dapp-connector/type-aliases/ConnectionStatus.md) * [DesiredInput](/api-reference/dapp-connector/type-aliases/DesiredInput.md) * [DesiredOutput](/api-reference/dapp-connector/type-aliases/DesiredOutput.md) * [ErrorCode](/api-reference/dapp-connector/type-aliases/ErrorCode.md) * [ExecutionStatus](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md) * [HintUsage](/api-reference/dapp-connector/type-aliases/HintUsage.md) * [HistoryEntry](/api-reference/dapp-connector/type-aliases/HistoryEntry.md) * [InitialAPI](/api-reference/dapp-connector/type-aliases/InitialAPI.md) * [KeyMaterialProvider](/api-reference/dapp-connector/type-aliases/KeyMaterialProvider.md) * [ProvingProvider](/api-reference/dapp-connector/type-aliases/ProvingProvider.md) * [Signature](/api-reference/dapp-connector/type-aliases/Signature.md) * [SignDataOptions](/api-reference/dapp-connector/type-aliases/SignDataOptions.md) * [TokenType](/api-reference/dapp-connector/type-aliases/TokenType.md) * [TxStatus](/api-reference/dapp-connector/type-aliases/TxStatus.md) * [WalletConnectedAPI](/api-reference/dapp-connector/type-aliases/WalletConnectedAPI.md) ## Variables[​](#variables "Direct link to Variables") * [ErrorCodes](/api-reference/dapp-connector/variables/ErrorCodes.md) --- # APIError > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / APIError # Type Alias: APIError > **APIError** = `Error` & `object` Declaration of the error type thrown by the DApp Connector. It is not a class extending the base `Error` type, because it would make it difficult to implement in a way where `instanceof APIError` would work. Instead a check like `error.type === 'DAppConnectorAPIError'` should be used. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### code[​](#code "Direct link to code") > **code**: [`ErrorCode`](/api-reference/dapp-connector/type-aliases/ErrorCode.md) The code of the error that's thrown ### reason[​](#reason "Direct link to reason") > **reason**: `string` The reason the error is thrown ### type[​](#type "Direct link to type") > **type**: `"DAppConnectorAPIError"` indication it is a DApp Connector Error --- # Configuration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / Configuration # Type Alias: Configuration > **Configuration** = `object` ## Properties[​](#properties "Direct link to Properties") ### indexerUri[​](#indexeruri "Direct link to indexerUri") > **indexerUri**: `string` Indexer URI *** ### indexerWsUri[​](#indexerwsuri "Direct link to indexerWsUri") > **indexerWsUri**: `string` Indexer WebSocket URI *** ### networkId[​](#networkid "Direct link to networkId") > **networkId**: `string` Network id connected to - present here mostly for completness and to allow dapp validate it is connected to the network it wishes to *** ### ~~proverServerUri?~~[​](#proverserveruri "Direct link to proverserveruri") > `optional` **proverServerUri**: `string` Prover Server URI, likely to not be present, as different proving modalities emerge #### Deprecated[​](#deprecated "Direct link to Deprecated") Use `getProvingProvider` instead *** ### substrateNodeUri[​](#substratenodeuri "Direct link to substrateNodeUri") > **substrateNodeUri**: `string` Substrate URI --- # ConnectedAPI > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / ConnectedAPI # Type Alias: ConnectedAPI > **ConnectedAPI** = [`WalletConnectedAPI`](/api-reference/dapp-connector/type-aliases/WalletConnectedAPI.md) & [`HintUsage`](/api-reference/dapp-connector/type-aliases/HintUsage.md) Connected API. It allows DApp to perform a range ofactions on the wallet after it is connected. Specifically the operations provided are: * interaction with wallet - [WalletConnectedAPI](/api-reference/dapp-connector/type-aliases/WalletConnectedAPI.md) covers those * hint usage of methods to the wallet (to help with permissions management) --- # ConnectionStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / ConnectionStatus # Type Alias: ConnectionStatus > **ConnectionStatus** = { `networkId`: `string`; `status`: `"connected"`; } | { `status`: `"disconnected"`; } Status of an existing connection to wallet It either indicates that the connection is established to a specific network id, or that the connection is lost ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") { `networkId`: `string`; `status`: `"connected"`; } ### networkId[​](#networkid "Direct link to networkId") > **networkId**: `string` ### status[​](#status "Direct link to status") > **status**: `"connected"` Connection is established to following network id { `status`: `"disconnected"`; } ### status[​](#status-1 "Direct link to status") > **status**: `"disconnected"` Connection is lost --- # DesiredInput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / DesiredInput # Type Alias: DesiredInput > **DesiredInput** = `object` Desired input from an intent. It specifies the type of the input and the amount to provide. ## Properties[​](#properties "Direct link to Properties") ### kind[​](#kind "Direct link to kind") > **kind**: `"shielded"` | `"unshielded"` *** ### type[​](#type "Direct link to type") > **type**: [`TokenType`](/api-reference/dapp-connector/type-aliases/TokenType.md) *** ### value[​](#value "Direct link to value") > **value**: `bigint` --- # DesiredOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / DesiredOutput # Type Alias: DesiredOutput > **DesiredOutput** = `object` Desired output from a transaction or intent. It specifies the type of the output, the amount and the recipient. Recipient needs to be a properly formatted Bech32m address matching the kind of the token and network id the wallet is connected to. ## Properties[​](#properties "Direct link to Properties") ### kind[​](#kind "Direct link to kind") > **kind**: `"shielded"` | `"unshielded"` *** ### recipient[​](#recipient "Direct link to recipient") > **recipient**: `string` *** ### type[​](#type "Direct link to type") > **type**: [`TokenType`](/api-reference/dapp-connector/type-aliases/TokenType.md) *** ### value[​](#value "Direct link to value") > **value**: `bigint` --- # ErrorCode > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / ErrorCode # Type Alias: ErrorCode > **ErrorCode** = *typeof* [`ErrorCodes`](/api-reference/dapp-connector/variables/ErrorCodes.md)\[keyof *typeof* [`ErrorCodes`](/api-reference/dapp-connector/variables/ErrorCodes.md)] All possible error codes gathered in a single union type. They are defined in [ErrorCodes](/api-reference/dapp-connector/variables/ErrorCodes.md). --- # ExecutionStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / ExecutionStatus # Type Alias: ExecutionStatus > **ExecutionStatus** = `Record`<`number`, `"Success"` | `"Failure"`> Execution status of a transaction. It indicates which sections of a transaction were executed successfully or not. --- # HintUsage > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / HintUsage # Type Alias: HintUsage > **HintUsage** = `object` ## Methods[​](#methods "Direct link to Methods") ### hintUsage()[​](#hintusage "Direct link to hintUsage()") > **hintUsage**(`methodNames`): `Promise`<`void`> Hint usage of methods to the wallet. DApps should use this method to hint to the wallet what methods are expected to be used in a certain context (be it a whole session, single view, or a user flow - it is up to DApp). The wallet can use these calls as an opportunity to ask user for permissions and in such case - resolve the promise only after the user has granted the permissions. #### Parameters[​](#parameters "Direct link to Parameters") ##### methodNames[​](#methodnames "Direct link to methodNames") keyof [`WalletConnectedAPI`](/api-reference/dapp-connector/type-aliases/WalletConnectedAPI.md)\[] #### Returns[​](#returns "Direct link to Returns") `Promise`<`void`> --- # HistoryEntry > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / HistoryEntry # Type Alias: HistoryEntry > **HistoryEntry** = `object` Minimal information about a transaction relevant for the wallet. ## Properties[​](#properties "Direct link to Properties") ### txHash[​](#txhash "Direct link to txHash") > **txHash**: `string` Hex-encoded hash of transaction *** ### txStatus[​](#txstatus "Direct link to txStatus") > **txStatus**: [`TxStatus`](/api-reference/dapp-connector/type-aliases/TxStatus.md) --- # InitialAPI > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / InitialAPI # Type Alias: InitialAPI > **InitialAPI** = `object` Initial API for a wallet providing a DApp Connector API - it contains the information and methods allowing DApp to chose and initiate a connection to the wallet. Wallets inject their Initial API under the `window.midnight` object. A single wallet can inject multiple instances of the Initial API, e.g. when supporting multiple versions. Together with UUID under which the initial API is installed, the contents are compatible with the [draft of CAIP-372](https://github.com/ChainAgnostic/CAIPs/pull/372/files). ## Properties[​](#properties "Direct link to Properties") ### apiVersion[​](#apiversion "Direct link to apiVersion") > **apiVersion**: `string` Version of the API implemented by this instance of the API, string containing a version of the API package @midnight-ntwrk/dapp-connector-api that was used in implementation E.g. wallet implementing version 3.1.5 provides apiVersion with value '3.1.5' This value lets DApps to differentiate between different versions of the API and implement appropriate logic for each version or not use some versions at all *** ### connect()[​](#connect "Direct link to connect()") > **connect**: (`networkId`) => `Promise`<[`ConnectedAPI`](/api-reference/dapp-connector/type-aliases/ConnectedAPI.md)> Connect to wallet, hinting desired network id; Use 'mainnet' for mainnet. #### Parameters[​](#parameters "Direct link to Parameters") ##### networkId[​](#networkid "Direct link to networkId") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<[`ConnectedAPI`](/api-reference/dapp-connector/type-aliases/ConnectedAPI.md)> *** ### icon[​](#icon "Direct link to icon") > **icon**: `string` Wallet icon, as an URL, either reference to a hosted resource, or a base64 encoded data URL. It is expected to be displayed to the user. Because of this, DApps need to display the icon in a secure fashion to prevent XSS. For example, displaying the icon using an `img` tag. *** ### name[​](#name "Direct link to name") > **name**: `string` Wallet name, expected to be displayed to the user. As such, DApps need to sanitize the name to prevent XSS when displaying it to the user. An example of sanitization is displaying the name using a text node. *** ### rdns[​](#rdns "Direct link to rdns") > **rdns**: `string` Wallet identifier, in a reverse DNS notation (e.g. `com.example.wallet`). Wallets should keep this identifier stable throughout the lifecycle of the product. DApps can use this property to identify the wallet, but should be prepared to handle values that are unknown, invalid, or potentially misleading, similar to handling user agent strings in web browsers. --- # KeyMaterialProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / KeyMaterialProvider # Type Alias: KeyMaterialProvider > **KeyMaterialProvider** = `object` Object resolving prover and verifier keys, as well as the ZKIR representation of the circuit. It is almost identical to the one in Midnight.js's `ZKConfigProvider` () It has separate methods for getting the ZKIR, prover key and verifier key to allow for caching of the keys and to avoid loading the prover key into memory when it is not needed. ## Methods[​](#methods "Direct link to Methods") ### getProverKey()[​](#getproverkey "Direct link to getProverKey()") > **getProverKey**(`circuitKeyLocation`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters "Direct link to Parameters") ##### circuitKeyLocation[​](#circuitkeylocation "Direct link to circuitKeyLocation") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> *** ### getVerifierKey()[​](#getverifierkey "Direct link to getVerifierKey()") > **getVerifierKey**(`circuitKeyLocation`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### circuitKeyLocation[​](#circuitkeylocation-1 "Direct link to circuitKeyLocation") `string` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> *** ### getZKIR()[​](#getzkir "Direct link to getZKIR()") > **getZKIR**(`circuitKeyLocation`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### circuitKeyLocation[​](#circuitkeylocation-2 "Direct link to circuitKeyLocation") `string` #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> --- # ProvingProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / ProvingProvider # Type Alias: ProvingProvider > **ProvingProvider** = `object` Object abstracting the proving functionality It is compatible with Ledger's ProvingProvider () ## Methods[​](#methods "Direct link to Methods") ### check()[​](#check "Direct link to check()") > **check**(`serializedPreimage`, `keyLocation`): `Promise`<(`bigint` | `undefined`)\[]> #### Parameters[​](#parameters "Direct link to Parameters") ##### serializedPreimage[​](#serializedpreimage "Direct link to serializedPreimage") `Uint8Array` ##### keyLocation[​](#keylocation "Direct link to keyLocation") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<(`bigint` | `undefined`)\[]> *** ### prove()[​](#prove "Direct link to prove()") > **prove**(`serializedPreimage`, `keyLocation`, `overwriteBindingInput?`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### serializedPreimage[​](#serializedpreimage-1 "Direct link to serializedPreimage") `Uint8Array` ##### keyLocation[​](#keylocation-1 "Direct link to keyLocation") `string` ##### overwriteBindingInput?[​](#overwritebindinginput "Direct link to overwriteBindingInput?") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> --- # Signature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / Signature # Type Alias: Signature > **Signature** = `object` Signature, accompanied by data signed and verifying key ## Properties[​](#properties "Direct link to Properties") ### data[​](#data "Direct link to data") > **data**: `string` The data signed *** ### signature[​](#signature "Direct link to signature") > **signature**: `string` *** ### verifyingKey[​](#verifyingkey "Direct link to verifyingKey") > **verifyingKey**: `string` --- # SignDataOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / SignDataOptions # Type Alias: SignDataOptions > **SignDataOptions** = `object` Options for signing data. It specified which key to use for signing and how the data to sign is encoded. ## Properties[​](#properties "Direct link to Properties") ### encoding[​](#encoding "Direct link to encoding") > **encoding**: `"hex"` | `"base64"` | `"text"` How are data for signing encoded. "hex" and "base64" mean binary data are encoded using one or the other format, the wallet must decode them into binary sequence first "text" means the data should be signed as provided in the string, but encoded into UTF-8 as a normalization step. Conversion is necessary, because JS strings are UTF-16 *** ### keyType[​](#keytype "Direct link to keyType") > **keyType**: `"unshielded"` What kind of key to use for signing --- # TokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / TokenType # Type Alias: TokenType > **TokenType** = `string` Type of a token. It will be a hex-encoded string relating to ledger's raw token type. --- # TxStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / TxStatus # Type Alias: TxStatus > **TxStatus** = { `executionStatus`: [`ExecutionStatus`](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md); `status`: `"finalized"`; } | { `executionStatus`: [`ExecutionStatus`](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md); `status`: `"confirmed"`; } | { `status`: `"pending"`; } | { `status`: `"discarded"`; } ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") { `executionStatus`: [`ExecutionStatus`](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md); `status`: `"finalized"`; } ### executionStatus[​](#executionstatus "Direct link to executionStatus") > **executionStatus**: [`ExecutionStatus`](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md) ### status[​](#status "Direct link to status") > **status**: `"finalized"` Transaction included in chain and finalized { `executionStatus`: [`ExecutionStatus`](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md); `status`: `"confirmed"`; } ### executionStatus[​](#executionstatus-1 "Direct link to executionStatus") > **executionStatus**: [`ExecutionStatus`](/api-reference/dapp-connector/type-aliases/ExecutionStatus.md) ### status[​](#status-1 "Direct link to status") > **status**: `"confirmed"` Transaction included in chain and not finalized yet { `status`: `"pending"`; } ### status[​](#status-2 "Direct link to status") > **status**: `"pending"` Transaction sent to network but is not known to be either confirmed or discarded yet { `status`: `"discarded"`; } ### status[​](#status-3 "Direct link to status") > **status**: `"discarded"` Transaction failed to be included in chain, e.g. because of TTL or some validity checks --- # WalletConnectedAPI > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / WalletConnectedAPI # Type Alias: WalletConnectedAPI > **WalletConnectedAPI** = `object` Wallet connected API. It is a subset of the Connected API defining all wallet-relevant methods. Full Connected API also implements [HintUsage](/api-reference/dapp-connector/type-aliases/HintUsage.md). The operations provided cover all necessary functionality for a DApp to interact with the wallet: * getting balances and addresses * submitting transactions * creating and balancing transactions * initializing intents (for swaps) * signing data ## Methods[​](#methods "Direct link to Methods") ### balanceSealedTransaction()[​](#balancesealedtransaction "Direct link to balanceSealedTransaction()") > **balanceSealedTransaction**(`tx`, `options?`): `Promise`<{ `tx`: `string`; }> Take sealed transaction (with proofs, signatures and cryptographically bound), pay fees, add necessary inputs and outputs to remove imbalances from it, returning a transaction ready for submission This method is mainly expected to be used by DApps when they operate on transactions created by the wallet or when the DApp wants to be sure that wallet performs balancing in a separate intent. In such case, it is important to remember that some contracts might make use of fallible sections, in which case wallet won't be able to properly balance the transaction. In such cases, the DApp should use [balanceUnsealedTransaction](#balanceunsealedtransaction) instead. In relation to Ledger API (`@midnight-ntwrk/ledger-v`), this method expects a serialized transaction of type `Transaction` Options: `payFees` - whether wallet should pay fees for the issued transaction or not, true by default #### Parameters[​](#parameters "Direct link to Parameters") ##### tx[​](#tx "Direct link to tx") `string` ##### options?[​](#options "Direct link to options?") ###### payFees?[​](#payfees "Direct link to payFees?") `boolean` #### Returns[​](#returns "Direct link to Returns") `Promise`<{ `tx`: `string`; }> *** ### balanceUnsealedTransaction()[​](#balanceunsealedtransaction "Direct link to balanceUnsealedTransaction()") > **balanceUnsealedTransaction**(`tx`, `options?`): `Promise`<{ `tx`: `string`; }> Take unsealed transaction (with proofs, with no signatures and with preimage data for cryptographic binding), pay fees, add necessary inputs and outputs to remove imbalances from it, returning a transaction ready for submission This method is expected to be used by DApps when interacting with contracts - in many cases when contracts interact with native tokens, where wallet may need to add inputs and outputs to an existing intent to properly balance the transaction. In relation to Ledger API (`@midnight-ntwrk/ledger-v`), this method expects a serialized transaction of type `Transaction` Options: `payFees` - whether wallet should pay fees for the issued transaction or not, true by default #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### tx[​](#tx-1 "Direct link to tx") `string` ##### options?[​](#options-1 "Direct link to options?") ###### payFees?[​](#payfees-1 "Direct link to payFees?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> *** ### getConfiguration()[​](#getconfiguration "Direct link to getConfiguration()") > **getConfiguration**(): `Promise`<[`Configuration`](/api-reference/dapp-connector/type-aliases/Configuration.md)> Get the configuration of the services used by the wallet. It is important for DApps to make use of those services whenever possible, as the wallet user might have some preferences in this regard, which e.g. improve privacy or performance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`Configuration`](/api-reference/dapp-connector/type-aliases/Configuration.md)> *** ### getConnectionStatus()[​](#getconnectionstatus "Direct link to getConnectionStatus()") > **getConnectionStatus**(): `Promise`<[`ConnectionStatus`](/api-reference/dapp-connector/type-aliases/ConnectionStatus.md)> Status of an existing connection to wallet DApps can use this method to check if the connection is still valid. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<[`ConnectionStatus`](/api-reference/dapp-connector/type-aliases/ConnectionStatus.md)> *** ### getDustAddress()[​](#getdustaddress "Direct link to getDustAddress()") > **getDustAddress**(): `Promise`<{ `dustAddress`: `string`; }> Get the Dust address of the wallet. It is provided in Bech32m format. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<{ `dustAddress`: `string`; }> *** ### getDustBalance()[​](#getdustbalance "Direct link to getDustBalance()") > **getDustBalance**(): `Promise`<{ `balance`: `bigint`; `cap`: `bigint`; }> Get the balance of Dust of the wallet. It reports both: * the current balance (which may change over time due to generation mechanics) * the cap (the maximum amount of Dust that can be generated from the current Night balance). #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<{ `balance`: `bigint`; `cap`: `bigint`; }> *** ### getProvingProvider()[​](#getprovingprovider "Direct link to getProvingProvider()") > **getProvingProvider**(`keyMaterialProvider`): `Promise`<[`ProvingProvider`](/api-reference/dapp-connector/type-aliases/ProvingProvider.md)> Obtain the proving provider from the wallet to delegate proving to the wallet. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### keyMaterialProvider[​](#keymaterialprovider "Direct link to keyMaterialProvider") [`KeyMaterialProvider`](/api-reference/dapp-connector/type-aliases/KeyMaterialProvider.md) object resolving prover and verifier keys, as well as the ZKIR representation of the circuit; `KeyMaterialProvider` is almost identical to the one in Midnight.js's `ZKConfigProvider` () #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`ProvingProvider`](/api-reference/dapp-connector/type-aliases/ProvingProvider.md)> A `ProvingProvider` instance, compatible with Ledger's ProvingProvider () *** ### getShieldedAddresses()[​](#getshieldedaddresses "Direct link to getShieldedAddresses()") > **getShieldedAddresses**(): `Promise`<{ `shieldedAddress`: `string`; `shieldedCoinPublicKey`: `string`; `shieldedEncryptionPublicKey`: `string`; }> Get the shielded addresses of the wallet. For convenience it also returns the coin public key and encryption public key. All of them are provided in Bech32m format. #### Returns[​](#returns-7 "Direct link to Returns") `Promise`<{ `shieldedAddress`: `string`; `shieldedCoinPublicKey`: `string`; `shieldedEncryptionPublicKey`: `string`; }> *** ### getShieldedBalances()[​](#getshieldedbalances "Direct link to getShieldedBalances()") > **getShieldedBalances**(): `Promise`<`Record`<`string`, `bigint`>> Get the balances of shielded tokens of the wallet. They are represented as a record, whose keys are token types. #### Returns[​](#returns-8 "Direct link to Returns") `Promise`<`Record`<`string`, `bigint`>> *** ### getTxHistory()[​](#gettxhistory "Direct link to getTxHistory()") > **getTxHistory**(`pageNumber`, `pageSize`): `Promise`<[`HistoryEntry`](/api-reference/dapp-connector/type-aliases/HistoryEntry.md)\[]> Get the history of transactions of the wallet. Each history entry is a simplistic record of the fact that a transaction is relevant to the wallet. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### pageNumber[​](#pagenumber "Direct link to pageNumber") `number` ##### pageSize[​](#pagesize "Direct link to pageSize") `number` #### Returns[​](#returns-9 "Direct link to Returns") `Promise`<[`HistoryEntry`](/api-reference/dapp-connector/type-aliases/HistoryEntry.md)\[]> *** ### getUnshieldedAddress()[​](#getunshieldedaddress "Direct link to getUnshieldedAddress()") > **getUnshieldedAddress**(): `Promise`<{ `unshieldedAddress`: `string`; }> Get the unshielded address of the wallet. It is provided in Bech32m format. #### Returns[​](#returns-10 "Direct link to Returns") `Promise`<{ `unshieldedAddress`: `string`; }> *** ### getUnshieldedBalances()[​](#getunshieldedbalances "Direct link to getUnshieldedBalances()") > **getUnshieldedBalances**(): `Promise`<`Record`<`string`, `bigint`>> Get the balances of unshielded tokens (potentially including Night) of the wallet. They are represented as a record, whose keys are token types. #### Returns[​](#returns-11 "Direct link to Returns") `Promise`<`Record`<`string`, `bigint`>> *** ### makeIntent()[​](#makeintent "Direct link to makeIntent()") > **makeIntent**(`desiredInputs`, `desiredOutputs`, `options`): `Promise`<{ `tx`: `string`; }> Initialize a transaction with unbalanced intent containing desired inputs and outputs. Primary use-case for this method is to create a transaction, which inits a swap Options: `intentId` - what id use for created intent: use 1 to ensure no transaction merging will result in actions executed before created intent in the same transaction use specific number within ledger limitations to make the intent have that segment id assigned use "random" to allow wallet to pick one in random (e.g. when creating intent for swap purposes) `payFees` - whether wallet should pay fees for the issued transaction or not #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### desiredInputs[​](#desiredinputs "Direct link to desiredInputs") [`DesiredInput`](/api-reference/dapp-connector/type-aliases/DesiredInput.md)\[] ##### desiredOutputs[​](#desiredoutputs "Direct link to desiredOutputs") [`DesiredOutput`](/api-reference/dapp-connector/type-aliases/DesiredOutput.md)\[] ##### options[​](#options-2 "Direct link to options") ###### intentId[​](#intentid "Direct link to intentId") `number` | `"random"` ###### payFees[​](#payfees-2 "Direct link to payFees") `boolean` #### Returns[​](#returns-12 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> *** ### makeTransfer()[​](#maketransfer "Direct link to makeTransfer()") > **makeTransfer**(`desiredOutputs`, `options?`): `Promise`<{ `tx`: `string`; }> Initialize a transfer transaction with desired outputs Options: `payFees` - whether wallet should pay fees for the issued transaction or not, true by default #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### desiredOutputs[​](#desiredoutputs-1 "Direct link to desiredOutputs") [`DesiredOutput`](/api-reference/dapp-connector/type-aliases/DesiredOutput.md)\[] ##### options?[​](#options-3 "Direct link to options?") ###### payFees?[​](#payfees-3 "Direct link to payFees?") `boolean` #### Returns[​](#returns-13 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> *** ### signData()[​](#signdata "Direct link to signData()") > **signData**(`data`, `options`): `Promise`<[`Signature`](/api-reference/dapp-connector/type-aliases/Signature.md)> Sign provided data using key and format specified in the options, data to sign will be prepended with right prefix #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### data[​](#data "Direct link to data") `string` ##### options[​](#options-4 "Direct link to options") [`SignDataOptions`](/api-reference/dapp-connector/type-aliases/SignDataOptions.md) #### Returns[​](#returns-14 "Direct link to Returns") `Promise`<[`Signature`](/api-reference/dapp-connector/type-aliases/Signature.md)> *** ### submitTransaction()[​](#submittransaction "Direct link to submitTransaction()") > **submitTransaction**(`tx`): `Promise`<`void`> Submit a transaction to the network, effectively using wallet as a relayer. The transaction received is expected to be balanced and "sealed" - it means it contains proofs, signatures and cryptographically bound (`Transaction` type from `@midnight-ntwrk/ledger`) #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### tx[​](#tx-2 "Direct link to tx") `string` #### Returns[​](#returns-15 "Direct link to Returns") `Promise`<`void`> --- # ErrorCodes > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/dapp-connector-api v4.0.1**](/api-reference/dapp-connector.md) *** [@midnight-ntwrk/dapp-connector-api](/api-reference/dapp-connector/globals.md) / ErrorCodes # Variable: ErrorCodes > `const` **ErrorCodes**: `object` All possible error codes gathered in a single object. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### Disconnected[​](#disconnected "Direct link to Disconnected") > `readonly` **Disconnected**: `"Disconnected"` = `'Disconnected'` The connection to the wallet was lost ### InternalError[​](#internalerror "Direct link to InternalError") > `readonly` **InternalError**: `"InternalError"` = `'InternalError'` The dapp connector wasn't able to process the request ### InvalidRequest[​](#invalidrequest "Direct link to InvalidRequest") > `readonly` **InvalidRequest**: `"InvalidRequest"` = `'InvalidRequest'` Can be thrown in various circumstances, e.g. one being a malformed transaction ### PermissionRejected[​](#permissionrejected "Direct link to PermissionRejected") > `readonly` **PermissionRejected**: `"PermissionRejected"` = `'PermissionRejected'` Permission to perform action was rejected. ### Rejected[​](#rejected "Direct link to Rejected") > `readonly` **Rejected**: `"Rejected"` = `'Rejected'` The user rejected the request --- > For the complete documentation index, see [llms.txt](/llms.txt) # DApp Connector API errors The Midnight DApp Connector is the browser-based API that connects DApps to supported wallets such as Lace and 1AM. This reference covers the error codes that the DApp Connector API returns when a DApp interacts with the wallet. Errors surface as `APIError` objects with a `type` field, not as `instanceof` checks. Always use `error.type === 'DAppConnectorAPIError'` to identify them. ## Error codes (v4.0.x)[​](#error-codes-v40x "Direct link to Error codes (v4.0.x)") The following error codes are available in the current version of the DApp Connector API. | Code | Description | Scope | Fix | | -------------------- | ------------------------------------------------------------ | ------------- | -------------------------------------------------------------------------------------- | | `Disconnected` | Connection to the wallet was lost mid-session. | Session-level | Re-establish the connection by calling `enable()` again. | | `InternalError` | Connector could not process the request internally. | Internal | Retry the operation; check Lace wallet logs and update the wallet extension if needed. | | `InvalidRequest` | Malformed transaction or invalid request parameters. | Client error | Verify the transaction structure; check parameter types and formats. | | `PermissionRejected` | Users have set a session-level preference to deny this DApp. | Persistent | Ask users to unblock the DApp in their wallet settings. | | `Rejected` | Users saw a specific request and declined this time. | Per-request | Tell users they cancelled the action; do not auto-retry. | ### Key distinction: `Rejected` vs. `PermissionRejected`[​](#key-distinction-rejected-vs-permissionrejected "Direct link to key-distinction-rejected-vs-permissionrejected") These two codes both represent user rejection, but differ in scope and how to respond. * **`Rejected`**: Users saw the specific transaction or request and declined this time. The DApp can try again with a different request. * **`PermissionRejected`**: Users have set a session-level preference to deny this DApp entirely. Retrying produces the same result until users change their wallet settings. ### Detecting `APIError`[​](#detecting-apierror "Direct link to detecting-apierror") Use `error.type` to identify DApp Connector API errors. Do not use `instanceof` checks, as `APIError` is not a class you can test against. ``` // Use the type field to identify connector errors if (error.type === 'DAppConnectorAPIError') { switch (error.code) { case 'Rejected': // user declined case 'PermissionRejected': // user blocked DApp case 'InvalidRequest': // bad request case 'InternalError': // internal failure case 'Disconnected': // connection lost } } // Do NOT use instanceof // if (error instanceof APIError) { ... } ``` ### Structure of `APIError`[​](#structure-of-apierror "Direct link to structure-of-apierror") The `APIError` type extends the native `Error` object with the following fields. ``` type APIError = Error & { type: 'DAppConnectorAPIError'; code: ErrorCode; // one of the 5 codes above reason: string; // human-readable explanation } ``` ## Transaction status types[​](#transaction-status-types "Direct link to Transaction status types") The DApp Connector also reports transaction status through these values. | Status | Description | | ----------- | ------------------------------------------------------ | | `finalized` | Consensus has finalized the transaction. | | `confirmed` | Transaction included in a block but not yet finalized. | | `pending` | Transaction submitted, awaiting block inclusion. | | `discarded` | The node discarded the transaction (not included). | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight indexer error codes The Midnight indexer is a Rust service built on Axum that serves a GraphQL API via `async-graphql`, typically on port 8088. All errors use `thiserror` derives. Errors fall into two categories: * **Client errors**: Appear verbatim in GraphQL error responses and indicate invalid caller input. * **Server errors**: Logged internally by the indexer. Callers receive a generic `"Internal Server Error"` message. You encounter these errors when: * The node rejects a GraphQL query or mutation due to invalid input * The `/ready` health endpoint returns non-200 during startup or when the indexer lags behind the node * Infrastructure failures occur (database, messaging, cipher) ## HTTP status codes[​](#http-status-codes "Direct link to HTTP status codes") The Axum HTTP layer returns these codes before any GraphQL processing occurs. | Code | Endpoint / context | Description | Fix | | ----------------------- | ------------------ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | 200 OK | `GET /ready` | Indexer is caught up with the node. | Service is healthy. | | 400 Bad Request | GraphQL body | Invalid request body (malformed JSON or missing required fields). | Check GraphQL query syntax and ensure `Content-Type: application/json` is set. | | 413 Payload Too Large | GraphQL body | Request body exceeds the configured size limit. | Reduce query complexity, paginate results, or split into multiple smaller queries. | | 503 Service Unavailable | `GET /ready` | Indexer has not caught up with the node. | Wait for the indexer to finish syncing, check node connectivity, and indexer logs. | ## GraphQL client error messages[​](#graphql-client-error-messages "Direct link to GraphQL client error messages") These strings appear verbatim in GraphQL error responses (`errors[].message`). They indicate invalid input from the caller. ### Block errors[​](#block-errors "Direct link to Block errors") These errors occur when the indexer cannot resolve a block reference in a query. | Message | Description | Fix | | ---------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | `"block with hash {hash} not found"` | No block with the given hash exists in the indexed chain. | The block might not be final yet, or the hash is incorrect; verify the hash and try again. | | `"block with height {height} not found"` | The indexer has not yet indexed a block at that height. | The indexer might not have reached that height yet; check sync status via `GET /ready`. | | `"invalid block hash"` | The supplied block hash is not valid hex or has the wrong length. | Verify the block hash format; it must be a valid 32-byte hex-encoded string. | ### Viewing key and session errors[​](#viewing-key-and-session-errors "Direct link to Viewing key and session errors") These errors occur when wallet credentials or session tokens fail validation. | Message | Description | Fix | | --------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `"invalid session ID"` | The session ID has an invalid format (not a valid UUID). | Use the session ID exactly as returned during session creation. | | `"invalid viewing key"` | The supplied viewing key failed to decode or validate. | Ensure a compatible SDK version generated the viewing key and that it is correctly encoded. | | `"unknown or expired session ID"` | The session ID does not exist or has timed out. | Re-authenticate to obtain a fresh session ID. | ### Transaction errors[​](#transaction-errors "Direct link to Transaction errors") These errors occur when a transaction reference or identifier supplied in a query is invalid. | Message | Description | Fix | | ---------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------- | | `"invalid transaction hash"` | The transaction hash is not a valid hex-encoded hash. | Verify the hash format; it must be a valid 32-byte hex string. | | `"invalid transaction identifier"` | The transaction identifier failed validation. | Check the identifier format; it may be base58 or hex depending on context. | ### Address errors[​](#address-errors "Direct link to Address errors") These errors occur when an address supplied in a query fails format or checksum validation. | Message | Description | Fix | | ---------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `"invalid address"` | The supplied address (unshielded, shielded, or DUST) failed Bech32m decode or HRP validation. | Verify the address format. For expected HRP prefixes, see the [Address format errors](#address-format-errors) section. | | `"invalid Cardano reward address"` | The Cardano stake address failed validation. | Use a valid Bech32-encoded Cardano stake address with HRP `stake` for Mainnet or `stake_test` for Testnet and ensure it is 29 bytes. | | `"invalid hex-encoded DUST address"` | The DUST address hex encoding is invalid. | Supply a correctly hex-encoded DUST address. | | `"invalid hex-encoded nullifier prefix"` | The nullifier prefix is not valid hex. | Supply a correctly hex-encoded nullifier prefix. | ### Pagination and identifier errors[​](#pagination-and-identifier-errors "Direct link to Pagination and identifier errors") These errors occur when pagination parameters or generic identifiers fail validation. | Message | Description | Fix | | ------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------- | | `"invalid identifier"` | A generic identifier (for example, contract address or key) failed validation. | Verify the format of the identifier you are passing. | | `"invalid offset"` | The pagination offset value is not a valid non-negative integer. | Use a non-negative integer for the offset parameter. | | `"maximum of ten reward addresses allowed"` | You supplied more than 10 Cardano reward addresses in a single query. | Split the request into batches of 10 or fewer addresses. | ## Domain errors[​](#domain-errors "Direct link to Domain errors") Domain errors arise from validation of structured values such as network IDs and protocol versions. ### `InvalidNetworkIdError`[​](#invalidnetworkiderror "Direct link to invalidnetworkiderror") Returned when a network ID value fails validation. | Variant | Description | Fix | | -------------- | -------------------------------- | ----------------------------------------------- | | `Empty` | Network ID must not be empty | Provide a non-empty network ID string. | | `NotLowercase` | Network ID must be all lowercase | Convert the network ID to lowercase before use. | ### `ProtocolVersionError`[​](#protocolversionerror "Direct link to protocolversionerror") Returned when the system cannot resolve a protocol version value to a known version. | Variant | Description | Fix | | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `ScaleDecode` | SCALE decoding of the protocol version failed. | The raw bytes are invalid; this typically indicates a node/indexer version mismatch. | | `TryFromI64` | The system cannot convert the version value from i64. | The raw version value is negative or out of i64 representable range; internal error. | | `Unsupported(u32)` | Protocol version number is not in a recognized range. | Valid ranges: 22000-23000 (maps to `V0_22`), 1000000-1001000 (maps to `V1_0`); update the indexer if a newer version is available. | ### `ledger::Error`[​](#ledgererror "Direct link to ledgererror") Internal ledger errors (13 variants). These are server errors. Callers see only "Internal Server Error". Check indexer logs for details. | Variant | Description | | ----------------------------------- | ------------------------------------------------------------- | | `BackwardsLedgerStateTranslation` | Ledger state translation went backwards (version regression). | | `BlockLimitExceeded` | Operation exceeds block-level limits. | | `ByteArrayLen` | Byte array has unexpected length. | | `Deserialize` | Failed to deserialize ledger data. | | `FromUtf8` | Failed to convert bytes to UTF-8 string. | | `GetContractState` | Failed to retrieve contract state. | | `InvalidUpdate` | The node rejected the ledger state update as invalid. | | `LedgerStateTranslation` | Generic ledger state translation failure. | | `LoadLedgerState` | Failed to load ledger state from storage. | | `MalformedTransaction` | Transaction data is structurally malformed. | | `Serialize` | Failed to serialize ledger data. | | `SystemTransaction` | Error processing a system transaction. | | `TransactionCost` | Failed to calculate transaction cost. | | `UnsupportedLedgerStateTranslation` | No translation path available for this ledger state version. | ## Address format errors[​](#address-format-errors "Direct link to Address format errors") These errors surface when a Midnight or Cardano address supplied to the indexer fails to decode. ### `DecodeAddressError`[​](#decodeaddresserror "Direct link to decodeaddresserror") Returned when a Midnight address fails to decode. | Variant | Description | Fix | | ------------ | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `Decode` | Bech32m decode failed (invalid characters, bad checksum, or truncated). | Ensure the address is a valid Bech32m string. | | `InvalidHrp` | Human-readable part (HRP) does not match the expected prefix. | Use the correct address type for the operation; see expected HRP prefixes below. | Expected HRP prefixes: | Address type | Mainnet HRP | Non-Mainnet HRP | | ------------------------- | --------------- | ---------------------------- | | Unshielded | `mn_addr` | `mn_addr_{network_id}` | | Encryption key (shielded) | `mn_shield-esk` | `mn_shield-esk_{network_id}` | | DUST | `mn_dust` | `mn_dust_{network_id}` | ### `DecodeCardanoRewardAddressError`[​](#decodecardanorewardaddresserror "Direct link to decodecardanorewardaddresserror") Returned when a Cardano stake (reward) address fails to decode. | Variant | Description | Fix | | --------------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `Decode` | Bech32 decode failed. | Ensure the address is a valid Bech32-encoded Cardano stake address. | | `InvalidHrp` | HRP is not `stake` or `stake_test`. | Use a Cardano Mainnet (`stake`) or Testnet (`stake_test`) reward address. | | `InvalidLength` | Decoded bytes are not 29 bytes. | The address payload must be exactly 29 bytes; verify the address is not truncated or padded. | | `WrongNetwork` | Address network byte does not match the expected network. | Ensure the Cardano address is for the correct network (Mainnet vs. Testnet). | ## Chain indexer errors (`SubxtNodeError`)[​](#chain-indexer-errors-subxtnodeerror "Direct link to chain-indexer-errors-subxtnodeerror") These errors arise from the streaming layer that connects the indexer to the Midnight node via Subxt. Most variants trigger automatic reconnection; persistent errors indicate node connectivity or compatibility issues. There are 22 variants in total. The following table lists the most common ones. | Variant | Description | Action | | ---------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `GenesisLedgerStateNotFound` | No genesis ledger state found in system parameters. | Node system parameters storage is missing genesis data; might indicate a misconfigured or corrupted node. | | `GetContractState` | The indexer cannot fetch contract state from the node. | Node RPC failure; check node logs and connectivity. | | `ProtocolVersion` | The indexer encountered an unsupported protocol version during sync. | The indexer does not recognize this protocol version; upgrade the indexer. | | `ReceiveBlock` | Node disconnected mid-stream. | The indexer auto-reconnects. If persistent, check node stability. | | `ScaleDecode` | SCALE decode failure when processing a block or event. | The indexer could not decode data from the node; likely a version mismatch. | | `SubscribeFinalizedBlocks` | The indexer cannot subscribe to the finalized block stream from the node. | Verify the node's WebSocket endpoint is reachable; check node logs. | ## Infrastructure errors[​](#infrastructure-errors "Direct link to Infrastructure errors") These are server errors. The indexer logs them internally and returns "Internal Server Error" to callers. Investigate via indexer logs. ### Database[​](#database "Direct link to Database") Database errors occur when the indexer cannot connect to or query its storage backend. | Category | Examples | Common causes | | ---------------- | --------------------------------------------------------- | ------------------------------------------------------------------------ | | `PostgresPool` | Connection pool exhaustion, failed to acquire connection. | PostgreSQL unreachable, connection limit exceeded, or credentials wrong. | | `SqlitePool` | SQLite pool failure. | SQLite file locked, disk full, or permissions issue. | | Migration errors | Schema migration failed on startup. | Database schema out of date or incompatible; run pending migrations. | ### Messaging (NATS)[​](#messaging-nats "Direct link to Messaging (NATS)") Messaging errors occur when the indexer cannot publish or receive events through the NATS message broker. | Category | Description | Common causes | | ---------------------- | ------------------------------------------------------ | ------------------------------------------------------ | | NATS publisher errors | Failed to publish a message to NATS. | NATS server unreachable or subject permissions denied. | | NATS subscriber errors | Failed to subscribe to or receive from a NATS subject. | NATS server connectivity issue or subject not found. | ### Cipher[​](#cipher "Direct link to Cipher") Cipher errors occur when the indexer cannot initialize its encryption key from configuration. | Variant | Description | Fix | | ------------------ | ------------------------------------------------ | ------------------------------------------------------------- | | Hex decode failure | Cipher key or encrypted value is not valid hex. | Verify the cipher key configuration is correctly hex-encoded. | | Key too short | Cipher key is below the minimum required length. | Provide a key of at least 32 bytes (64 hex characters). | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Ledger error reference The `midnight-ledger` crate defines the full taxonomy of transaction validation, execution, and state management errors. These are the Rust-level error types behind the numeric `LedgerApiError` codes that the node surfaces. ## Error hierarchy[​](#error-hierarchy "Direct link to Error hierarchy") Understanding the chain from top-level to low-level is essential when reading nested error output. A `MalformedTransaction::InvalidProof` near the top of a chain might trace back to a deep `OnchainProgramError::Decode` inside a contract transcript execution. ``` MalformedTransaction └─ wraps zswap::MalformedOffer └─ wraps TranscriptRejected └─ wraps OnchainProgramError └─ wraps InvalidBuiltinDecode └─ wraps merkle_tree::InvalidUpdate ``` ## Error types[​](#error-types "Direct link to Error types") The following sections describe each error type in the chain, from the top-level transaction envelope down to low-level tree and VM operations. ### `MalformedTransaction`[​](#malformedtransaction "Direct link to malformedtransaction") Over 50 variants, parameterized as `MalformedTransaction`. These are structural validity errors the ledger checks before any state application. The ledger rejects malformed transactions without modifying state. #### Proof and cryptographic errors[​](#proof-and-cryptographic-errors "Direct link to Proof and cryptographic errors") These errors indicate failures in zero-knowledge proof verification or cryptographic consistency checks. | Variant | Description | Fix | | --------------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | | `BindingCommitmentOpeningInvalid` | The binding commitment opening does not match the committed value. | Indicates a bug in transaction construction; recheck commitment generation. | | `InvalidNetworkId` | The transaction targets a different network (for example, Mainnet vs. Devnet). | Rebuild the transaction targeting the correct network ID. | | `InvalidProof` | A zero-knowledge proof failed verification. | Reproving required; check that the witness and public inputs match. | | `InvalidSchnorrProof` | A Schnorr signature proof failed verification. | Key mismatch or corrupted signing data; re-sign. | | `PedersenCheckFailure` | A Pedersen commitment consistency check failed. | Balance or value encoding error; recheck transaction values. | #### Structural errors[​](#structural-errors "Direct link to Structural errors") These errors indicate violations of canonical form or transaction structure rules. | Variant | Description | Fix | | --------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `FallibleWithoutCheckpoint` | A fallible transaction segment lacks the required checkpoint. | Add a checkpoint to the fallible segment. | | `NotNormalized` | Transaction fields are not in the required canonical sort order. | Sort and normalize transaction fields per the ledger spec before submitting. | | `TooManyZswapEntries` | The transaction contains more Zswap entries than the protocol allows. | Split Zswap operations across multiple transactions. | | `TransactionTooLarge` | The serialized transaction exceeds the maximum allowed byte size. | Split into smaller transactions or reduce payload size. | | `VerifierKeyTooLarge` | A verifier key in the transaction exceeds the size limit. | Check that the correct (non-debug) verifier key is in use. | #### Claims errors[​](#claims-errors "Direct link to Claims errors") These errors occur when coin claim data is inconsistent or fails verification. | Variant | Description | Fix | | ---------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `ClaimCoinMismatch` | The coin referenced in a claim does not match the expected coin. | Ensure the claim targets the correct coin data. | | `ClaimNullifierFailed` | The nullifier in a claim is invalid or does not match. | Regenerate the nullifier from the correct key and coin data. | | `ClaimOverflow` | Arithmetic overflow occurred while summing claim values. | Reduce individual claim values; the total may exceed `u64::MAX`. | | `ClaimReceiveFailed` | A coin receive claim is invalid or the ledger cannot verify it. | Check that the claim data matches the target coin. | | `ClaimSpendFailed` | A coin spend claim failed verification. | Verify the spend authorization and nullifier data. | | `UnclaimedCoinCom` | A coin commitment is present but has no corresponding claim. | Ensure every coin commitment has a valid associated claim. | | `UnclaimedNullifier` | A nullifier is present but has no corresponding coin claim. | Ensure every nullifier has a corresponding spend claim. | | `Unbalanced` | The transaction inputs and outputs do not balance; value is not conserved. | Recheck token amounts across all inputs and outputs. | #### Committee errors[​](#committee-errors "Direct link to Committee errors") These errors arise when a transaction's committee signatures are missing, insufficient, or invalid. | Variant | Description | Fix | | --------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------- | | `InvalidCommitteeSignature` | A committee signature has an invalid format or does not verify. | Re-collect signatures from valid committee members. | | `KeyNotInCommittee` | A key used for signing is not a member of the expected committee. | Use a key registered as a committee member for this epoch. | | `ThresholdMissed` | The required threshold of committee signatures was not reached. | Gather signatures from more committee members before submitting. | #### Intents errors[​](#intents-errors "Direct link to Intents errors") These errors occur when transaction intents carry invalid signatures or conflicting segment identifiers. | Variant | Description | Fix | | ------------------------------------ | ------------------------------------------------------------------ | --------------------------------------------- | | `IntentAtGuaranteedSegmentId` | An intent targets a guaranteed segment ID, which is not permitted. | Move the intent to a non-guaranteed segment. | | `IntentSegmentIdCollision` | Two intents reference the same segment ID. | Assign unique segment IDs to each intent. | | `IntentSignatureVerificationFailure` | An intent's signature failed verification. | Re-sign the intent with the correct key. | | `IntentSignatureKeyMismatch` | The signing key does not match the key declared in the intent. | Ensure the intent uses the key it references. | #### Balance check errors[​](#balance-check-errors "Direct link to Balance check errors") These errors occur when token balance verification fails during transaction validation. | Variant | Description | Fix | | ------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | | `BalanceCheckConversionFailure` | Type conversion failed during balance verification. | Indicates a bug in value encoding; check token type consistency. | | `BalanceCheckOutOfBounds` | A balance value is outside the valid numeric range for the check. | Verify that all token amounts are within protocol-defined bounds. | | `BalanceCheckOverspend` | The transaction attempts to spend more than is available. | Reduce spend amounts or add sufficient inputs. | #### DUST errors[​](#dust-errors "Direct link to DUST errors") These errors occur when DUST registration or spend operations fail validation. | Variant | Description | Fix | | ------------------------------------ | ---------------------------------------------------------------------------- | ----------------------------------------------------------- | | `InsufficientDustForRegistrationFee` | The DUST amount is below the minimum required to cover the registration fee. | Increase the DUST amount to meet the minimum fee threshold. | | `InvalidDustRegistrationSignature` | The DUST registration signature is invalid. | Re-sign the DUST registration with the correct key. | | `InvalidDustSpendProof` | The proof for a DUST spend is invalid. | Regenerate the spend proof with correct witness data. | | `MultipleDustRegistrationsForKey` | The same key appears in multiple DUST registrations in one transaction. | Use each DUST key at most once per transaction. | | `OutOfDustValidityWindow` | The DUST registration or spend is outside the allowed validity window. | Check block height and resubmit within the validity window. | #### Version errors[​](#version-errors "Direct link to Version errors") These errors occur when a proof or transcript uses a version the node does not recognize. | Variant | Description | Fix | | ----------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------- | | `FallibleTranscriptVersion` | The transcript version is invalid for a fallible segment. | Ensure fallible segments use the correct transcript version format. | | `GuaranteedTranscriptVersion` | The transcript version is invalid for a guaranteed segment. | Ensure guaranteed segments use the correct transcript version format. | | `UnsupportedProofVersion` | The proof uses a version the node does not support. | Upgrade the SDK or reproduce the proof with a supported version. | #### Check errors[​](#check-errors "Direct link to Check errors") These errors occur when static consistency checks on transaction effects or segment ordering fail. | Variant | Description | Fix | | ------------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | `DisjointCheckFailure` | Segments that should be disjoint share resources or state. | Ensure segments operate on non-overlapping state. | | `EffectsCheckFailure` | The declared effects of the transaction failed static consistency checks. | Verify that declared effects match what contract execution would produce. | | `SequencingCheckFailure` | The transaction violated segment ordering constraints. | Reorder segments to satisfy sequencing requirements. | #### Sorting and deduplication errors[​](#sorting-and-deduplication-errors "Direct link to Sorting and deduplication errors") These errors occur when transaction inputs or outputs violate canonical ordering or uniqueness requirements. | Variant | Description | Fix | | -------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | `DuplicateInputs` | The same input appears more than once in the transaction. | Remove duplicate inputs. | | `InputsNotSorted` | Transaction inputs are not in the required canonical sort order. | Sort inputs according to the ledger's canonical ordering before building the transaction. | | `InputsSignaturesLengthMismatch` | The number of input signatures does not match the number of inputs. | Provide exactly one signature per input. | | `OutputsNotSorted` | Transaction outputs are not in the required canonical sort order. | Sort outputs canonically before building the transaction. | ### `TransactionInvalid`[​](#transactioninvalid "Direct link to transactioninvalid") These state-application errors occur when the ledger applies a structurally valid transaction to the current state but rejects it due to state inconsistencies. This enum is `#[non_exhaustive]` and defines 19 variants. | Variant | Description | Fix | | --------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `BalanceCheckOutOfBounds` | A balance value is out of valid range during state application. | Verify token amounts are within bounds after accounting for current state. | | `ContractAlreadyDeployed` | A contract deployment targets an address that already has a contract. | Deploy to a different address or verify deployment uniqueness. | | `ContractNotPresent` | A transaction calls a contract that does not exist at the given address. | Verify the contract address and confirm the contract exists at that address. | | `DivideByZero` | A division by zero occurred during transaction processing. | Indicates a bug in transaction value computation. | | `DustDeregistrationNotRegistered` | The transaction attempts to deregister a DUST key that has no active registration. | Confirm the key has an active registration before deregistering it. | | `DustDoubleSpend` | A DUST coin the transaction attempts to spend is already spent. | Check current DUST UTXO state; the coin has already been spent. | | `EffectsMismatch` | The actual effects of applying the transaction differ from the declared effects. | Declared effects must exactly match what contract execution produces. | | `GenerationInfoAlreadyPresent` | Generation info for this epoch/key is already recorded on-chain. | You can only submit generation info once per epoch. | | `InputNotInUtxos` | A transaction input references a UTXO that does not exist in the current state. | The UTXO may already be spent; fetch fresh state before building the transaction. | | `InsufficientClaimable` | The transaction attempts to claim more than is available in the claimable pool. | Reduce the claim amount or wait for more claimable funds to become available. | | `InvariantViolation` | The ledger detected an internal invariant violation. | Report as a bug; this should not occur with a correctly implemented node or SDK. | | `MerkleTreeError` | A Merkle tree operation failed during state application. | For more details, see the [`merkle_tree::InvalidUpdate`](#merkle_treeinvalidupdate) section. | | `ReplayCounterMismatch` | The replay protection counter does not match the expected value. | Fetch the current replay counter from the node and use it in the transaction. | | `ReplayProtectionViolation` | The transaction violates replay protection constraints. | Ensure the transaction is not a duplicate or out-of-sequence. | | `RewardTooSmall` | The reward amount is below the minimum required. | Increase the reward amount to meet the protocol minimum. | | `Transcript` | The ledger rejected a contract transcript execution (wraps `TranscriptRejected`). | For more details, see the [TranscriptRejected errors section](#transcriptrejected). | | `VerifierKeyAlreadyPresent` | A verifier key registration targets a key that is already registered. | Do not re-register existing verifier keys. | | `VerifierKeyNotFound` | A verifier key referenced in the transaction is not registered on-chain. | Register the verifier key before submitting transactions that reference it. | | `Zswap` | A Zswap sub-operation failed (wraps `zswap::TransactionInvalid`). | For more details, see the [Zswap errors section](#zswap-errors). | ### `OnchainProgramError`[​](#onchainprogramerror "Direct link to onchainprogramerror") These errors surface when contract transcript execution fails inside the Impact VM on-chain execution engine. This enum defines 17 variants. | Variant | Description | | ---------------------- | ----------------------------------------------------------------------------------------------------- | | `ArithmeticOverflow` | An arithmetic operation overflowed the supported integer range. | | `AttemptedArrayDelete` | An attempt made to delete an array element, which is not supported. | | `BoundsExceeded` | An array or buffer access targeted an out-of-bounds position. | | `CacheMiss` | A cache lookup for a required value returned no result during execution. | | `CellBoundExceeded` | A cell value exceeded the maximum allowed size. | | `Decode` | Failed to decode a value from the stack or program data (wraps `InvalidBuiltinDecode`). | | `ExpectedCell` | The VM expected a cell value at a stack position but found a different type. | | `InvalidArgs` | A built-in function received invalid or wrong-count arguments. | | `LogBoundExceeded` | A logging operation exceeded the maximum allowed log size. | | `MerkleTreeError` | A Merkle tree built-in operation failed inside the VM. | | `MissingKey` | A required key was not found in the contract state map. | | `OutOfGas` | The transaction ran out of gas during contract execution. | | `RanOffStack` | The VM stack ran out of space; a pop or read targeted an empty stack. | | `RanPastProgramEnd` | The program counter advanced past the end of the bytecode. | | `ReadMismatch` | A read from contract state returned a value that does not match the value declared in the transcript. | | `StackOverflow` | The VM call stack grew too deep, exceeding the recursion limit. | | `TooLongForEqual` | An equality comparison targeted values exceeding the maximum comparable length. | | `TypeError(String)` | A type mismatch occurred during VM execution. The string describes the mismatch. | ### `TranscriptRejected`[​](#transcriptrejected "Direct link to transcriptrejected") This type wraps `OnchainProgramError` and represents failures during on-chain contract execution. It defines five variants. | Variant | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------- | | `Decode` | Failed to decode the transcript input before execution could begin. | | `EffectDecodeError` | Failed to decode the effects emitted by the contract execution. | | `Execution` | Contract execution failed (wraps `OnchainProgramError`). The inner error contains the VM-level failure. | | `FinalStackWrongLength` | After execution completed, the stack did not have the expected number of elements. | | `WeakStateReturned` | The contract returned a weakened state when the protocol required a full state. | ### Zswap errors[​](#zswap-errors "Direct link to Zswap errors") Zswap manages private coin operations including shielded transfers, coin commitments, and double-spend prevention. #### `zswap::TransactionInvalid`[​](#zswaptransactioninvalid "Direct link to zswaptransactioninvalid") State-level Zswap failures that occur when the ledger applies a Zswap operation to the current state. | Variant | Description | Fix | | -------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `CommitmentAlreadyPresent` | A coin commitment already exists in the commitment tree. | Duplicate commitment; check for replay or construction error. | | `MerkleTreeError` | A Merkle tree update failed during Zswap state application. | For more details, see the [`merkle_tree::InvalidUpdate`](#merkle_treeinvalidupdate) section. | | `NullifierAlreadyPresent` | The nullifier has already been spent; this is a double-spend attempt. | The coin has been spent; do not attempt to spend it again. | | `UnknownMerkleRoot` | The Merkle root referenced in the proof is not known to the current state. | Fetch the current Merkle root from the node and rebuild the proof. | #### `zswap::MalformedOffer`[​](#zswapmalformedoffer "Direct link to zswapmalformedoffer") Structural Zswap errors checked before any state application. | Variant | Description | Fix | | ------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `ContractSentCiphertext` | A contract attempted to send ciphertext, which is not permitted in this context. | Contracts must not produce ciphertext outputs directly. | | `InvalidProof` | A Zswap zero-knowledge proof failed verification. | Regenerate the proof with correct witness and public inputs. | | `NonDisjointCoinMerge` | A coin merge targeted non-disjoint coin sets. | Ensure merged coin sets are fully disjoint. | | `NotNormalized` | The offer is not in canonical normalized form. | Normalize the offer before including it in a transaction. | #### `zswap::OfferCreationFailed`[​](#zswapoffercreationfailed "Direct link to zswapoffercreationfailed") Client-side errors encountered while constructing a Zswap offer. | Variant | Description | Fix | | ------------------ | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `InvalidIndex` | The offer construction used an invalid index. | Verify the coin index is within the valid range for the Merkle tree. | | `MerkleTreeError` | A Merkle tree operation failed during offer construction. | For more details, see the [`merkle_tree::InvalidUpdate`](#merkle_treeinvalidupdate) section. | | `NotContractOwned` | The offer references a coin that is not owned by the expected contract. | Ensure you construct offers only for coins the correct contract owns. | | `Proving` | The zero-knowledge proving step failed during offer creation. | Check that all witnesses are valid; re-run proving with correct inputs. | | `TreeNotRehashed` | The Merkle tree requires a rehash after recent updates. | Call the tree rehash operation before constructing the offer. | ### Merkle tree errors[​](#merkle-tree-errors "Direct link to Merkle tree errors") These errors surface when operations on the commitment Merkle tree fail. #### `merkle_tree::InvalidIndex`[​](#merkle_treeinvalidindex "Direct link to merkle_treeinvalidindex") Returned when a provided index is out of range for the current tree size. | Variant | Description | | ------------------- | -------------------------------------------------------------------- | | `InvalidIndex(u64)` | The provided index is out of range for the current Merkle tree size. | #### `merkle_tree::InvalidUpdate`[​](#merkle_treeinvalidupdate "Direct link to merkle_treeinvalidupdate") Six variants representing structural failures when updating the Merkle tree. | Variant | Description | | ----------------------- | ------------------------------------------------------------------------------ | | `BadUpdatePath` | The Merkle path provided for the update is incorrect or inconsistent. | | `CollapsedIndex` | An update targeted a collapsed (pruned) subtree node. | | `EndBeforeStart` | The end index of an update range is before the start index. | | `EndOutOfTree` | The end index of an update range extends past the tree boundary. | | `NotFullyRehashed` | The tree has pending updates without a rehash; it is in an inconsistent state. | | `StubUpdate` | An update targeted a stub node that cannot accept updates. | | `WrongNumberOfSegments` | The update provides a different number of segments than expected. | ### Other error types[​](#other-error-types "Direct link to Other error types") The following types cover client-side construction, fee calculation, system transactions, and auxiliary operations. #### `FeeCalculationError`[​](#feecalculationerror "Direct link to feecalculationerror") Errors that occur during fee computation before transaction submission. | Variant | Description | | ---------------------- | ------------------------------------------------------------------------------ | | `BlockLimitExceeded` | The transaction exceeded the block limit during fee computation. | | `OutsideTimeToDismiss` | The transaction exceeds the maximum allowed time-to-dismiss for its byte size. | #### `MalformedContractDeploy`[​](#malformedcontractdeploy "Direct link to malformedcontractdeploy") Errors specific to contract deployment transactions, checked before state application. | Variant | Description | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `IncorrectChargedState` | The contract deployment contains an incorrectly computed map of charged keys. | | `NonZeroBalance` | The contract deployment carries a non-zero token balance. Contract deployments must not include pre-existing balances. | #### `SystemTransactionError`[​](#systemtransactionerror "Direct link to systemtransactionerror") These errors arise in protocol-level system transactions, such as epoch transitions and committee updates. This type defines 10 variants. | Variant | Description | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | `CommitmentAlreadyPresent` | A coin commitment already exists in the tree; this is a double-spend attempt. | | `GenerationInfoAlreadyPresent` | DUST generation info for this epoch already exists; the ledger rejects the duplicate insertion. | | `IllegalPayout` | The payout or bridge amount exceeds the remaining native token supply or bridge pool. | | `IllegalReserveDistribution` | The distribution amount exceeds the remaining reserve token supply. | | `InsufficientTreasuryFunds` | The treasury does not hold enough tokens of the requested type to fulfil the request. | | `InvalidBasisPoints` | The `cardano_to_midnight_bridge_fee_basis_points` value is 10,000 or greater, which is outside the valid range. | | `InvariantViolation` | The total NIGHT supply implied by the transaction exceeds `MAX_SUPPLY`. | | `MerkleTreeError` | A Merkle tree operation failed during the system transaction. See `merkle_tree::InvalidUpdate` for details. | | `ReplayProtectionFailure` | The system transaction violated replay protection constraints (wraps `TransactionApplicationError`). | | `TreasuryDisabled` | Governance has not yet enabled the treasury; the ledger rejects treasury access until stakeholders reach an agreement. | #### `TransactionConstructionError`[​](#transactionconstructionerror "Direct link to transactionconstructionerror") Client-side errors encountered while building a transaction before submission. | Variant | Description | | -------------------- | ------------------------------------------------------------------------------------------- | | `MissingVerifierKey` | The contract operation lacks a verifier key; the proving step cannot proceed. | | `ProofFailed` | Proof generation failed during transaction assembly (wraps `ProvingError`). | | `TransactionEmpty` | The transaction contains no operations; add at least one before submission. | | `UnfinishedCall` | The client started a contract call but did not complete it before building the transaction. | #### `TransactionProvingError`[​](#transactionprovingerror "Direct link to transactionprovingerror") The following errors occur during the proving phase. note The `Proving` variant wraps `ProvingError`, which is an opaque `anyhow::Error` alias. The `Tokio` variant wraps `std::io::Error` and surfaces I/O failures from the async runtime. | Variant | Description | | ----------------- | -------------------------------------------------------------------------------------- | | `LeftoverEntries` | The transcript for a contract operation had more entries than the proof consumed. | | `MissingKeyset` | The proving keys for the required circuit location could not be found. | | `Proving` | The underlying proving backend returned an error (wraps `ProvingError`). | | `RanOutOfEntries` | The transcript for a contract operation ran out of entries before the proof completed. | | `Tokio` | An I/O error occurred during async proof generation (wraps `std::io::Error`). | #### `EventReplayError`[​](#eventreplayerror "Direct link to eventreplayerror") Errors encountered during event log replay, used for syncing wallet state from on-chain events. | Variant | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `DtimeUpdateForUntracked` | An attempt targeted a DUST generation entry that the client does not track. | | `EventForPastTime` | An event carries a timestamp earlier than the time the client has already synced to. | | `MerkleTreeError` | A Merkle tree operation failed during event replay. For more details, see the [`merkle_tree::InvalidUpdate`](#merkle_treeinvalidupdate) section. | | `NonLinearInsertion` | The client inserted events into a Merkle tree non-linearly; the expected index and the received index do not match. | #### `DustLocalStateError`[​](#dustlocalstateerror "Direct link to dustlocalstateerror") The following errors occur in local DUST state management on the client side. | Variant | Description | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `BackingNightNotFound` | No generation info exists for the given backing NIGHT nonce. | | `CommitmentIndexNotFound` | No commitment exists for the given commitment index. | | `GenerationIndexNotFound` | No generation info exists for the given generation index. | | `MerkleTreeError` | A Merkle tree operation failed during local state management. For more details, see the [`merkle_tree::InvalidUpdate`](#merkle_treeinvalidupdate) section. | | `NonLinearInsertion` | The client inserted values into a Merkle tree non-linearly; the expected and received indices do not match. | | `WrongGenerationInfo` | The generation info stored for the given index is invalid. | ## Cross-reference: Rust error to node error code[​](#cross-reference-rust-error-to-node-error-code "Direct link to Cross-reference: Rust error to node error code") When debugging a node error code, find the underlying Rust error by: * Looking up the numeric `LedgerApiError` code in the node error codes reference to find the high-level category. * Checking the node's structured error response body. The Rust error type is often serialized as a string in the `detail` or `cause` field. * Matching the Rust type name against the tables in this reference. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Proof server errors The proof server is a standalone HTTP service that generates zero-knowledge proofs for transactions. It is part of the `midnight-ledger` repository and typically runs on port 6300. It is the only crate in `midnight-ledger` that uses `thiserror` derives for error handling. The server maps errors to HTTP status codes and returns them as HTTP responses. ## Worker pool errors (`WorkerPoolError`)[​](#worker-pool-errors-workerpoolerror "Direct link to worker-pool-errors-workerpoolerror") These errors arise from the proof server's internal job queue and worker pool management. | HTTP status | Error | Description | Fix | | ------------------------- | --------------------- | --------------------------------------- | --------------------------------------------------- | | 400 Bad Request | `JobNotPending(Uuid)` | Tried to cancel a non-pending job. | Job is already processing, completed, or cancelled. | | 428 Precondition Required | `JobMissing(Uuid)` | Referenced job not found. | The job ID is invalid or has expired. | | 429 Too Many Requests | `JobQueueFull` | The proof generation job queue is full. | Wait and retry; the server is under heavy load. | | 500 Internal Server Error | `ChannelClosed` | Internal work channel closed. | Restart the proof server. | ## Work errors (`WorkError`)[​](#work-errors-workerror "Direct link to work-errors-workerror") These errors occur during the actual proof generation process. | HTTP Status | Error | Description | Fix | | ------------------------- | ----------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------ | | 400 Bad Request | `BadInput(String)` | Proof request input data is invalid. | Check the transaction data being sent for proving. | | 500 Internal Server Error | `CancelledUnexpectedly` | The system cancelled the job without an explicit request | Internal error; retry the proof request | | 500 Internal Server Error | `InternalError(String)` | Internal proof generation error. | Check proof server logs; restart the proof server if the error persists. | | 500 Internal Server Error | `JoinError` | Task join error during proof generation. | Internal threading error; retry or restart. | ## Job status enum[​](#job-status-enum "Direct link to Job status enum") The proof server tracks each proof job through the following states. | Status | Description | | ------------------ | --------------------------------- | | `Pending` | Job queued, waiting for a worker. | | `Processing` | Proof generation in progress. | | `Cancelled` | The system cancelled this job. | | `Error(WorkError)` | Job failed with an error. | | `Success(Vec)` | Proof generated successfully. | ## Health endpoint[​](#health-endpoint "Direct link to Health endpoint") Use the `/ready` endpoint to check whether the proof server is accepting new requests. | Endpoint | HTTP status | Description | | ------------ | ----------------------- | ----------------------------------------- | | `GET /ready` | 200 OK | Server is ready to accept proof requests. | | `GET /ready` | 503 Service Unavailable | Server is busy (all workers occupied). | ## Common issues[​](#common-issues "Direct link to Common issues") The following table covers the most frequent problems and their likely causes. | Symptom | Likely cause | Fix | | ------------------------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | 429 responses | Too many concurrent proof requests are being sent to the server. | Reduce the number of parallel proof requests and implement an exponential backoff retry strategy so requests are spaced out under load. | | 503 from `/ready` | All proof workers are busy. | Wait for current proofs to complete or increase the worker count in config. | | 500 with "BadInput" | Malformed transaction data | Verify the transaction was built correctly with the SDK. | | Connection refused on port 6300 | Proof server not running | Start the proof server container, check Docker status. | | Slow proof generation | Large circuit or insufficient resources | Allocate more CPU or memory to the proof server container. | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Ledger API **@midnight/ledger v8.0.3** *** # Ledger TypeScript API This document outlines the flow of transaction assembly and usage with the ledger TS API. ## Proof stages[​](#proof-stages "Direct link to Proof stages") Most transaction components will be in one of three stages: `X`, `UnprovenX`, or `ProofErasedX`. The `UnprovenX` stage is *always* the first one. It is possible to transition to the `X` stage by proving an `UnprovenTransaction` through the proof server. For testing, and where proofs aren't necessary, the `ProofErasedX` stage is used, which can be reached via `eraseProof[s]` from the other two stages. ## Transaction structure[​](#transaction-structure "Direct link to Transaction structure") A [Transaction](/api-reference/ledger/classes/Transaction.md) runs in two phases: a *guaranteed* segment, handling fee payments and fast-to-verify operations, and a series of *fallible segments*. Each segment may fail atomically, separately from the guaranteed segment. It therefore contains: * A "guaranteed" [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md) * A map of segment IDs to "fallible" [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md)s. * A map of segment IDs to [Intent](/api-reference/ledger/classes/Intent.md)s, which include [UnshieldedOffer](/api-reference/ledger/classes/UnshieldedOffer.md)s and [ContractAction](/api-reference/ledger/type-aliases/ContractAction.md)s. It also contains additional cryptographic glue that will be omitted in this document. ### Zswap[​](#zswap "Direct link to Zswap") A [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md) consists of: * A set of [ZswapInput](/api-reference/ledger/classes/ZswapInput.md)s, burning coins. * A set of [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md)s, creating coins. * A set of [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md)s, indicating a coin that is created and burnt in the same transaction. * A mapping from [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md)s to offer balance, positive when there are more inputs than outputs and vice versa. [ZswapInput](/api-reference/ledger/classes/ZswapInput.md)s can be created either from a [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) and a contract address, if the coin is contract-owned, or from a [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) and a [ZswapLocalState](/api-reference/ledger/classes/ZswapLocalState.md), if it is user-owned. Similarly, [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md)s can be created from a [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) and a contract address for contract-owned coins, or from a [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) and a user's public key(s), if it is user-owned. A [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md) is created similarly to a [ZswapInput](/api-reference/ledger/classes/ZswapInput.md), but directly converts an existing [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md). A [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) is a [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) with an index into the Merkle tree of coin commitments that can be used to find the relevant coin to spend, while a [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) consists of a coin's [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md), value, and a nonce. ### Calls[​](#calls "Direct link to Calls") A [ContractDeploy](/api-reference/ledger/classes/ContractDeploy.md) consists of an initial contract state, and a nonce. A [ContractCall](/api-reference/ledger/classes/ContractCall.md) consists of a contract's address, the entry point used on this contract, a guaranteed and a fallible public oracle transcript, a communication commitment, and a proof. [ContractCall](/api-reference/ledger/classes/ContractCall.md)s are constructed via [ContractCallPrototype](/api-reference/ledger/classes/ContractCallPrototype.md)s, which consist of the following raw pieces of data: * The contract address * The contract's entry point * The contract operation expected (that is, the verifier key and transcript shape expected to be at this contract address and entry point) * The guaranteed transcript (as produced by the generated JS code) * The fallible transcript (as produced by the generated JS code) * The outputs of the private oracle calls (As a FAB [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md)s) * The input(s) to the call, concatenated together (As a FAB [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md)) * The output(s) to the call, concatenated together (As a FAB [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md)) * The communications commitment randomness (As a hex-encoded field element string) * A unique identifier for the ZK circuit used (used by the proof server to index for the prover key) NOTE: currently the JS code only generates a single transcript. We probably just want a canonical way to split this into guaranteed/fallible? A [Intent](/api-reference/ledger/classes/Intent.md) object is assembed, and [ContractCallPrototype](/api-reference/ledger/classes/ContractCallPrototype.md)s / [ContractDeploy](/api-reference/ledger/classes/ContractDeploy.md)s are added to this directly. This can then be inserted into an [Transaction](/api-reference/ledger/classes/Transaction.md). ## State Structure[​](#state-structure "Direct link to State Structure") The [LedgerState](/api-reference/ledger/classes/LedgerState.md) is the primary entry point for Midnight's ledger state, and it consists of a [ZswapChainState](/api-reference/ledger/classes/ZswapChainState.md), as well as a mapping from [ContractAddress](/api-reference/ledger/type-aliases/ContractAddress.md)es to [ContractState](/api-reference/ledger/classes/ContractState.md)s. States are immutable, and applying transactions always produce new outputs states. --- # Binding > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Binding # Class: Binding A Fiat-Shamir proof of exponent binding (or ephemerally signing) an [Intent](/api-reference/ledger/classes/Intent.md). ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new Binding(data): Binding; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### data[​](#data "Direct link to data") `String` #### Returns[​](#returns "Direct link to Returns") `Binding` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` instance: "binding"; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): Binding; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `Binding` --- # ChargedState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ChargedState # Class: ChargedState Represents a [StateValue](/api-reference/ledger/classes/StateValue.md) with storage annotations. These track the state usage that has been charged for so far. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ChargedState(state): ChargedState; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`StateValue`](/api-reference/ledger/classes/StateValue.md) #### Returns[​](#returns "Direct link to Returns") `ChargedState` ## Properties[​](#properties "Direct link to Properties") ### state[​](#state-1 "Direct link to state") ``` readonly state: StateValue; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # ClaimRewardsTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ClaimRewardsTransaction # Class: ClaimRewardsTransaction\ A request to allocate rewards, authorized by the reward's recipient ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ClaimRewardsTransaction( markerS, network_id, value, owner, nonce, signature, kind?): ClaimRewardsTransaction; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### markerS[​](#markers "Direct link to markerS") `S`\[`"instance"`] ##### network\_id[​](#network_id "Direct link to network_id") `string` ##### value[​](#value "Direct link to value") `bigint` ##### owner[​](#owner "Direct link to owner") `string` ##### nonce[​](#nonce "Direct link to nonce") `string` ##### signature[​](#signature "Direct link to signature") `S` ##### kind?[​](#kind "Direct link to kind?") [`ClaimKind`](/api-reference/ledger/type-aliases/ClaimKind.md) #### Returns[​](#returns "Direct link to Returns") `ClaimRewardsTransaction`<`S`> ## Properties[​](#properties "Direct link to Properties") ### dataToSign[​](#datatosign "Direct link to dataToSign") ``` readonly dataToSign: Uint8Array; ``` The raw data any valid signature must be over to approve this transaction. *** ### kind[​](#kind-1 "Direct link to kind") ``` readonly kind: ClaimKind; ``` The kind of claim being made, either a `Reward` or a `CardanoBridge` claim. *** ### nonce[​](#nonce-1 "Direct link to nonce") ``` readonly nonce: string; ``` The rewarded coin's randomness, preventing it from colliding with other coins. *** ### owner[​](#owner-1 "Direct link to owner") ``` readonly owner: string; ``` The signing key owning this coin. *** ### signature[​](#signature-1 "Direct link to signature") ``` readonly signature: S; ``` The signature on this request. *** ### value[​](#value-1 "Direct link to value") ``` readonly value: bigint; ``` The rewarded coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer ## Methods[​](#methods "Direct link to Methods") ### addSignature()[​](#addsignature "Direct link to addSignature()") ``` addSignature(signature): ClaimRewardsTransaction; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### signature[​](#signature-2 "Direct link to signature") `string` #### Returns[​](#returns-1 "Direct link to Returns") `ClaimRewardsTransaction`<[`SignatureEnabled`](/api-reference/ledger/classes/SignatureEnabled.md)> *** ### eraseSignatures()[​](#erasesignatures "Direct link to eraseSignatures()") ``` eraseSignatures(): ClaimRewardsTransaction; ``` #### Returns[​](#returns-2 "Direct link to Returns") `ClaimRewardsTransaction`<[`SignatureErased`](/api-reference/ledger/classes/SignatureErased.md)> *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-3 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(markerS, raw): ClaimRewardsTransaction; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### S[​](#s-1 "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### markerS[​](#markers-1 "Direct link to markerS") `S`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-5 "Direct link to Returns") `ClaimRewardsTransaction`<`S`> *** ### new()[​](#new "Direct link to new()") ``` static new( network_id, value, owner, nonce, kind): ClaimRewardsTransaction; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### network\_id[​](#network_id-1 "Direct link to network_id") `string` ##### value[​](#value-2 "Direct link to value") `bigint` ##### owner[​](#owner-2 "Direct link to owner") `string` ##### nonce[​](#nonce-2 "Direct link to nonce") `string` ##### kind[​](#kind-2 "Direct link to kind") [`ClaimKind`](/api-reference/ledger/type-aliases/ClaimKind.md) #### Returns[​](#returns-6 "Direct link to Returns") `ClaimRewardsTransaction`<[`SignatureErased`](/api-reference/ledger/classes/SignatureErased.md)> --- # CoinSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CoinSecretKey # Class: CoinSecretKey Holds the coin secret key of a user, serialized as a hex-encoded 32-byte string ## Methods[​](#methods "Direct link to Methods") ### clear()[​](#clear "Direct link to clear()") ``` clear(): void; ``` Clears the coin secret key, so that it is no longer usable nor held in memory #### Returns[​](#returns "Direct link to Returns") `void` *** ### yesIKnowTheSecurityImplicationsOfThis\_serialize()[​](#yesiknowthesecurityimplicationsofthis_serialize "Direct link to yesIKnowTheSecurityImplicationsOfThis_serialize()") ``` yesIKnowTheSecurityImplicationsOfThis_serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): CoinSecretKey; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `CoinSecretKey` --- # ContractCall > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractCall # Class: ContractCall\

A single contract call segment ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Properties[​](#properties "Direct link to Properties") ### address[​](#address "Direct link to address") ``` readonly address: string; ``` The address being called *** ### communicationCommitment[​](#communicationcommitment "Direct link to communicationCommitment") ``` readonly communicationCommitment: string; ``` The communication commitment of this call *** ### entryPoint[​](#entrypoint "Direct link to entryPoint") ``` readonly entryPoint: string | Uint8Array; ``` The entry point being called *** ### fallibleTranscript[​](#fallibletranscript "Direct link to fallibleTranscript") ``` readonly fallibleTranscript: | undefined | Transcript; ``` The fallible execution stage transcript *** ### guaranteedTranscript[​](#guaranteedtranscript "Direct link to guaranteedTranscript") ``` readonly guaranteedTranscript: | undefined | Transcript; ``` The guaranteed execution stage transcript *** ### proof[​](#proof "Direct link to proof") ``` readonly proof: P; ``` The proof attached to this call ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # ContractCallPrototype > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractCallPrototype # Class: ContractCallPrototype A [ContractCall](/api-reference/ledger/classes/ContractCall.md) still being assembled ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractCallPrototype( address, entry_point, op, guaranteed_public_transcript, fallible_public_transcript, private_transcript_outputs, input, output, communication_commitment_rand, key_location): ContractCallPrototype; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### address[​](#address "Direct link to address") `string` The address being called ##### entry\_point[​](#entry_point "Direct link to entry_point") The entry point being called `string` | `Uint8Array`<`ArrayBufferLike`> ##### op[​](#op "Direct link to op") [`ContractOperation`](/api-reference/ledger/classes/ContractOperation.md) The operation expected at this entry point ##### guaranteed\_public\_transcript[​](#guaranteed_public_transcript "Direct link to guaranteed_public_transcript") The guaranteed transcript computed for this call `undefined` | [`Transcript`](/api-reference/ledger/type-aliases/Transcript.md)<[`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)> ##### fallible\_public\_transcript[​](#fallible_public_transcript "Direct link to fallible_public_transcript") The fallible transcript computed for this call `undefined` | [`Transcript`](/api-reference/ledger/type-aliases/Transcript.md)<[`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)> ##### private\_transcript\_outputs[​](#private_transcript_outputs "Direct link to private_transcript_outputs") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)\[] The private transcript recorded for this call ##### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) The input(s) provided to this call ##### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) The output(s) computed from this call ##### communication\_commitment\_rand[​](#communication_commitment_rand "Direct link to communication_commitment_rand") `string` The communication randomness used for this call ##### key\_location[​](#key_location "Direct link to key_location") `string` An identifier for how the key for this call may be looked up #### Returns[​](#returns "Direct link to Returns") `ContractCallPrototype` ## Methods[​](#methods "Direct link to Methods") ### intoCall()[​](#intocall "Direct link to intoCall()") ``` intoCall(parentBinding): ContractCall; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### parentBinding[​](#parentbinding "Direct link to parentBinding") [`PreBinding`](/api-reference/ledger/classes/PreBinding.md) #### Returns[​](#returns-1 "Direct link to Returns") [`ContractCall`](/api-reference/ledger/classes/ContractCall.md)<[`PreProof`](/api-reference/ledger/classes/PreProof.md)> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` --- # ContractDeploy > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractDeploy # Class: ContractDeploy A contract deployment segment, instructing the creation of a new contract address, if not already present ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractDeploy(initial_state): ContractDeploy; ``` Creates a deployment for an arbitrary contract state The deployment and its address are randomised. #### Parameters[​](#parameters "Direct link to Parameters") ##### initial\_state[​](#initial_state "Direct link to initial_state") [`ContractState`](/api-reference/ledger/classes/ContractState.md) #### Returns[​](#returns "Direct link to Returns") `ContractDeploy` ## Properties[​](#properties "Direct link to Properties") ### address[​](#address "Direct link to address") ``` readonly address: string; ``` The address this deployment will attempt to create *** ### initialState[​](#initialstate "Direct link to initialState") ``` readonly initialState: ContractState; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # ContractMaintenanceAuthority > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractMaintenanceAuthority # Class: ContractMaintenanceAuthority A committee permitted to make changes to this contract. If a threshold of the public keys in this committee sign off, they can change the rules of this contract, or recompile it for a new version. If the threshold is greater than the number of committee members, it is impossible for them to sign anything. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractMaintenanceAuthority( committee, threshold, counter?): ContractMaintenanceAuthority; ``` Constructs a new authority from its components If not supplied, `counter` will default to `0n`. Values should be non-negative, and at most 2^32 - 1. At deployment, `counter` must be `0n`, and any subsequent update should set counter to exactly one greater than the current value. #### Parameters[​](#parameters "Direct link to Parameters") ##### committee[​](#committee "Direct link to committee") `string`\[] ##### threshold[​](#threshold "Direct link to threshold") `number` ##### counter?[​](#counter "Direct link to counter?") `bigint` #### Returns[​](#returns "Direct link to Returns") `ContractMaintenanceAuthority` ## Properties[​](#properties "Direct link to Properties") ### committee[​](#committee-1 "Direct link to committee") ``` readonly committee: string[]; ``` The committee public keys *** ### counter[​](#counter-1 "Direct link to counter") ``` readonly counter: bigint; ``` The replay protection counter *** ### threshold[​](#threshold-1 "Direct link to threshold") ``` readonly threshold: number; ``` How many keys must sign rule changes ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractState; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") [`ContractState`](/api-reference/ledger/classes/ContractState.md) --- # ContractOperation > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractOperation # Class: ContractOperation An individual operation, or entry point of a contract, consisting primarily of a ZK verifier keys, potentially for different versions of the proving system. Only the latest available version is exposed to this API. Note that the serialized form of the key is checked on initialization ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractOperation(): ContractOperation; ``` #### Returns[​](#returns "Direct link to Returns") `ContractOperation` ## Properties[​](#properties "Direct link to Properties") ### verifierKey[​](#verifierkey "Direct link to verifierKey") ``` verifierKey: Uint8Array; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractOperation; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `ContractOperation` --- # ContractOperationVersion > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractOperationVersion # Class: ContractOperationVersion The version associated with a [ContractOperation](/api-reference/ledger/classes/ContractOperation.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractOperationVersion(version): ContractOperationVersion; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### version[​](#version "Direct link to version") `"v3"` #### Returns[​](#returns "Direct link to Returns") `ContractOperationVersion` ## Properties[​](#properties "Direct link to Properties") ### version[​](#version-1 "Direct link to version") ``` readonly version: "v3"; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # ContractOperationVersionedVerifierKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractOperationVersionedVerifierKey # Class: ContractOperationVersionedVerifierKey A versioned verifier key to be associated with a [ContractOperation](/api-reference/ledger/classes/ContractOperation.md). ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractOperationVersionedVerifierKey(version, rawVk): ContractOperationVersionedVerifierKey; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### version[​](#version "Direct link to version") `"v3"` ##### rawVk[​](#rawvk "Direct link to rawVk") `Uint8Array` #### Returns[​](#returns "Direct link to Returns") `ContractOperationVersionedVerifierKey` ## Properties[​](#properties "Direct link to Properties") ### rawVk[​](#rawvk-1 "Direct link to rawVk") ``` readonly rawVk: Uint8Array; ``` *** ### version[​](#version-1 "Direct link to version") ``` readonly version: "v3"; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # ContractState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractState # Class: ContractState The state of a contract, consisting primarily of the [data](#data) accessible directly to the contract, and the map of [ContractOperation](/api-reference/ledger/classes/ContractOperation.md)s that can be called on it, the keys of which can be accessed with [operations](#operations), and the individual operations can be read with [operation](#operation) and written to with [setOperation](#setoperation). ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ContractState(): ContractState; ``` Creates a blank contract state #### Returns[​](#returns "Direct link to Returns") `ContractState` ## Properties[​](#properties "Direct link to Properties") ### balance[​](#balance "Direct link to balance") ``` balance: Map; ``` The public balances held by this contract *** ### data[​](#data "Direct link to data") ``` data: ChargedState; ``` The current value of the primary state of the contract *** ### maintenanceAuthority[​](#maintenanceauthority "Direct link to maintenanceAuthority") ``` maintenanceAuthority: ContractMaintenanceAuthority; ``` The maintenance authority associated with this contract ## Methods[​](#methods "Direct link to Methods") ### operation()[​](#operation "Direct link to operation()") ``` operation(operation): undefined | ContractOperation; ``` Get the operation at a specific entry point name #### Parameters[​](#parameters "Direct link to Parameters") ##### operation[​](#operation-1 "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`ContractOperation`](/api-reference/ledger/classes/ContractOperation.md) *** ### operations()[​](#operations "Direct link to operations()") ``` operations(): (string | Uint8Array)[]; ``` Return a list of the entry points currently registered on this contract #### Returns[​](#returns-2 "Direct link to Returns") (`string` | `Uint8Array`<`ArrayBufferLike`>)\[] *** ### query()[​](#query "Direct link to query()") ``` query(query, cost_model): GatherResult[]; ``` Runs a series of operations against the current state, and returns the results #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### query[​](#query-1 "Direct link to query") [`Op`](/api-reference/ledger/type-aliases/Op.md)<`null`>\[] ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/ledger/classes/CostModel.md) #### Returns[​](#returns-3 "Direct link to Returns") [`GatherResult`](/api-reference/ledger/type-aliases/GatherResult.md)\[] *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-4 "Direct link to Returns") `Uint8Array` *** ### setOperation()[​](#setoperation "Direct link to setOperation()") ``` setOperation(operation, value): void; ``` Set a specific entry point name to contain a given operation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### operation[​](#operation-2 "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> ##### value[​](#value "Direct link to value") [`ContractOperation`](/api-reference/ledger/classes/ContractOperation.md) #### Returns[​](#returns-5 "Direct link to Returns") `void` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractState; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-7 "Direct link to Returns") `ContractState` --- # CostModel > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CostModel # Class: CostModel A cost model for calculating transaction fees ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` *** ### initialCostModel()[​](#initialcostmodel "Direct link to initialCostModel()") ``` static initialCostModel(): CostModel; ``` The initial cost model of Midnight #### Returns[​](#returns-1 "Direct link to Returns") `CostModel` --- # DustActions > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustActions # Class: DustActions\ ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustActions( markerS, markerP, ctime, spends?, registrations?): DustActions; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### markerS[​](#markers "Direct link to markerS") `S`\[`"instance"`] ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### ctime[​](#ctime "Direct link to ctime") `Date` ##### spends?[​](#spends "Direct link to spends?") [`DustSpend`](/api-reference/ledger/classes/DustSpend.md)<`P`>\[] ##### registrations?[​](#registrations "Direct link to registrations?") [`DustRegistration`](/api-reference/ledger/classes/DustRegistration.md)<`S`>\[] #### Returns[​](#returns "Direct link to Returns") `DustActions`<`S`, `P`> ## Properties[​](#properties "Direct link to Properties") ### ctime[​](#ctime-1 "Direct link to ctime") ``` ctime: Date; ``` *** ### registrations[​](#registrations-1 "Direct link to registrations") ``` registrations: DustRegistration[]; ``` *** ### spends[​](#spends-1 "Direct link to spends") ``` spends: DustSpend

[]; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize( markerS, markerP, raw): DustActions; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### S[​](#s-1 "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### markerS[​](#markers-1 "Direct link to markerS") `S`\[`"instance"`] ##### markerP[​](#markerp-1 "Direct link to markerP") `P`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `DustActions`<`S`, `P`> --- # DustGenerationState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustGenerationState # Class: DustGenerationState ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustGenerationState(): DustGenerationState; ``` #### Returns[​](#returns "Direct link to Returns") `DustGenerationState` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): DustGenerationState; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `DustGenerationState` --- # DustLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustLocalState # Class: DustLocalState ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustLocalState(params): DustLocalState; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### params[​](#params "Direct link to params") [`DustParameters`](/api-reference/ledger/classes/DustParameters.md) #### Returns[​](#returns "Direct link to Returns") `DustLocalState` ## Properties[​](#properties "Direct link to Properties") ### params[​](#params-1 "Direct link to params") ``` readonly params: DustParameters; ``` *** ### syncTime[​](#synctime "Direct link to syncTime") ``` readonly syncTime: Date; ``` *** ### utxos[​](#utxos "Direct link to utxos") ``` readonly utxos: QualifiedDustOutput[]; ``` ## Methods[​](#methods "Direct link to Methods") ### generationInfo()[​](#generationinfo "Direct link to generationInfo()") ``` generationInfo(qdo): | undefined | DustGenerationInfo; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### qdo[​](#qdo "Direct link to qdo") [`QualifiedDustOutput`](/api-reference/ledger/type-aliases/QualifiedDustOutput.md) #### Returns[​](#returns-1 "Direct link to Returns") \| `undefined` | [`DustGenerationInfo`](/api-reference/ledger/type-aliases/DustGenerationInfo.md) *** ### processTtls()[​](#processttls "Direct link to processTtls()") ``` processTtls(time): DustLocalState; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### time[​](#time "Direct link to time") `Date` #### Returns[​](#returns-2 "Direct link to Returns") `DustLocalState` *** ### replayEvents()[​](#replayevents "Direct link to replayEvents()") ``` replayEvents(sk, events): DustLocalState; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### sk[​](#sk "Direct link to sk") [`DustSecretKey`](/api-reference/ledger/classes/DustSecretKey.md) ##### events[​](#events "Direct link to events") [`Event`](/api-reference/ledger/classes/Event.md)\[] #### Returns[​](#returns-3 "Direct link to Returns") `DustLocalState` *** ### replayEventsWithChanges()[​](#replayeventswithchanges "Direct link to replayEventsWithChanges()") ``` replayEventsWithChanges(sk, events): DustLocalStateWithChanges; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### sk[​](#sk-1 "Direct link to sk") [`DustSecretKey`](/api-reference/ledger/classes/DustSecretKey.md) ##### events[​](#events-1 "Direct link to events") [`Event`](/api-reference/ledger/classes/Event.md)\[] #### Returns[​](#returns-4 "Direct link to Returns") [`DustLocalStateWithChanges`](/api-reference/ledger/classes/DustLocalStateWithChanges.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-5 "Direct link to Returns") `Uint8Array` *** ### spend()[​](#spend "Direct link to spend()") ``` spend( sk, utxo, vFee, ctime): [DustLocalState, DustSpend]; ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### sk[​](#sk-2 "Direct link to sk") [`DustSecretKey`](/api-reference/ledger/classes/DustSecretKey.md) ##### utxo[​](#utxo "Direct link to utxo") [`QualifiedDustOutput`](/api-reference/ledger/type-aliases/QualifiedDustOutput.md) ##### vFee[​](#vfee "Direct link to vFee") `bigint` ##### ctime[​](#ctime "Direct link to ctime") `Date` #### Returns[​](#returns-6 "Direct link to Returns") \[`DustLocalState`, [`DustSpend`](/api-reference/ledger/classes/DustSpend.md)<[`PreProof`](/api-reference/ledger/classes/PreProof.md)>] *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-7 "Direct link to Returns") `string` *** ### walletBalance()[​](#walletbalance "Direct link to walletBalance()") ``` walletBalance(time): bigint; ``` #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### time[​](#time-1 "Direct link to time") `Date` #### Returns[​](#returns-8 "Direct link to Returns") `bigint` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): DustLocalState; ``` #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-9 "Direct link to Returns") `DustLocalState` --- # DustLocalStateWithChanges > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustLocalStateWithChanges # Class: DustLocalStateWithChanges ## Properties[​](#properties "Direct link to Properties") ### changes[​](#changes "Direct link to changes") ``` readonly changes: DustStateChanges[]; ``` The state changes that occurred during the replay *** ### state[​](#state "Direct link to state") ``` readonly state: DustLocalState; ``` The updated local state after replaying events --- # DustParameters > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustParameters # Class: DustParameters ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustParameters( nightDustRatio, generationDecayRate, dustGracePeriodSeconds): DustParameters; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### nightDustRatio[​](#nightdustratio "Direct link to nightDustRatio") `bigint` ##### generationDecayRate[​](#generationdecayrate "Direct link to generationDecayRate") `bigint` ##### dustGracePeriodSeconds[​](#dustgraceperiodseconds "Direct link to dustGracePeriodSeconds") `bigint` #### Returns[​](#returns "Direct link to Returns") `DustParameters` ## Properties[​](#properties "Direct link to Properties") ### dustGracePeriodSeconds[​](#dustgraceperiodseconds-1 "Direct link to dustGracePeriodSeconds") ``` dustGracePeriodSeconds: bigint; ``` *** ### generationDecayRate[​](#generationdecayrate-1 "Direct link to generationDecayRate") ``` generationDecayRate: bigint; ``` *** ### nightDustRatio[​](#nightdustratio-1 "Direct link to nightDustRatio") ``` nightDustRatio: bigint; ``` *** ### timeToCapSeconds[​](#timetocapseconds "Direct link to timeToCapSeconds") ``` readonly timeToCapSeconds: bigint; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): DustParameters; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `DustParameters` --- # DustRegistration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustRegistration # Class: DustRegistration\ ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustRegistration( markerS, nightKey, dustAddress, allowFeePayment, signature?): DustRegistration; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### markerS[​](#markers "Direct link to markerS") `S`\[`"instance"`] ##### nightKey[​](#nightkey "Direct link to nightKey") `string` ##### dustAddress[​](#dustaddress "Direct link to dustAddress") `undefined` | `bigint` ##### allowFeePayment[​](#allowfeepayment "Direct link to allowFeePayment") `bigint` ##### signature?[​](#signature "Direct link to signature?") `S` #### Returns[​](#returns "Direct link to Returns") `DustRegistration`<`S`> ## Properties[​](#properties "Direct link to Properties") ### allowFeePayment[​](#allowfeepayment-1 "Direct link to allowFeePayment") ``` allowFeePayment: bigint; ``` *** ### dustAddress[​](#dustaddress-1 "Direct link to dustAddress") ``` dustAddress: undefined | bigint; ``` *** ### nightKey[​](#nightkey-1 "Direct link to nightKey") ``` nightKey: string; ``` *** ### signature[​](#signature-1 "Direct link to signature") ``` signature: S; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(markerS, raw): DustRegistration; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### S[​](#s-1 "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### markerS[​](#markers-1 "Direct link to markerS") `S`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `DustRegistration`<`S`> --- # DustSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustSecretKey # Class: DustSecretKey A secret key for the Dust, used to derive Dust UTxO nonces and prove credentials to spend Dust UTxOs ## Properties[​](#properties "Direct link to Properties") ### publicKey[​](#publickey "Direct link to publicKey") ``` publicKey: bigint; ``` ## Methods[​](#methods "Direct link to Methods") ### clear()[​](#clear "Direct link to clear()") ``` clear(): void; ``` Clears the dust secret key, so that it is no longer usable nor held in memory #### Returns[​](#returns "Direct link to Returns") `void` *** ### fromBigint()[​](#frombigint "Direct link to fromBigint()") ``` static fromBigint(bigint): DustSecretKey; ``` Temporary method to create an instance of DustSecretKey from a bigint (its natural representation) #### Parameters[​](#parameters "Direct link to Parameters") ##### bigint[​](#bigint "Direct link to bigint") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `DustSecretKey` *** ### fromSeed()[​](#fromseed "Direct link to fromSeed()") ``` static fromSeed(seed): DustSecretKey; ``` Create an instance of DustSecretKey from a seed. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### seed[​](#seed "Direct link to seed") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `DustSecretKey` --- # DustSpend > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustSpend # Class: DustSpend\

## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Properties[​](#properties "Direct link to Properties") ### newCommitment[​](#newcommitment "Direct link to newCommitment") ``` readonly newCommitment: bigint; ``` *** ### oldNullifier[​](#oldnullifier "Direct link to oldNullifier") ``` readonly oldNullifier: bigint; ``` *** ### proof[​](#proof "Direct link to proof") ``` readonly proof: P; ``` *** ### vFee[​](#vfee "Direct link to vFee") ``` readonly vFee: bigint; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize

(markerP, raw): DustSpend

; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `DustSpend`<`P`> --- # DustState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustState # Class: DustState ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustState(): DustState; ``` #### Returns[​](#returns "Direct link to Returns") `DustState` ## Properties[​](#properties "Direct link to Properties") ### generation[​](#generation "Direct link to generation") ``` readonly generation: DustGenerationState; ``` *** ### utxo[​](#utxo "Direct link to utxo") ``` readonly utxo: DustUtxoState; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): DustState; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `DustState` --- # DustStateChanges > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustStateChanges # Class: DustStateChanges ## Properties[​](#properties "Direct link to Properties") ### receivedUtxos[​](#receivedutxos "Direct link to receivedUtxos") ``` readonly receivedUtxos: QualifiedDustOutput[]; ``` The UTXOs that were received in this state change *** ### source[​](#source "Direct link to source") ``` readonly source: string; ``` The source of the state change, as a hex-encoded string *** ### spentUtxos[​](#spentutxos "Direct link to spentUtxos") ``` readonly spentUtxos: QualifiedDustOutput[]; ``` The UTXOs that were spent in this state change --- # DustUtxoState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustUtxoState # Class: DustUtxoState ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new DustUtxoState(): DustUtxoState; ``` #### Returns[​](#returns "Direct link to Returns") `DustUtxoState` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): DustUtxoState; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `DustUtxoState` --- # EncryptionSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / EncryptionSecretKey # Class: EncryptionSecretKey Holds the encryption secret key of a user, which may be used to determine if a given offer contains outputs addressed to this user ## Methods[​](#methods "Direct link to Methods") ### clear()[​](#clear "Direct link to clear()") ``` clear(): void; ``` Clears the encryption secret key, so that it is no longer usable nor held in memory #### Returns[​](#returns "Direct link to Returns") `void` *** ### test()[​](#test "Direct link to test()") ``` test

(offer): boolean; ``` #### Type Parameters[​](#type-parameters "Direct link to Type Parameters") ##### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters "Direct link to Parameters") ##### offer[​](#offer "Direct link to offer") [`ZswapOffer`](/api-reference/ledger/classes/ZswapOffer.md)<`P`> #### Returns[​](#returns-1 "Direct link to Returns") `boolean` *** ### yesIKnowTheSecurityImplicationsOfThis\_serialize()[​](#yesiknowthesecurityimplicationsofthis_serialize "Direct link to yesIKnowTheSecurityImplicationsOfThis_serialize()") ``` yesIKnowTheSecurityImplicationsOfThis_serialize(): Uint8Array; ``` #### Returns[​](#returns-2 "Direct link to Returns") `Uint8Array` *** ### yesIKnowTheSecurityImplicationsOfThis\_taggedSerialize()[​](#yesiknowthesecurityimplicationsofthis_taggedserialize "Direct link to yesIKnowTheSecurityImplicationsOfThis_taggedSerialize()") ``` yesIKnowTheSecurityImplicationsOfThis_taggedSerialize(): Uint8Array; ``` #### Returns[​](#returns-3 "Direct link to Returns") `Uint8Array` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): EncryptionSecretKey; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-4 "Direct link to Returns") `EncryptionSecretKey` *** ### taggedDeserialize()[​](#taggeddeserialize "Direct link to taggedDeserialize()") ``` static taggedDeserialize(raw): EncryptionSecretKey; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw-1 "Direct link to raw") `Uint8Array` #### Returns[​](#returns-5 "Direct link to Returns") `EncryptionSecretKey` --- # Event > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Event # Class: Event An event emitted by the ledger ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): Event; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `Event` --- # Intent > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Intent # Class: Intent\ An intent is a potentially unbalanced partial transaction, that may be combined with other intents to form a whole. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ### B[​](#b "Direct link to B") `B` *extends* [`Bindingish`](/api-reference/ledger/type-aliases/Bindingish.md) ## Properties[​](#properties "Direct link to Properties") ### actions[​](#actions "Direct link to actions") ``` actions: ContractAction

[]; ``` The action sequence of this intent. #### Throws[​](#throws "Direct link to Throws") Writing throws if `B` is [Binding](/api-reference/ledger/classes/Binding.md). *** ### binding[​](#binding "Direct link to binding") ``` readonly binding: B; ``` *** ### dustActions[​](#dustactions "Direct link to dustActions") ``` dustActions: undefined | DustActions; ``` The DUST interactions made by this intent #### Throws[​](#throws-1 "Direct link to Throws") Writing throws if `B` is [Binding](/api-reference/ledger/classes/Binding.md). *** ### fallibleUnshieldedOffer[​](#fallibleunshieldedoffer "Direct link to fallibleUnshieldedOffer") ``` fallibleUnshieldedOffer: undefined | UnshieldedOffer; ``` The UTXO inputs and outputs in the fallible section of this intent. #### Throws[​](#throws-2 "Direct link to Throws") Writing throws if `B` is [Binding](/api-reference/ledger/classes/Binding.md), unless the only change is in the signature set. *** ### guaranteedUnshieldedOffer[​](#guaranteedunshieldedoffer "Direct link to guaranteedUnshieldedOffer") ``` guaranteedUnshieldedOffer: undefined | UnshieldedOffer; ``` The UTXO inputs and outputs in the guaranteed section of this intent. #### Throws[​](#throws-3 "Direct link to Throws") Writing throws if `B` is [Binding](/api-reference/ledger/classes/Binding.md), unless the only change is in the signature set. *** ### ttl[​](#ttl "Direct link to ttl") ``` ttl: Date; ``` The time this intent expires. #### Throws[​](#throws-4 "Direct link to Throws") Writing throws if `B` is [Binding](/api-reference/ledger/classes/Binding.md). ## Methods[​](#methods "Direct link to Methods") ### addCall()[​](#addcall "Direct link to addCall()") ``` addCall(call): Intent; ``` Adds a contract call to this intent. #### Parameters[​](#parameters "Direct link to Parameters") ##### call[​](#call "Direct link to call") [`ContractCallPrototype`](/api-reference/ledger/classes/ContractCallPrototype.md) #### Returns[​](#returns "Direct link to Returns") `Intent`<`S`, [`PreProof`](/api-reference/ledger/classes/PreProof.md), [`PreBinding`](/api-reference/ledger/classes/PreBinding.md)> *** ### addDeploy()[​](#adddeploy "Direct link to addDeploy()") ``` addDeploy(deploy): Intent; ``` Adds a contract deploy to this intent. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### deploy[​](#deploy "Direct link to deploy") [`ContractDeploy`](/api-reference/ledger/classes/ContractDeploy.md) #### Returns[​](#returns-1 "Direct link to Returns") `Intent`<`S`, [`PreProof`](/api-reference/ledger/classes/PreProof.md), [`PreBinding`](/api-reference/ledger/classes/PreBinding.md)> *** ### addMaintenanceUpdate()[​](#addmaintenanceupdate "Direct link to addMaintenanceUpdate()") ``` addMaintenanceUpdate(update): Intent; ``` Adds a maintenance update to this intent. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### update[​](#update "Direct link to update") [`MaintenanceUpdate`](/api-reference/ledger/classes/MaintenanceUpdate.md) #### Returns[​](#returns-2 "Direct link to Returns") `Intent`<`S`, [`PreProof`](/api-reference/ledger/classes/PreProof.md), [`PreBinding`](/api-reference/ledger/classes/PreBinding.md)> *** ### bind()[​](#bind "Direct link to bind()") ``` bind(segmentId): Intent; ``` Enforces binding for this intent. This is irreversible. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### segmentId[​](#segmentid "Direct link to segmentId") `number` #### Returns[​](#returns-3 "Direct link to Returns") `Intent`<`S`, `P`, [`Binding`](/api-reference/ledger/classes/Binding.md)> #### Throws[​](#throws-5 "Direct link to Throws") If `segmentId` is not a valid segment ID. *** ### eraseProofs()[​](#eraseproofs "Direct link to eraseProofs()") ``` eraseProofs(): Intent; ``` Removes proofs from this intent. #### Returns[​](#returns-4 "Direct link to Returns") `Intent`<`S`, [`NoProof`](/api-reference/ledger/classes/NoProof.md), [`NoBinding`](/api-reference/ledger/classes/NoBinding.md)> *** ### eraseSignatures()[​](#erasesignatures "Direct link to eraseSignatures()") ``` eraseSignatures(): Intent; ``` Removes signatures from this intent. #### Returns[​](#returns-5 "Direct link to Returns") `Intent`<[`SignatureErased`](/api-reference/ledger/classes/SignatureErased.md), `P`, `B`> *** ### intentHash()[​](#intenthash "Direct link to intentHash()") ``` intentHash(segmentId): string; ``` Returns the hash of this intent, for it's given segment ID. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### segmentId[​](#segmentid-1 "Direct link to segmentId") `number` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-7 "Direct link to Returns") `Uint8Array` *** ### signatureData()[​](#signaturedata "Direct link to signatureData()") ``` signatureData(segmentId): Uint8Array; ``` The raw data that is signed for unshielded inputs in this intent. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### segmentId[​](#segmentid-2 "Direct link to segmentId") `number` #### Returns[​](#returns-8 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-9 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize( markerS, markerP, markerB, raw): Intent; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### S[​](#s-1 "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ##### B[​](#b-1 "Direct link to B") `B` *extends* [`Bindingish`](/api-reference/ledger/type-aliases/Bindingish.md) #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### markerS[​](#markers "Direct link to markerS") `S`\[`"instance"`] ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### markerB[​](#markerb "Direct link to markerB") `B`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-10 "Direct link to Returns") `Intent`<`S`, `P`, `B`> *** ### new()[​](#new "Direct link to new()") ``` static new(ttl): UnprovenIntent; ``` #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### ttl[​](#ttl-1 "Direct link to ttl") `Date` #### Returns[​](#returns-11 "Direct link to Returns") [`UnprovenIntent`](/api-reference/ledger/type-aliases/UnprovenIntent.md) --- # LedgerParameters > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / LedgerParameters # Class: LedgerParameters Parameters used by the Midnight ledger, including transaction fees and bounds ## Properties[​](#properties "Direct link to Properties") ### dust[​](#dust "Direct link to dust") ``` readonly dust: DustParameters; ``` The parameters associated with DUST. *** ### feePrices[​](#feeprices "Direct link to feePrices") ``` readonly feePrices: FeePrices; ``` The fee prices for transaction *** ### transactionCostModel[​](#transactioncostmodel "Direct link to transactionCostModel") ``` readonly transactionCostModel: TransactionCostModel; ``` The cost model used for transaction fees contained in these parameters ## Methods[​](#methods "Direct link to Methods") ### maxPriceAdjustment()[​](#maxpriceadjustment "Direct link to maxPriceAdjustment()") ``` maxPriceAdjustment(): number; ``` The maximum price adjustment per block with the current parameters, as a multiplicative factor (that is: 1.1 would indicate a 10% adjustment). Will always return the positive (>1) adjustment factor. Note that negative adjustments are the additive inverse (1.1 has a corresponding 0.9 downward adjustment), *not* the multiplicative as might reasonably be assumed. #### Returns[​](#returns "Direct link to Returns") `number` *** ### normalizeFullness()[​](#normalizefullness "Direct link to normalizeFullness()") ``` normalizeFullness(fullness): NormalizedCost; ``` Normalizes a detailed block fullness cost to the block limits. #### Parameters[​](#parameters "Direct link to Parameters") ##### fullness[​](#fullness "Direct link to fullness") [`SyntheticCost`](/api-reference/ledger/type-aliases/SyntheticCost.md) #### Returns[​](#returns-1 "Direct link to Returns") [`NormalizedCost`](/api-reference/ledger/type-aliases/NormalizedCost.md) #### Throws[​](#throws "Direct link to Throws") if any of the block limits is exceeded *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-2 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-3 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): LedgerParameters; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-4 "Direct link to Returns") `LedgerParameters` *** ### initialParameters()[​](#initialparameters "Direct link to initialParameters()") ``` static initialParameters(): LedgerParameters; ``` The initial parameters of Midnight #### Returns[​](#returns-5 "Direct link to Returns") `LedgerParameters` --- # LedgerState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / LedgerState # Class: LedgerState The state of the Midnight ledger ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new LedgerState(network_id, zswap): LedgerState; ``` Intializes from a Zswap state, with an empty contract set #### Parameters[​](#parameters "Direct link to Parameters") ##### network\_id[​](#network_id "Direct link to network_id") `string` ##### zswap[​](#zswap "Direct link to zswap") [`ZswapChainState`](/api-reference/ledger/classes/ZswapChainState.md) #### Returns[​](#returns "Direct link to Returns") `LedgerState` ## Properties[​](#properties "Direct link to Properties") ### blockRewardPool[​](#blockrewardpool "Direct link to blockRewardPool") ``` readonly blockRewardPool: bigint; ``` The remaining unrewarded supply of native tokens. *** ### dust[​](#dust "Direct link to dust") ``` readonly dust: DustState; ``` The dust subsystem state *** ### lockedPool[​](#lockedpool "Direct link to lockedPool") ``` readonly lockedPool: bigint; ``` The remaining size of the locked Night pool. *** ### parameters[​](#parameters-1 "Direct link to parameters") ``` parameters: LedgerParameters; ``` The parameters of the ledger *** ### reservePool[​](#reservepool "Direct link to reservePool") ``` readonly reservePool: bigint; ``` The size of the reserve Night pool *** ### utxo[​](#utxo "Direct link to utxo") ``` readonly utxo: UtxoState; ``` The unshielded utxos present *** ### zswap[​](#zswap-1 "Direct link to zswap") ``` readonly zswap: ZswapChainState; ``` The Zswap part of the ledger state ## Methods[​](#methods "Direct link to Methods") ### apply()[​](#apply "Direct link to apply()") ``` apply(transaction, context): [LedgerState, TransactionResult]; ``` Applies a [Transaction](/api-reference/ledger/classes/Transaction.md) #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### transaction[​](#transaction "Direct link to transaction") [`VerifiedTransaction`](/api-reference/ledger/classes/VerifiedTransaction.md) ##### context[​](#context "Direct link to context") [`TransactionContext`](/api-reference/ledger/classes/TransactionContext.md) #### Returns[​](#returns-1 "Direct link to Returns") \[`LedgerState`, [`TransactionResult`](/api-reference/ledger/classes/TransactionResult.md)] *** ### applySystemTx()[​](#applysystemtx "Direct link to applySystemTx()") ``` applySystemTx(transaction, tblock): [LedgerState, Event[]]; ``` Applies a system transaction to this ledger state. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### transaction[​](#transaction-1 "Direct link to transaction") [`SystemTransaction`](/api-reference/ledger/classes/SystemTransaction.md) ##### tblock[​](#tblock "Direct link to tblock") `Date` #### Returns[​](#returns-2 "Direct link to Returns") \[`LedgerState`, [`Event`](/api-reference/ledger/classes/Event.md)\[]] *** ### bridgeReceiving()[​](#bridgereceiving "Direct link to bridgeReceiving()") #### Call Signature[​](#call-signature "Direct link to Call Signature") ``` bridgeReceiving(recipient): bigint; ``` How much in bridged night a recipient is owed and can claim. ##### Parameters[​](#parameters-4 "Direct link to Parameters") ###### recipient[​](#recipient "Direct link to recipient") `string` ##### Returns[​](#returns-3 "Direct link to Returns") `bigint` #### Call Signature[​](#call-signature-1 "Direct link to Call Signature") ``` bridgeReceiving(recipient): bigint; ``` How much in bridged night a recipient is owed and can claim. ##### Parameters[​](#parameters-5 "Direct link to Parameters") ###### recipient[​](#recipient-1 "Direct link to recipient") `string` ##### Returns[​](#returns-4 "Direct link to Returns") `bigint` *** ### index()[​](#index "Direct link to index()") ``` index(address): undefined | ContractState; ``` Indexes into the contract state map with a given contract address #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### address[​](#address "Direct link to address") `string` #### Returns[​](#returns-5 "Direct link to Returns") `undefined` | [`ContractState`](/api-reference/ledger/classes/ContractState.md) *** ### postBlockUpdate()[​](#postblockupdate "Direct link to postBlockUpdate()") ``` postBlockUpdate( tblock, detailedBlockFullness?, overallBlockFullness?): LedgerState; ``` Carries out a post-block update, which does amortized bookkeeping that only needs to be done once per state change. Typically, `postBlockUpdate` should be run after any (sequence of) (system)-transaction application(s). #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### tblock[​](#tblock-1 "Direct link to tblock") `Date` ##### detailedBlockFullness?[​](#detailedblockfullness "Direct link to detailedBlockFullness?") [`NormalizedCost`](/api-reference/ledger/type-aliases/NormalizedCost.md) ##### overallBlockFullness?[​](#overallblockfullness "Direct link to overallBlockFullness?") `number` #### Returns[​](#returns-6 "Direct link to Returns") `LedgerState` *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-7 "Direct link to Returns") `Uint8Array` *** ### testingDistributeNight()[​](#testingdistributenight "Direct link to testingDistributeNight()") ``` testingDistributeNight( recipient, amount, tblock): LedgerState; ``` Allows distributing the specified amount of Night to the recipient's address. Use is for testing purposes only. #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### recipient[​](#recipient-2 "Direct link to recipient") `string` ##### amount[​](#amount "Direct link to amount") `bigint` ##### tblock[​](#tblock-2 "Direct link to tblock") `Date` #### Returns[​](#returns-8 "Direct link to Returns") `LedgerState` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-9 "Direct link to Returns") `string` *** ### treasuryBalance()[​](#treasurybalance "Direct link to treasuryBalance()") ``` treasuryBalance(token_type): bigint; ``` Retrieves the balance of the treasury for a specific token type. #### Parameters[​](#parameters-10 "Direct link to Parameters") ##### token\_type[​](#token_type "Direct link to token_type") [`TokenType`](/api-reference/ledger/type-aliases/TokenType.md) #### Returns[​](#returns-10 "Direct link to Returns") `bigint` *** ### unclaimedBlockRewards()[​](#unclaimedblockrewards "Direct link to unclaimedBlockRewards()") ``` unclaimedBlockRewards(recipient): bigint; ``` How much in block rewards a recipient is owed and can claim. #### Parameters[​](#parameters-11 "Direct link to Parameters") ##### recipient[​](#recipient-3 "Direct link to recipient") `string` #### Returns[​](#returns-11 "Direct link to Returns") `bigint` *** ### updateIndex()[​](#updateindex "Direct link to updateIndex()") ``` updateIndex( address, state, balance): LedgerState; ``` Sets the state of a given contract address from a [ChargedState](/api-reference/ledger/classes/ChargedState.md) #### Parameters[​](#parameters-12 "Direct link to Parameters") ##### address[​](#address-1 "Direct link to address") `string` ##### state[​](#state "Direct link to state") [`ChargedState`](/api-reference/ledger/classes/ChargedState.md) ##### balance[​](#balance "Direct link to balance") `Map`<[`TokenType`](/api-reference/ledger/type-aliases/TokenType.md), `bigint`> #### Returns[​](#returns-12 "Direct link to Returns") `LedgerState` *** ### blank()[​](#blank "Direct link to blank()") ``` static blank(network_id): LedgerState; ``` A fully blank state #### Parameters[​](#parameters-13 "Direct link to Parameters") ##### network\_id[​](#network_id-1 "Direct link to network_id") `string` #### Returns[​](#returns-13 "Direct link to Returns") `LedgerState` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): LedgerState; ``` #### Parameters[​](#parameters-14 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-14 "Direct link to Returns") `LedgerState` --- # MaintenanceUpdate > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / MaintenanceUpdate # Class: MaintenanceUpdate A contract maintenance update, updating associated operations, or changing the maintenance authority. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new MaintenanceUpdate( address, updates, counter): MaintenanceUpdate; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### address[​](#address "Direct link to address") `string` ##### updates[​](#updates "Direct link to updates") [`SingleUpdate`](/api-reference/ledger/type-aliases/SingleUpdate.md)\[] ##### counter[​](#counter "Direct link to counter") `bigint` #### Returns[​](#returns "Direct link to Returns") `MaintenanceUpdate` ## Properties[​](#properties "Direct link to Properties") ### address[​](#address-1 "Direct link to address") ``` readonly address: string; ``` The address this deployment will attempt to create *** ### counter[​](#counter-1 "Direct link to counter") ``` readonly counter: bigint; ``` The counter this update is valid against *** ### dataToSign[​](#datatosign "Direct link to dataToSign") ``` readonly dataToSign: Uint8Array; ``` The raw data any valid signature must be over to approve this update. *** ### signatures[​](#signatures "Direct link to signatures") ``` readonly signatures: [bigint, string][]; ``` The signatures on this update *** ### updates[​](#updates-1 "Direct link to updates") ``` readonly updates: SingleUpdate[]; ``` The updates to carry out ## Methods[​](#methods "Direct link to Methods") ### addSignature()[​](#addsignature "Direct link to addSignature()") ``` addSignature(idx, signature): MaintenanceUpdate; ``` Adds a new signature to this update #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### idx[​](#idx "Direct link to idx") `bigint` ##### signature[​](#signature "Direct link to signature") `string` #### Returns[​](#returns-1 "Direct link to Returns") `MaintenanceUpdate` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` --- # MerkleTreeCollapsedUpdate > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / MerkleTreeCollapsedUpdate # Class: MerkleTreeCollapsedUpdate A compact delta on the coin commitments Merkle tree, used to keep local spending trees in sync with the global state without requiring receiving all transactions. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new MerkleTreeCollapsedUpdate( state, start, end): MerkleTreeCollapsedUpdate; ``` Create a new compact update from a non-compact state, and inclusive `start` and `end` indices #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`ZswapChainState`](/api-reference/ledger/classes/ZswapChainState.md) ##### start[​](#start "Direct link to start") `bigint` ##### end[​](#end "Direct link to end") `bigint` #### Returns[​](#returns "Direct link to Returns") `MerkleTreeCollapsedUpdate` #### Throws[​](#throws "Direct link to Throws") If the indices are out-of-bounds for the state, or `end < start` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): MerkleTreeCollapsedUpdate; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `MerkleTreeCollapsedUpdate` --- # NoBinding > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / NoBinding # Class: NoBinding ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new NoBinding(data): NoBinding; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### data[​](#data "Direct link to data") `String` #### Returns[​](#returns "Direct link to Returns") `NoBinding` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` instance: "no-binding"; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): NoBinding; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `NoBinding` --- # NoProof > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / NoProof # Class: NoProof A unit type used to indicate the absence of proofs. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new NoProof(): NoProof; ``` #### Returns[​](#returns "Direct link to Returns") `NoProof` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` instance: "no-proof"; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # PreBinding > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / PreBinding # Class: PreBinding Information that will be used to bind an [Intent](/api-reference/ledger/classes/Intent.md) in the future, but does not yet prevent modification of it. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new PreBinding(data): PreBinding; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### data[​](#data "Direct link to data") `String` #### Returns[​](#returns "Direct link to Returns") `PreBinding` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` instance: "pre-binding"; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): PreBinding; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `PreBinding` --- # PrePartitionContractCall > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / PrePartitionContractCall # Class: PrePartitionContractCall A [ContractCall](/api-reference/ledger/classes/ContractCall.md) prior to being partitioned into guarnateed and fallible parts, for use with [Transaction.addCalls](/api-reference/ledger/classes/Transaction.md#addcalls). Note that this is similar, but not the same as [ContractCall](/api-reference/ledger/classes/ContractCall.md), which assumes [partitionTranscripts](/api-reference/ledger/functions/partitionTranscripts.md) was already used. [Transaction.addCalls](/api-reference/ledger/classes/Transaction.md#addcalls) is a replacement for this that also handles Zswap components, and creates relevant intents when needed. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new PrePartitionContractCall( address, entry_point, op, pre_transcript, private_transcript_outputs, input, output, communication_commitment_rand, key_location): PrePartitionContractCall; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### address[​](#address "Direct link to address") `string` ##### entry\_point[​](#entry_point "Direct link to entry_point") `string` | `Uint8Array`<`ArrayBufferLike`> ##### op[​](#op "Direct link to op") [`ContractOperation`](/api-reference/ledger/classes/ContractOperation.md) ##### pre\_transcript[​](#pre_transcript "Direct link to pre_transcript") [`PreTranscript`](/api-reference/ledger/classes/PreTranscript.md) ##### private\_transcript\_outputs[​](#private_transcript_outputs "Direct link to private_transcript_outputs") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)\[] ##### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ##### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ##### communication\_commitment\_rand[​](#communication_commitment_rand "Direct link to communication_commitment_rand") `string` ##### key\_location[​](#key_location "Direct link to key_location") `string` #### Returns[​](#returns "Direct link to Returns") `PrePartitionContractCall` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # PreProof > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / PreProof # Class: PreProof The preimage, or data required to produce, a [Proof](/api-reference/ledger/classes/Proof.md). ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new PreProof(data): PreProof; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### data[​](#data "Direct link to data") `String` #### Returns[​](#returns "Direct link to Returns") `PreProof` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` instance: "pre-proof"; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): PreProof; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `PreProof` --- # PreTranscript > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / PreTranscript # Class: PreTranscript A transcript prior to partitioning, consisting of the context to run it in, the program that will make up the transcript, and optionally a communication commitment to bind calls together. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new PreTranscript( context, program, comm_comm?): PreTranscript; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### context[​](#context "Direct link to context") [`QueryContext`](/api-reference/ledger/classes/QueryContext.md) ##### program[​](#program "Direct link to program") [`Op`](/api-reference/ledger/type-aliases/Op.md)<[`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)>\[] ##### comm\_comm?[​](#comm_comm "Direct link to comm_comm?") `string` #### Returns[​](#returns "Direct link to Returns") `PreTranscript` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # Proof > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Proof # Class: Proof A zero-knowledge proof. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new Proof(data): Proof; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### data[​](#data "Direct link to data") `String` #### Returns[​](#returns "Direct link to Returns") `Proof` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` instance: "proof"; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): Proof; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `Proof` --- # QueryContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / QueryContext # Class: QueryContext Provides the information needed to fully process a transaction, including information about the rest of the transaction, and the state of the chain at the time of execution. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new QueryContext(state, address): QueryContext; ``` Construct a basic context from a contract's address and current state value #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`ChargedState`](/api-reference/ledger/classes/ChargedState.md) ##### address[​](#address "Direct link to address") `string` #### Returns[​](#returns "Direct link to Returns") `QueryContext` ## Properties[​](#properties "Direct link to Properties") ### address[​](#address-1 "Direct link to address") ``` readonly address: string; ``` The address of the contract *** ### block[​](#block "Direct link to block") ``` block: CallContext; ``` The block-level information accessible to the contract *** ### comIndices[​](#comindices "Direct link to comIndices") ``` readonly comIndices: Map; ``` The commitment indices map accessible to the contract, primarily via [qualify](#qualify) *** ### effects[​](#effects "Direct link to effects") ``` effects: Effects; ``` The effects that occurred during execution against this context, should match those declared in a [Transcript](/api-reference/ledger/type-aliases/Transcript.md) *** ### state[​](#state-1 "Direct link to state") ``` readonly state: ChargedState; ``` The current contract state retained in the context ## Methods[​](#methods "Direct link to Methods") ### insertCommitment()[​](#insertcommitment "Direct link to insertCommitment()") ``` insertCommitment(comm, index): QueryContext; ``` Register a given coin commitment as being accessible at a specific index, for use when receiving coins in-contract, and needing to record their index to later spend them #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### comm[​](#comm "Direct link to comm") `string` ##### index[​](#index "Direct link to index") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `QueryContext` *** ### qualify()[​](#qualify "Direct link to qualify()") ``` qualify(coin): undefined | Value; ``` **`Internal`** Internal counterpart to [insertCommitment](#insertcommitment); upgrades an encoded [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) to an encoded [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) using the inserted commitments #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`Value`](/api-reference/ledger/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | [`Value`](/api-reference/ledger/type-aliases/Value.md) *** ### query()[​](#query "Direct link to query()") ``` query( ops, cost_model, gas_limit?): QueryResults; ``` Runs a sequence of operations in gather mode, returning the results of the gather. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### ops[​](#ops "Direct link to ops") [`Op`](/api-reference/ledger/type-aliases/Op.md)<`null`>\[] ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/ledger/classes/CostModel.md) ##### gas\_limit?[​](#gas_limit "Direct link to gas_limit?") [`RunningCost`](/api-reference/ledger/type-aliases/RunningCost.md) #### Returns[​](#returns-3 "Direct link to Returns") [`QueryResults`](/api-reference/ledger/classes/QueryResults.md) *** ### runTranscript()[​](#runtranscript "Direct link to runTranscript()") ``` runTranscript(transcript, cost_model): QueryContext; ``` Runs a transcript in verifying mode against the current query context, outputting a new query context, with the [state](#state) and [effects](#effects) from after the execution. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### transcript[​](#transcript "Direct link to transcript") [`Transcript`](/api-reference/ledger/type-aliases/Transcript.md)<[`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)> ##### cost\_model[​](#cost_model-1 "Direct link to cost_model") [`CostModel`](/api-reference/ledger/classes/CostModel.md) #### Returns[​](#returns-4 "Direct link to Returns") `QueryContext` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` *** ### toVmStack()[​](#tovmstack "Direct link to toVmStack()") ``` toVmStack(): VmStack; ``` Converts the QueryContext to [VmStack](/api-reference/ledger/classes/VmStack.md). #### Returns[​](#returns-6 "Direct link to Returns") [`VmStack`](/api-reference/ledger/classes/VmStack.md) --- # QueryResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / QueryResults # Class: QueryResults The results of making a query against a specific state or context ## Properties[​](#properties "Direct link to Properties") ### context[​](#context "Direct link to context") ``` readonly context: QueryContext; ``` The context state after executing the query. This can be used to execute further queries *** ### events[​](#events "Direct link to events") ``` readonly events: GatherResult[]; ``` Any events/results that occurred during or from the query *** ### gasCost[​](#gascost "Direct link to gasCost") ``` readonly gasCost: RunningCost; ``` The measured cost of executing the query ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # ReplaceAuthority > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ReplaceAuthority # Class: ReplaceAuthority An update instruction to replace the current contract maintenance authority with a new one. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ReplaceAuthority(authority): ReplaceAuthority; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### authority[​](#authority "Direct link to authority") [`ContractMaintenanceAuthority`](/api-reference/ledger/classes/ContractMaintenanceAuthority.md) #### Returns[​](#returns "Direct link to Returns") `ReplaceAuthority` ## Properties[​](#properties "Direct link to Properties") ### authority[​](#authority-1 "Direct link to authority") ``` readonly authority: ContractMaintenanceAuthority; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # SignatureEnabled > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SignatureEnabled # Class: SignatureEnabled ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new SignatureEnabled(data): SignatureEnabled; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### data[​](#data "Direct link to data") `string` #### Returns[​](#returns "Direct link to Returns") `SignatureEnabled` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` readonly instance: "signature"; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): SignatureEnabled; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `SignatureEnabled` --- # SignatureErased > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SignatureErased # Class: SignatureErased ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new SignatureErased(): SignatureErased; ``` #### Returns[​](#returns "Direct link to Returns") `SignatureErased` ## Properties[​](#properties "Direct link to Properties") ### instance[​](#instance "Direct link to instance") ``` readonly instance: "signature-erased"; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # StateBoundedMerkleTree > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / StateBoundedMerkleTree # Class: StateBoundedMerkleTree Represents a fixed-depth Merkle tree storing hashed data, whose preimages are unknown ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new StateBoundedMerkleTree(height): StateBoundedMerkleTree; ``` Create a blank tree with the given height #### Parameters[​](#parameters "Direct link to Parameters") ##### height[​](#height "Direct link to height") `number` #### Returns[​](#returns "Direct link to Returns") `StateBoundedMerkleTree` ## Properties[​](#properties "Direct link to Properties") ### height[​](#height-1 "Direct link to height") ``` readonly height: number; ``` ## Methods[​](#methods "Direct link to Methods") ### collapse()[​](#collapse "Direct link to collapse()") ``` collapse(start, end): StateBoundedMerkleTree; ``` **`Internal`** Erases all but necessary hashes between, and inclusive of, `start` and `end` inidices #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### start[​](#start "Direct link to start") `bigint` ##### end[​](#end "Direct link to end") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `StateBoundedMerkleTree` #### Throws[​](#throws "Direct link to Throws") If the indices are out-of-bounds for the tree, or `end < start` *** ### findPathForLeaf()[​](#findpathforleaf "Direct link to findPathForLeaf()") ``` findPathForLeaf(leaf): undefined | AlignedValue; ``` **`Internal`** Internal implementation of the finding path primitive. Returns undefined if the leaf is not in the tree. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### leaf[​](#leaf "Direct link to leaf") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) *** ### pathForLeaf()[​](#pathforleaf "Direct link to pathForLeaf()") ``` pathForLeaf(index, leaf): AlignedValue; ``` **`Internal`** Internal implementation of the path construction primitive #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### index[​](#index "Direct link to index") `bigint` ##### leaf[​](#leaf-1 "Direct link to leaf") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Throws[​](#throws-1 "Direct link to Throws") If the index is out-of-bounds for the tree *** ### rehash()[​](#rehash "Direct link to rehash()") ``` rehash(): StateBoundedMerkleTree; ``` Rehashes the tree, updating all internal hashes and ensuring all node hashes are present. Necessary because the onchain runtime does not automatically rehash trees. #### Returns[​](#returns-4 "Direct link to Returns") `StateBoundedMerkleTree` *** ### root()[​](#root "Direct link to root()") ``` root(): undefined | AlignedValue; ``` **`Internal`** Internal implementation of the merkle tree root primitive. Returns undefined if the tree has not been fully hashed. #### Returns[​](#returns-5 "Direct link to Returns") `undefined` | [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### update()[​](#update "Direct link to update()") ``` update(index, leaf): StateBoundedMerkleTree; ``` Inserts a value into the Merkle tree, returning the updated tree #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### index[​](#index-1 "Direct link to index") `bigint` ##### leaf[​](#leaf-2 "Direct link to leaf") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Returns[​](#returns-7 "Direct link to Returns") `StateBoundedMerkleTree` #### Throws[​](#throws-2 "Direct link to Throws") If the index is out-of-bounds for the tree --- # StateMap > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / StateMap # Class: StateMap Represents a key-value map, where keys are [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md)s, and values are [StateValue](/api-reference/ledger/classes/StateValue.md)s. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new StateMap(): StateMap; ``` #### Returns[​](#returns "Direct link to Returns") `StateMap` ## Methods[​](#methods "Direct link to Methods") ### get()[​](#get "Direct link to get()") ``` get(key): undefined | StateValue; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### key[​](#key "Direct link to key") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`StateValue`](/api-reference/ledger/classes/StateValue.md) *** ### insert()[​](#insert "Direct link to insert()") ``` insert(key, value): StateMap; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### key[​](#key-1 "Direct link to key") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/ledger/classes/StateValue.md) #### Returns[​](#returns-2 "Direct link to Returns") `StateMap` *** ### keys()[​](#keys "Direct link to keys()") ``` keys(): AlignedValue[]; ``` #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)\[] *** ### remove()[​](#remove "Direct link to remove()") ``` remove(key): StateMap; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### key[​](#key-2 "Direct link to key") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Returns[​](#returns-4 "Direct link to Returns") `StateMap` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` --- # StateValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / StateValue # Class: StateValue Represents the core of a contract's state, and recursively represents each of its components. There are different *classes* of state values: * `null` * Cells of [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md)s * Maps from [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md)s to state values * Bounded Merkle trees containing [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md) leaves * Short (<= 15 element) arrays of state values State values are *immutable*, any operations that mutate states will return a new state instead. ## Methods[​](#methods "Direct link to Methods") ### arrayPush()[​](#arraypush "Direct link to arrayPush()") ``` arrayPush(value): StateValue; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") `StateValue` #### Returns[​](#returns "Direct link to Returns") `StateValue` *** ### asArray()[​](#asarray "Direct link to asArray()") ``` asArray(): undefined | StateValue[]; ``` #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | `StateValue`\[] *** ### asBoundedMerkleTree()[​](#asboundedmerkletree "Direct link to asBoundedMerkleTree()") ``` asBoundedMerkleTree(): undefined | StateBoundedMerkleTree; ``` #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | [`StateBoundedMerkleTree`](/api-reference/ledger/classes/StateBoundedMerkleTree.md) *** ### asCell()[​](#ascell "Direct link to asCell()") ``` asCell(): AlignedValue; ``` #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) *** ### asMap()[​](#asmap "Direct link to asMap()") ``` asMap(): undefined | StateMap; ``` #### Returns[​](#returns-4 "Direct link to Returns") `undefined` | [`StateMap`](/api-reference/ledger/classes/StateMap.md) *** ### encode()[​](#encode "Direct link to encode()") ``` encode(): EncodedStateValue; ``` **`Internal`** #### Returns[​](#returns-5 "Direct link to Returns") [`EncodedStateValue`](/api-reference/ledger/type-aliases/EncodedStateValue.md) *** ### logSize()[​](#logsize "Direct link to logSize()") ``` logSize(): number; ``` #### Returns[​](#returns-6 "Direct link to Returns") `number` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-7 "Direct link to Returns") `string` *** ### type()[​](#type "Direct link to type()") ``` type(): "map" | "null" | "cell" | "array" | "boundedMerkleTree"; ``` #### Returns[​](#returns-8 "Direct link to Returns") `"map"` | `"null"` | `"cell"` | `"array"` | `"boundedMerkleTree"` *** ### decode()[​](#decode "Direct link to decode()") ``` static decode(value): StateValue; ``` **`Internal`** #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`EncodedStateValue`](/api-reference/ledger/type-aliases/EncodedStateValue.md) #### Returns[​](#returns-9 "Direct link to Returns") `StateValue` *** ### newArray()[​](#newarray "Direct link to newArray()") ``` static newArray(): StateValue; ``` #### Returns[​](#returns-10 "Direct link to Returns") `StateValue` *** ### newBoundedMerkleTree()[​](#newboundedmerkletree "Direct link to newBoundedMerkleTree()") ``` static newBoundedMerkleTree(tree): StateValue; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### tree[​](#tree "Direct link to tree") [`StateBoundedMerkleTree`](/api-reference/ledger/classes/StateBoundedMerkleTree.md) #### Returns[​](#returns-11 "Direct link to Returns") `StateValue` *** ### newCell()[​](#newcell "Direct link to newCell()") ``` static newCell(value): StateValue; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### value[​](#value-2 "Direct link to value") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### Returns[​](#returns-12 "Direct link to Returns") `StateValue` *** ### newMap()[​](#newmap "Direct link to newMap()") ``` static newMap(map): StateValue; ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### map[​](#map "Direct link to map") [`StateMap`](/api-reference/ledger/classes/StateMap.md) #### Returns[​](#returns-13 "Direct link to Returns") `StateValue` *** ### newNull()[​](#newnull "Direct link to newNull()") ``` static newNull(): StateValue; ``` #### Returns[​](#returns-14 "Direct link to Returns") `StateValue` --- # SystemTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SystemTransaction # Class: SystemTransaction A privileged transaction issued by the system. ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): SystemTransaction; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `SystemTransaction` --- # Transaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Transaction # Class: Transaction\ A Midnight transaction, consisting a section of [ContractAction](/api-reference/ledger/type-aliases/ContractAction.md)s, and a guaranteed and fallible [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md). The guaranteed section are run first, and fee payment is taken during this part. If it succeeds, the fallible section is also run, and atomically rolled back if it fails. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ### B[​](#b "Direct link to B") `B` *extends* [`Bindingish`](/api-reference/ledger/type-aliases/Bindingish.md) ## Properties[​](#properties "Direct link to Properties") ### bindingRandomness[​](#bindingrandomness "Direct link to bindingRandomness") ``` readonly bindingRandomness: bigint; ``` The binding randomness associated with this transaction *** ### fallibleOffer[​](#fallibleoffer "Direct link to fallibleOffer") ``` fallibleOffer: undefined | Map>; ``` The fallible Zswap offer Note that writing to this re-computes binding information if and only if this transaction is unbound *and* unproven. If this is not the case, creating or removing offer components will lead to a binding error down the line. #### Throws[​](#throws "Direct link to Throws") On writing if `B` is [Binding](/api-reference/ledger/classes/Binding.md) or this is not a standard transaction *** ### guaranteedOffer[​](#guaranteedoffer "Direct link to guaranteedOffer") ``` guaranteedOffer: undefined | ZswapOffer

; ``` The guaranteed Zswap offer Note that writing to this re-computes binding information if and only if this transaction is unbound *and* unproven. If this is not the case, creating or removing offer components will lead to a binding error down the line. #### Throws[​](#throws-1 "Direct link to Throws") On writing if `B` is [Binding](/api-reference/ledger/classes/Binding.md) or this is not a standard transaction *** ### intents[​](#intents "Direct link to intents") ``` intents: undefined | Map>; ``` The intents contained in this transaction Note that writing to this re-computes binding information if and only if this transaction is unbound *and* unproven. If this is not the case, creating or removing intents will lead to a binding error down the line, but modifying existing intents will succeed. #### Throws[​](#throws-2 "Direct link to Throws") On writing if `B` is [Binding](/api-reference/ledger/classes/Binding.md) or this is not a standard transaction *** ### rewards[​](#rewards "Direct link to rewards") ``` readonly rewards: | undefined | ClaimRewardsTransaction; ``` The rewards this transaction represents, if applicable ## Methods[​](#methods "Direct link to Methods") ### addCalls()[​](#addcalls "Direct link to addCalls()") ``` addCalls( segment, calls, params, ttl, zswapInputs?, zswapOutputs?, zswapTransient?): Transaction; ``` Adds a set of new calls to the transaction. In contrast to [Intent.addCall](/api-reference/ledger/classes/Intent.md#addcall), this takes calls *before* transcript partitioning ([partitionTranscripts](/api-reference/ledger/functions/partitionTranscripts.md)), will create the target intent where needed, and will ensure that relevant Zswap parts are placed in the same section as contract interactions with them. #### Parameters[​](#parameters "Direct link to Parameters") ##### segment[​](#segment "Direct link to segment") [`SegmentSpecifier`](/api-reference/ledger/type-aliases/SegmentSpecifier.md) ##### calls[​](#calls "Direct link to calls") [`PrePartitionContractCall`](/api-reference/ledger/classes/PrePartitionContractCall.md)\[] ##### params[​](#params "Direct link to params") [`LedgerParameters`](/api-reference/ledger/classes/LedgerParameters.md) ##### ttl[​](#ttl "Direct link to ttl") `Date` ##### zswapInputs?[​](#zswapinputs "Direct link to zswapInputs?") [`ZswapInput`](/api-reference/ledger/classes/ZswapInput.md)<[`PreProof`](/api-reference/ledger/classes/PreProof.md)>\[] ##### zswapOutputs?[​](#zswapoutputs "Direct link to zswapOutputs?") [`ZswapOutput`](/api-reference/ledger/classes/ZswapOutput.md)<[`PreProof`](/api-reference/ledger/classes/PreProof.md)>\[] ##### zswapTransient?[​](#zswaptransient "Direct link to zswapTransient?") [`ZswapTransient`](/api-reference/ledger/classes/ZswapTransient.md)<[`PreProof`](/api-reference/ledger/classes/PreProof.md)>\[] #### Returns[​](#returns "Direct link to Returns") `Transaction`<`S`, `P`, `B`> #### Throws[​](#throws-3 "Direct link to Throws") If called on bound, proven, or proof-erased transactions. *** ### bind()[​](#bind "Direct link to bind()") ``` bind(): Transaction; ``` Enforces binding for this transaction. This is irreversible. #### Returns[​](#returns-1 "Direct link to Returns") `Transaction`<`S`, `P`, [`Binding`](/api-reference/ledger/classes/Binding.md)> *** ### cost()[​](#cost "Direct link to cost()") ``` cost(params, enforceTimeToDismiss?): SyntheticCost; ``` The underlying resource cost of this transaction. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### params[​](#params-1 "Direct link to params") [`LedgerParameters`](/api-reference/ledger/classes/LedgerParameters.md) ##### enforceTimeToDismiss?[​](#enforcetimetodismiss "Direct link to enforceTimeToDismiss?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") [`SyntheticCost`](/api-reference/ledger/type-aliases/SyntheticCost.md) *** ### eraseProofs()[​](#eraseproofs "Direct link to eraseProofs()") ``` eraseProofs(): Transaction; ``` Erases the proofs contained in this transaction #### Returns[​](#returns-3 "Direct link to Returns") `Transaction`<`S`, [`NoProof`](/api-reference/ledger/classes/NoProof.md), [`NoBinding`](/api-reference/ledger/classes/NoBinding.md)> *** ### eraseSignatures()[​](#erasesignatures "Direct link to eraseSignatures()") ``` eraseSignatures(): Transaction; ``` Removes signatures from this transaction. #### Returns[​](#returns-4 "Direct link to Returns") `Transaction`<[`SignatureErased`](/api-reference/ledger/classes/SignatureErased.md), `P`, `B`> *** ### fees()[​](#fees "Direct link to fees()") ``` fees(params, enforceTimeToDismiss?): bigint; ``` The cost of this transaction, in SPECKs. Note that this is *only* accurate when called with proven transactions. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### params[​](#params-2 "Direct link to params") [`LedgerParameters`](/api-reference/ledger/classes/LedgerParameters.md) ##### enforceTimeToDismiss?[​](#enforcetimetodismiss-1 "Direct link to enforceTimeToDismiss?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `bigint` *** ### feesWithMargin()[​](#feeswithmargin "Direct link to feesWithMargin()") ``` feesWithMargin(params, margin): bigint; ``` The cost of this transaction, in SPECKs, with a safety margin of `n` blocks applied. As with [fees](#fees), this is only accurate for proven transactions. Warning: `n` must be a non-negative integer, and it is an exponent, it is very easy to get a completely unreasonable margin here! #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### params[​](#params-3 "Direct link to params") [`LedgerParameters`](/api-reference/ledger/classes/LedgerParameters.md) ##### margin[​](#margin "Direct link to margin") `number` #### Returns[​](#returns-6 "Direct link to Returns") `bigint` *** ### identifiers()[​](#identifiers "Direct link to identifiers()") ``` identifiers(): string[]; ``` Returns the set of identifiers contained within this transaction. Any of these *may* be used to watch for a specific transaction. #### Returns[​](#returns-7 "Direct link to Returns") `string`\[] *** ### imbalances()[​](#imbalances "Direct link to imbalances()") ``` imbalances(segment, fees?): Map; ``` For given fees, and a given section (guaranteed/fallible), what the surplus or deficit of this transaction in any token type is. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### segment[​](#segment-1 "Direct link to segment") `number` ##### fees?[​](#fees-1 "Direct link to fees?") `bigint` #### Returns[​](#returns-8 "Direct link to Returns") `Map`<[`TokenType`](/api-reference/ledger/type-aliases/TokenType.md), `bigint`> #### Throws[​](#throws-4 "Direct link to Throws") If `segment` is not a valid segment ID *** ### merge()[​](#merge "Direct link to merge()") ``` merge(other): Transaction; ``` Merges this transaction with another #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### other[​](#other "Direct link to other") `Transaction`<`S`, `P`, `B`> #### Returns[​](#returns-9 "Direct link to Returns") `Transaction`<`S`, `P`, `B`> #### Throws[​](#throws-5 "Direct link to Throws") If both transactions have contract interactions, or they spend the same coins *** ### mockProve()[​](#mockprove "Direct link to mockProve()") ``` mockProve(): Transaction; ``` Mocks proving, producing a 'proven' transaction that, while it will *not* verify, is accurate for fee computation purposes. Due to the variability in proof sizes, this *only* works for transactions that do not contain unproven contract calls. #### Returns[​](#returns-10 "Direct link to Returns") `Transaction`<`S`, [`Proof`](/api-reference/ledger/classes/Proof.md), [`Binding`](/api-reference/ledger/classes/Binding.md)> #### Throws[​](#throws-6 "Direct link to Throws") If called on bound, proven, or proof-erased transactions, or if the transaction contains unproven contract calls. *** ### prove()[​](#prove "Direct link to prove()") ``` prove(provider, cost_model): Promise>; ``` Proves the transaction, with access to a low-level proving provider. This may *only* be called for `P = PreProof`. #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### provider[​](#provider "Direct link to provider") [`ProvingProvider`](/api-reference/ledger/type-aliases/ProvingProvider.md) ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/ledger/classes/CostModel.md) #### Returns[​](#returns-11 "Direct link to Returns") `Promise`<`Transaction`<`S`, [`Proof`](/api-reference/ledger/classes/Proof.md), `B`>> #### Throws[​](#throws-7 "Direct link to Throws") If called on bound, proven, or proof-erased transactions. *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-12 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-13 "Direct link to Returns") `string` *** ### transactionHash()[​](#transactionhash "Direct link to transactionHash()") ``` transactionHash(): string; ``` Returns the hash associated with this transaction. Due to the ability to merge transactions, this should not be used to watch for a specific transaction. #### Returns[​](#returns-14 "Direct link to Returns") `string` *** ### wellFormed()[​](#wellformed "Direct link to wellFormed()") ``` wellFormed( ref_state, strictness, tblock): VerifiedTransaction; ``` Tests well-formedness criteria, optionally including transaction balancing #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### ref\_state[​](#ref_state "Direct link to ref_state") [`LedgerState`](/api-reference/ledger/classes/LedgerState.md) ##### strictness[​](#strictness "Direct link to strictness") [`WellFormedStrictness`](/api-reference/ledger/classes/WellFormedStrictness.md) ##### tblock[​](#tblock "Direct link to tblock") `Date` #### Returns[​](#returns-15 "Direct link to Returns") [`VerifiedTransaction`](/api-reference/ledger/classes/VerifiedTransaction.md) #### Throws[​](#throws-8 "Direct link to Throws") If the transaction is not well-formed for any reason *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize( markerS, markerP, markerB, raw): Transaction; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### S[​](#s-1 "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ##### B[​](#b-1 "Direct link to B") `B` *extends* [`Bindingish`](/api-reference/ledger/type-aliases/Bindingish.md) #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### markerS[​](#markers "Direct link to markerS") `S`\[`"instance"`] ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### markerB[​](#markerb "Direct link to markerB") `B`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-16 "Direct link to Returns") `Transaction`<`S`, `P`, `B`> *** ### fromParts()[​](#fromparts "Direct link to fromParts()") ``` static fromParts( network_id, guaranteed?, fallible?, intent?): UnprovenTransaction; ``` Creates a transaction from its parts. #### Parameters[​](#parameters-10 "Direct link to Parameters") ##### network\_id[​](#network_id "Direct link to network_id") `string` ##### guaranteed?[​](#guaranteed "Direct link to guaranteed?") [`UnprovenOffer`](/api-reference/ledger/type-aliases/UnprovenOffer.md) ##### fallible?[​](#fallible "Direct link to fallible?") [`UnprovenOffer`](/api-reference/ledger/type-aliases/UnprovenOffer.md) ##### intent?[​](#intent "Direct link to intent?") [`UnprovenIntent`](/api-reference/ledger/type-aliases/UnprovenIntent.md) #### Returns[​](#returns-17 "Direct link to Returns") [`UnprovenTransaction`](/api-reference/ledger/type-aliases/UnprovenTransaction.md) *** ### fromPartsRandomized()[​](#frompartsrandomized "Direct link to fromPartsRandomized()") ``` static fromPartsRandomized( network_id, guaranteed?, fallible?, intent?): UnprovenTransaction; ``` Creates a transaction from its parts, randomizing the segment ID to better allow merging. #### Parameters[​](#parameters-11 "Direct link to Parameters") ##### network\_id[​](#network_id-1 "Direct link to network_id") `string` ##### guaranteed?[​](#guaranteed-1 "Direct link to guaranteed?") [`UnprovenOffer`](/api-reference/ledger/type-aliases/UnprovenOffer.md) ##### fallible?[​](#fallible-1 "Direct link to fallible?") [`UnprovenOffer`](/api-reference/ledger/type-aliases/UnprovenOffer.md) ##### intent?[​](#intent-1 "Direct link to intent?") [`UnprovenIntent`](/api-reference/ledger/type-aliases/UnprovenIntent.md) #### Returns[​](#returns-18 "Direct link to Returns") [`UnprovenTransaction`](/api-reference/ledger/type-aliases/UnprovenTransaction.md) *** ### fromRewards()[​](#fromrewards "Direct link to fromRewards()") ``` static fromRewards(rewards): Transaction; ``` Creates a rewards claim transaction, the funds claimed must have been legitimately rewarded previously. #### Type Parameters[​](#type-parameters-2 "Direct link to Type Parameters") ##### S[​](#s-2 "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) #### Parameters[​](#parameters-12 "Direct link to Parameters") ##### rewards[​](#rewards-1 "Direct link to rewards") [`ClaimRewardsTransaction`](/api-reference/ledger/classes/ClaimRewardsTransaction.md)<`S`> #### Returns[​](#returns-19 "Direct link to Returns") `Transaction`<`S`, [`PreProof`](/api-reference/ledger/classes/PreProof.md), [`Binding`](/api-reference/ledger/classes/Binding.md)> --- # TransactionContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / TransactionContext # Class: TransactionContext The context against which a transaction is run. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new TransactionContext( ref_state, block_context, whitelist?): TransactionContext; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### ref\_state[​](#ref_state "Direct link to ref_state") [`LedgerState`](/api-reference/ledger/classes/LedgerState.md) A past ledger state that is used as a reference point for 'static' data. ##### block\_context[​](#block_context "Direct link to block_context") [`BlockContext`](/api-reference/ledger/type-aliases/BlockContext.md) Information about the block this transaction is, or will be, contained in. ##### whitelist?[​](#whitelist "Direct link to whitelist?") `Set`<`string`> A list of contracts that are being tracked, or `undefined` to track all contracts. #### Returns[​](#returns "Direct link to Returns") `TransactionContext` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # TransactionCostModel > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / TransactionCostModel # Class: TransactionCostModel ## Properties[​](#properties "Direct link to Properties") ### baselineCost[​](#baselinecost "Direct link to baselineCost") ``` readonly baselineCost: RunningCost; ``` A baseline cost to begin with *** ### inputFeeOverhead[​](#inputfeeoverhead "Direct link to inputFeeOverhead") ``` readonly inputFeeOverhead: bigint; ``` The increase in fees to expect from adding a new input to a transaction *** ### outputFeeOverhead[​](#outputfeeoverhead "Direct link to outputFeeOverhead") ``` readonly outputFeeOverhead: bigint; ``` The increase in fees to expect from adding a new output to a transaction *** ### runtimeCostModel[​](#runtimecostmodel "Direct link to runtimeCostModel") ``` readonly runtimeCostModel: CostModel; ``` A cost model for calculating transaction fees ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): TransactionCostModel; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `TransactionCostModel` *** ### initialTransactionCostModel()[​](#initialtransactioncostmodel "Direct link to initialTransactionCostModel()") ``` static initialTransactionCostModel(): TransactionCostModel; ``` The initial cost model of Midnight #### Returns[​](#returns-3 "Direct link to Returns") `TransactionCostModel` --- # TransactionResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / TransactionResult # Class: TransactionResult The result status of applying a transaction. Includes an error message if the transaction failed, or partially failed. ## Properties[​](#properties "Direct link to Properties") ### error?[​](#error "Direct link to error?") ``` readonly optional error: string; ``` *** ### events[​](#events "Direct link to events") ``` readonly events: Event[]; ``` *** ### successfulSegments?[​](#successfulsegments "Direct link to successfulSegments?") ``` readonly optional successfulSegments: Map; ``` *** ### type[​](#type "Direct link to type") ``` readonly type: "success" | "partialSuccess" | "failure"; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # UnshieldedOffer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnshieldedOffer # Class: UnshieldedOffer\ An unshielded offer consists of inputs, outputs, and signatures that authorize the inputs. The data the signatures sign is provided by [Intent.signatureData](/api-reference/ledger/classes/Intent.md#signaturedata). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ## Properties[​](#properties "Direct link to Properties") ### inputs[​](#inputs "Direct link to inputs") ``` readonly inputs: UtxoSpend[]; ``` *** ### outputs[​](#outputs "Direct link to outputs") ``` readonly outputs: UtxoOutput[]; ``` *** ### signatures[​](#signatures "Direct link to signatures") ``` readonly signatures: string[]; ``` ## Methods[​](#methods "Direct link to Methods") ### addSignatures()[​](#addsignatures "Direct link to addSignatures()") ``` addSignatures(signatures): UnshieldedOffer; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### signatures[​](#signatures-1 "Direct link to signatures") `string`\[] #### Returns[​](#returns "Direct link to Returns") `UnshieldedOffer`<`S`> *** ### eraseSignatures()[​](#erasesignatures "Direct link to eraseSignatures()") ``` eraseSignatures(): UnshieldedOffer; ``` #### Returns[​](#returns-1 "Direct link to Returns") `UnshieldedOffer`<[`SignatureErased`](/api-reference/ledger/classes/SignatureErased.md)> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### new()[​](#new "Direct link to new()") ``` static new( inputs, outputs, signatures): UnshieldedOffer; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### inputs[​](#inputs-1 "Direct link to inputs") [`UtxoSpend`](/api-reference/ledger/type-aliases/UtxoSpend.md)\[] ##### outputs[​](#outputs-1 "Direct link to outputs") [`UtxoOutput`](/api-reference/ledger/type-aliases/UtxoOutput.md)\[] ##### signatures[​](#signatures-2 "Direct link to signatures") `string`\[] #### Returns[​](#returns-3 "Direct link to Returns") `UnshieldedOffer`<[`SignatureEnabled`](/api-reference/ledger/classes/SignatureEnabled.md)> --- # UtxoMeta > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UtxoMeta # Class: UtxoMeta Metadata about a specific UTXO ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new UtxoMeta(ctime): UtxoMeta; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### ctime[​](#ctime "Direct link to ctime") `Date` #### Returns[​](#returns "Direct link to Returns") `UtxoMeta` ## Properties[​](#properties "Direct link to Properties") ### ctime[​](#ctime-1 "Direct link to ctime") ``` ctime: Date; ``` The creation time of the UTXO, that is, when it was inserted into the state. --- # UtxoState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UtxoState # Class: UtxoState The sub-state for unshielded UTXOs ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new UtxoState(): UtxoState; ``` #### Returns[​](#returns "Direct link to Returns") `UtxoState` ## Properties[​](#properties "Direct link to Properties") ### utxos[​](#utxos "Direct link to utxos") ``` readonly utxos: Set; ``` The set of valid UTXOs ## Methods[​](#methods "Direct link to Methods") ### delta()[​](#delta "Direct link to delta()") ``` delta(prior, filterBy?): [Set, Set]; ``` Given a prior UTXO state, produce the set differences `this \ prior`, and `prior \ this`, optionally filtered by a further condition. Note that this should be more efficient than iterating or manifesting the [utxos](#utxos) value, as the low-level implementation can avoid traversing shared sub-structures. #### Parameters[​](#parameters "Direct link to Parameters") ##### prior[​](#prior "Direct link to prior") `UtxoState` ##### filterBy?[​](#filterby "Direct link to filterBy?") (`utxo`) => `boolean` #### Returns[​](#returns-1 "Direct link to Returns") \[`Set`<[`Utxo`](/api-reference/ledger/type-aliases/Utxo.md)>, `Set`<[`Utxo`](/api-reference/ledger/type-aliases/Utxo.md)>] *** ### filter()[​](#filter "Direct link to filter()") ``` filter(addr): Set; ``` Filters out the UTXOs owned by a specific user address #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### addr[​](#addr "Direct link to addr") `string` #### Returns[​](#returns-2 "Direct link to Returns") `Set`<[`Utxo`](/api-reference/ledger/type-aliases/Utxo.md)> *** ### lookupMeta()[​](#lookupmeta "Direct link to lookupMeta()") ``` lookupMeta(utxo): undefined | UtxoMeta; ``` Lookup the metadata for a specific UTXO. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### utxo[​](#utxo "Direct link to utxo") [`Utxo`](/api-reference/ledger/type-aliases/Utxo.md) #### Returns[​](#returns-3 "Direct link to Returns") `undefined` | [`UtxoMeta`](/api-reference/ledger/classes/UtxoMeta.md) *** ### new()[​](#new "Direct link to new()") ``` static new(utxos): UtxoState; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### utxos[​](#utxos-1 "Direct link to utxos") `Map`<[`Utxo`](/api-reference/ledger/type-aliases/Utxo.md), [`UtxoMeta`](/api-reference/ledger/classes/UtxoMeta.md)> #### Returns[​](#returns-4 "Direct link to Returns") `UtxoState` --- # VerifiedTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / VerifiedTransaction # Class: VerifiedTransaction A transaction that has been validated with `wellFormed`. ## Properties[​](#properties "Direct link to Properties") ### transaction[​](#transaction "Direct link to transaction") ``` readonly transaction: Transaction; ``` The actual underlying transaction --- # VerifierKeyInsert > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / VerifierKeyInsert # Class: VerifierKeyInsert An update instruction to insert a verifier key at a specific operation and version. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new VerifierKeyInsert(operation, vk): VerifierKeyInsert; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### operation[​](#operation "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> ##### vk[​](#vk "Direct link to vk") [`ContractOperationVersionedVerifierKey`](/api-reference/ledger/classes/ContractOperationVersionedVerifierKey.md) #### Returns[​](#returns "Direct link to Returns") `VerifierKeyInsert` ## Properties[​](#properties "Direct link to Properties") ### operation[​](#operation-1 "Direct link to operation") ``` readonly operation: string | Uint8Array; ``` *** ### vk[​](#vk-1 "Direct link to vk") ``` readonly vk: ContractOperationVersionedVerifierKey; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # VerifierKeyRemove > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / VerifierKeyRemove # Class: VerifierKeyRemove An update instruction to remove a verifier key of a specific operation and version. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new VerifierKeyRemove(operation, version): VerifierKeyRemove; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### operation[​](#operation "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> ##### version[​](#version "Direct link to version") [`ContractOperationVersion`](/api-reference/ledger/classes/ContractOperationVersion.md) #### Returns[​](#returns "Direct link to Returns") `VerifierKeyRemove` ## Properties[​](#properties "Direct link to Properties") ### operation[​](#operation-1 "Direct link to operation") ``` readonly operation: string | Uint8Array; ``` *** ### version[​](#version-1 "Direct link to version") ``` readonly version: ContractOperationVersion; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # VmResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / VmResults # Class: VmResults Represents the results of a VM call ## Properties[​](#properties "Direct link to Properties") ### events[​](#events "Direct link to events") ``` readonly events: GatherResult[]; ``` The events that got emitted by this VM invocation *** ### gasCost[​](#gascost "Direct link to gasCost") ``` readonly gasCost: RunningCost; ``` The computed gas cost of running this VM invocation *** ### stack[​](#stack "Direct link to stack") ``` readonly stack: VmStack; ``` The VM stack at the end of the VM invocation ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # VmStack > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / VmStack # Class: VmStack Represents the state of the VM's stack at a specific point. The stack is an array of [StateValue](/api-reference/ledger/classes/StateValue.md)s, each of which is also annotated with whether it is "strong" or "weak"; that is, whether it is permitted to be stored on-chain or not. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new VmStack(): VmStack; ``` #### Returns[​](#returns "Direct link to Returns") `VmStack` ## Methods[​](#methods "Direct link to Methods") ### get()[​](#get "Direct link to get()") ``` get(idx): undefined | StateValue; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### idx[​](#idx "Direct link to idx") `number` #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`StateValue`](/api-reference/ledger/classes/StateValue.md) *** ### isStrong()[​](#isstrong "Direct link to isStrong()") ``` isStrong(idx): undefined | boolean; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### idx[​](#idx-1 "Direct link to idx") `number` #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | `boolean` *** ### length()[​](#length "Direct link to length()") ``` length(): number; ``` #### Returns[​](#returns-3 "Direct link to Returns") `number` *** ### push()[​](#push "Direct link to push()") ``` push(value, is_strong): void; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/ledger/classes/StateValue.md) ##### is\_strong[​](#is_strong "Direct link to is_strong") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `void` *** ### removeLast()[​](#removelast "Direct link to removeLast()") ``` removeLast(): void; ``` #### Returns[​](#returns-5 "Direct link to Returns") `void` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` --- # WellFormedStrictness > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / WellFormedStrictness # Class: WellFormedStrictness Strictness criteria for evaluating transaction well-formedness, used for disabling parts of transaction validation for testing. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new WellFormedStrictness(): WellFormedStrictness; ``` #### Returns[​](#returns "Direct link to Returns") `WellFormedStrictness` ## Properties[​](#properties "Direct link to Properties") ### enforceBalancing[​](#enforcebalancing "Direct link to enforceBalancing") ``` enforceBalancing: boolean; ``` Whether to require the transaction to have a non-negative balance *** ### enforceLimits[​](#enforcelimits "Direct link to enforceLimits") ``` enforceLimits: boolean; ``` Whether to enforce the transaction byte limit *** ### verifyContractProofs[​](#verifycontractproofs "Direct link to verifyContractProofs") ``` verifyContractProofs: boolean; ``` Whether to validate contract proofs in the transaction *** ### verifyNativeProofs[​](#verifynativeproofs "Direct link to verifyNativeProofs") ``` verifyNativeProofs: boolean; ``` Whether to validate Midnight-native (non-contract) proofs in the transaction *** ### verifySignatures[​](#verifysignatures "Direct link to verifySignatures") ``` verifySignatures: boolean; ``` Whether to enforce the signature verification --- # ZswapChainState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapChainState # Class: ZswapChainState The on-chain state of Zswap, consisting of a Merkle tree of coin commitments, a set of nullifiers, an index into the Merkle tree, and a set of valid past Merkle tree roots ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ZswapChainState(): ZswapChainState; ``` #### Returns[​](#returns "Direct link to Returns") `ZswapChainState` ## Properties[​](#properties "Direct link to Properties") ### firstFree[​](#firstfree "Direct link to firstFree") ``` readonly firstFree: bigint; ``` The first free index in the coin commitment tree ## Methods[​](#methods "Direct link to Methods") ### filter()[​](#filter "Direct link to filter()") ``` filter(contractAddress): ZswapChainState; ``` Filters the state to only include coins that are relevant to a given contract address. #### Parameters[​](#parameters "Direct link to Parameters") ##### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` #### Returns[​](#returns-1 "Direct link to Returns") `ZswapChainState` *** ### postBlockUpdate()[​](#postblockupdate "Direct link to postBlockUpdate()") ``` postBlockUpdate(tblock): ZswapChainState; ``` Carries out a post-block update, which does amortized bookkeeping that only needs to be done once per state change. Typically, `postBlockUpdate` should be run after any (sequence of) (system)-transaction application(s). #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### tblock[​](#tblock "Direct link to tblock") `Date` #### Returns[​](#returns-2 "Direct link to Returns") `ZswapChainState` *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-3 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `string` *** ### tryApply()[​](#tryapply "Direct link to tryApply()") ``` tryApply

(offer, whitelist?): [ZswapChainState, Map]; ``` Try to apply an [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md) to the state, returning the updated state and a map on newly inserted coin commitments to their inserted indices. #### Type Parameters[​](#type-parameters "Direct link to Type Parameters") ##### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### offer[​](#offer "Direct link to offer") [`ZswapOffer`](/api-reference/ledger/classes/ZswapOffer.md)<`P`> ##### whitelist?[​](#whitelist "Direct link to whitelist?") `Set`<`string`> A set of contract addresses that are of interest. If set, *only* these addresses are tracked, and all other information is discarded. #### Returns[​](#returns-5 "Direct link to Returns") \[`ZswapChainState`, `Map`<`string`, `bigint`>] *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ZswapChainState; ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-6 "Direct link to Returns") `ZswapChainState` *** ### deserializeFromLedgerState()[​](#deserializefromledgerstate "Direct link to deserializeFromLedgerState()") ``` static deserializeFromLedgerState(raw): ZswapChainState; ``` Given a whole ledger serialized state, deserialize only the Zswap portion #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### raw[​](#raw-1 "Direct link to raw") `Uint8Array` #### Returns[​](#returns-7 "Direct link to Returns") `ZswapChainState` --- # ZswapInput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapInput # Class: ZswapInput\

A shielded transaction input ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Properties[​](#properties "Direct link to Properties") ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the input, if the sender is a contract *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the input *** ### proof[​](#proof "Direct link to proof") ``` readonly proof: P; ``` The proof of this input ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize

(markerP, raw): ZswapInput

; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `ZswapInput`<`P`> *** ### newContractOwned()[​](#newcontractowned "Direct link to newContractOwned()") ``` static newContractOwned( coin, segment, contract, state): UnprovenInput; ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `undefined` | `number` ##### contract[​](#contract "Direct link to contract") `string` ##### state[​](#state "Direct link to state") [`ZswapChainState`](/api-reference/ledger/classes/ZswapChainState.md) #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenInput`](/api-reference/ledger/type-aliases/UnprovenInput.md) --- # ZswapLocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapLocalState # Class: ZswapLocalState The local state of a user/wallet, consisting of a set of unspent coins It also keeps track of coins that are in-flight, either expecting to spend or expecting to receive, and a local copy of the global coin commitment Merkle tree to generate proofs against. It does not store keys internally, but accepts them as arguments to various operations. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") ``` new ZswapLocalState(): ZswapLocalState; ``` Creates a new, empty state #### Returns[​](#returns "Direct link to Returns") `ZswapLocalState` ## Properties[​](#properties "Direct link to Properties") ### coins[​](#coins "Direct link to coins") ``` readonly coins: Set; ``` The set of *spendable* coins of this wallet *** ### firstFree[​](#firstfree "Direct link to firstFree") ``` readonly firstFree: bigint; ``` The first free index in the internal coin commitments Merkle tree. This may be used to identify which merkle tree updates are necessary. *** ### pendingOutputs[​](#pendingoutputs "Direct link to pendingOutputs") ``` readonly pendingOutputs: Map; ``` The outputs that this wallet is expecting to receive in the future, with an optional TTL attached. *** ### pendingSpends[​](#pendingspends "Direct link to pendingSpends") ``` readonly pendingSpends: Map; ``` The spends that this wallet is expecting to be finalized on-chain in the future. Each has an optional TTL attached. ## Methods[​](#methods "Direct link to Methods") ### apply()[​](#apply "Direct link to apply()") ``` apply

(secretKeys, offer): ZswapLocalState; ``` Locally applies an offer to the current state, returning the updated state #### Type Parameters[​](#type-parameters "Direct link to Type Parameters") ##### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters "Direct link to Parameters") ##### secretKeys[​](#secretkeys "Direct link to secretKeys") [`ZswapSecretKeys`](/api-reference/ledger/classes/ZswapSecretKeys.md) ##### offer[​](#offer "Direct link to offer") [`ZswapOffer`](/api-reference/ledger/classes/ZswapOffer.md)<`P`> #### Returns[​](#returns-1 "Direct link to Returns") `ZswapLocalState` *** ### applyCollapsedUpdate()[​](#applycollapsedupdate "Direct link to applyCollapsedUpdate()") ``` applyCollapsedUpdate(update): ZswapLocalState; ``` Applies a collapsed Merkle tree update to the current local state, fast forwarding through the indices included in it, if it is a correct update. The general flow for usage if Alice is in state A, and wants to ask Bob how to reach the new state B, is: * Find where she left off – what's her firstFree? * Find out where she's going – ask for Bob's firstFree. * Find what contents she does care about – ask Bob for the filtered entries she want to include proper in her tree. * In order, of Merkle tree indices: * Insert (with `apply` offers Alice cares about). * Skip (with this method) sections Alice does not care about, obtaining the collapsed update covering the gap from Bob. Note that `firstFree` is not included in the tree itself, and both ends of updates *are* included. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### update[​](#update "Direct link to update") [`MerkleTreeCollapsedUpdate`](/api-reference/ledger/classes/MerkleTreeCollapsedUpdate.md) #### Returns[​](#returns-2 "Direct link to Returns") `ZswapLocalState` *** ### applyFailed()[​](#applyfailed "Direct link to applyFailed()") ``` applyFailed

(offer): ZswapLocalState; ``` Locally reverts pending outputs/spends from an offer known to have failed or which has been discarded. #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### offer[​](#offer-1 "Direct link to offer") [`ZswapOffer`](/api-reference/ledger/classes/ZswapOffer.md)<`P`> #### Returns[​](#returns-3 "Direct link to Returns") `ZswapLocalState` *** ### clearPending()[​](#clearpending "Direct link to clearPending()") ``` clearPending(time): ZswapLocalState; ``` Clears pending outputs / spends that have passed their TTL without being included in a block. Note that as TTLs are *from a block perspective*, and there is some latency between the block and the wallet, the time passed in here should not be the current time, but incorporate a latency buffer. NOTE: This API endpoint is currently non-functional and works as a no-op. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### time[​](#time "Direct link to time") `Date` #### Returns[​](#returns-4 "Direct link to Returns") `ZswapLocalState` *** ### replayEvents()[​](#replayevents "Direct link to replayEvents()") ``` replayEvents(secretKeys, events): ZswapLocalState; ``` Replays observed events against the current local state. These *must* be replayed in the same order as emitted by the chain being followed. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-1 "Direct link to secretKeys") [`ZswapSecretKeys`](/api-reference/ledger/classes/ZswapSecretKeys.md) ##### events[​](#events "Direct link to events") [`Event`](/api-reference/ledger/classes/Event.md)\[] #### Returns[​](#returns-5 "Direct link to Returns") `ZswapLocalState` *** ### replayEventsWithChanges()[​](#replayeventswithchanges "Direct link to replayEventsWithChanges()") ``` replayEventsWithChanges(secretKeys, events): ZswapLocalStateWithChanges; ``` Replays observed events against the current local state, returning both the updated state and the state changes. These *must* be replayed in the same order as emitted by the chain being followed. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-2 "Direct link to secretKeys") [`ZswapSecretKeys`](/api-reference/ledger/classes/ZswapSecretKeys.md) ##### events[​](#events-1 "Direct link to events") [`Event`](/api-reference/ledger/classes/Event.md)\[] #### Returns[​](#returns-6 "Direct link to Returns") [`ZswapLocalStateWithChanges`](/api-reference/ledger/classes/ZswapLocalStateWithChanges.md) *** ### revertTransaction()[​](#reverttransaction "Direct link to revertTransaction()") ``` revertTransaction(transaction): ZswapLocalState; ``` Locally reverts all pending outputs/spends from a transaction which has been discarded. Behaves as [applyFailed](#applyfailed) for the entire transaction. #### Type Parameters[​](#type-parameters-2 "Direct link to Type Parameters") ##### S[​](#s "Direct link to S") `S` *extends* [`Signaturish`](/api-reference/ledger/type-aliases/Signaturish.md) ##### P[​](#p-2 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ##### B[​](#b "Direct link to B") `B` *extends* [`Bindingish`](/api-reference/ledger/type-aliases/Bindingish.md) #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### transaction[​](#transaction "Direct link to transaction") [`Transaction`](/api-reference/ledger/classes/Transaction.md)<`S`, `P`, `B`> #### Returns[​](#returns-7 "Direct link to Returns") `ZswapLocalState` *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-8 "Direct link to Returns") `Uint8Array` *** ### spend()[​](#spend "Direct link to spend()") ``` spend( secretKeys, coin, segment, ttl?): [ZswapLocalState, UnprovenInput]; ``` Initiates a new spend of a specific coin, outputting the corresponding [ZswapInput](/api-reference/ledger/classes/ZswapInput.md), and the updated state marking this coin as in-flight. #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-3 "Direct link to secretKeys") [`ZswapSecretKeys`](/api-reference/ledger/classes/ZswapSecretKeys.md) ##### coin[​](#coin "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `undefined` | `number` ##### ttl?[​](#ttl "Direct link to ttl?") `Date` #### Returns[​](#returns-9 "Direct link to Returns") \[`ZswapLocalState`, [`UnprovenInput`](/api-reference/ledger/type-aliases/UnprovenInput.md)] *** ### spendFromOutput()[​](#spendfromoutput "Direct link to spendFromOutput()") ``` spendFromOutput( secretKeys, coin, segment, output, ttl?): [ZswapLocalState, UnprovenTransient]; ``` Initiates a new spend of a new-yet-received output, outputting the corresponding [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md), and the updated state marking this coin as in-flight. #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-4 "Direct link to secretKeys") [`ZswapSecretKeys`](/api-reference/ledger/classes/ZswapSecretKeys.md) ##### coin[​](#coin-1 "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) ##### segment[​](#segment-1 "Direct link to segment") `undefined` | `number` ##### output[​](#output "Direct link to output") [`UnprovenOutput`](/api-reference/ledger/type-aliases/UnprovenOutput.md) ##### ttl?[​](#ttl-1 "Direct link to ttl?") `Date` #### Returns[​](#returns-10 "Direct link to Returns") \[`ZswapLocalState`, [`UnprovenTransient`](/api-reference/ledger/type-aliases/UnprovenTransient.md)] *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-11 "Direct link to Returns") `string` *** ### watchFor()[​](#watchfor "Direct link to watchFor()") ``` watchFor(coinPublicKey, coin): ZswapLocalState; ``` Adds a coin to the list of coins that are expected to be received This should be used if an output is creating a coin for this wallet, which does not contain a ciphertext to detect it. In this case, the wallet must know the commitment ahead of time to notice the receipt. #### Parameters[​](#parameters-10 "Direct link to Parameters") ##### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") `string` ##### coin[​](#coin-2 "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) #### Returns[​](#returns-12 "Direct link to Returns") `ZswapLocalState` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ZswapLocalState; ``` #### Parameters[​](#parameters-11 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-13 "Direct link to Returns") `ZswapLocalState` --- # ZswapLocalStateWithChanges > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapLocalStateWithChanges # Class: ZswapLocalStateWithChanges ## Properties[​](#properties "Direct link to Properties") ### changes[​](#changes "Direct link to changes") ``` readonly changes: ZswapStateChanges[]; ``` The state changes that occurred during the replay *** ### state[​](#state "Direct link to state") ``` readonly state: ZswapLocalState; ``` The updated local state after replaying events --- # ZswapOffer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapOffer # Class: ZswapOffer\

A full Zswap offer; the zswap part of a transaction Consists of sets of [ZswapInput](/api-reference/ledger/classes/ZswapInput.md)s, [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md)s, and [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md)s, as well as a [deltas](#deltas) vector of the transaction value ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Properties[​](#properties "Direct link to Properties") ### deltas[​](#deltas "Direct link to deltas") ``` readonly deltas: Map; ``` The value of this offer for each token type; note that this may be negative This is input coin values - output coin values, for value vectors *** ### inputs[​](#inputs "Direct link to inputs") ``` readonly inputs: ZswapInput

[]; ``` The inputs this offer is composed of *** ### outputs[​](#outputs "Direct link to outputs") ``` readonly outputs: ZswapOutput

[]; ``` The outputs this offer is composed of *** ### transients[​](#transients "Direct link to transients") ``` readonly transients: ZswapTransient

[]; ``` The transients this offer is composed of ## Methods[​](#methods "Direct link to Methods") ### merge()[​](#merge "Direct link to merge()") ``` merge(other): ZswapOffer

; ``` Combine this offer with another #### Parameters[​](#parameters "Direct link to Parameters") ##### other[​](#other "Direct link to other") `ZswapOffer`<`P`> #### Returns[​](#returns "Direct link to Returns") `ZswapOffer`<`P`> *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize

(markerP, raw): ZswapOffer

; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") `ZswapOffer`<`P`> *** ### fromInput()[​](#frominput "Direct link to fromInput()") ``` static fromInput

( input, type_?, value?): ZswapOffer

; ``` Creates a singleton offer, from an [ZswapInput](/api-reference/ledger/classes/ZswapInput.md) and its value vector The `type_` and `value` parameters are deprecated and will be ignored. #### Type Parameters[​](#type-parameters-2 "Direct link to Type Parameters") ##### P[​](#p-2 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### input[​](#input "Direct link to input") [`ZswapInput`](/api-reference/ledger/classes/ZswapInput.md)<`P`> ##### type\_?[​](#type_ "Direct link to type_?") `string` ##### value?[​](#value "Direct link to value?") `bigint` #### Returns[​](#returns-4 "Direct link to Returns") `ZswapOffer`<`P`> *** ### fromOutput()[​](#fromoutput "Direct link to fromOutput()") ``` static fromOutput

( output, type_?, value?): ZswapOffer

; ``` Creates a singleton offer, from an [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md) and its value vector The `type_` and `value` parameters are deprecated and will be ignored. #### Type Parameters[​](#type-parameters-3 "Direct link to Type Parameters") ##### P[​](#p-3 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### output[​](#output "Direct link to output") [`ZswapOutput`](/api-reference/ledger/classes/ZswapOutput.md)<`P`> ##### type\_?[​](#type_-1 "Direct link to type_?") `string` ##### value?[​](#value-1 "Direct link to value?") `bigint` #### Returns[​](#returns-5 "Direct link to Returns") `ZswapOffer`<`P`> *** ### fromTransient()[​](#fromtransient "Direct link to fromTransient()") ``` static fromTransient

(transient): ZswapOffer

; ``` Creates a singleton offer, from a [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md) #### Type Parameters[​](#type-parameters-4 "Direct link to Type Parameters") ##### P[​](#p-4 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### transient[​](#transient "Direct link to transient") [`ZswapTransient`](/api-reference/ledger/classes/ZswapTransient.md)<`P`> #### Returns[​](#returns-6 "Direct link to Returns") `ZswapOffer`<`P`> --- # ZswapOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapOutput # Class: ZswapOutput\

A shielded transaction output ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the output *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the output, if the recipient is a contract *** ### proof[​](#proof "Direct link to proof") ``` readonly proof: P; ``` The proof of this output ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize

(markerP, raw): ZswapOutput

; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `ZswapOutput`<`P`> *** ### new()[​](#new "Direct link to new()") ``` static new( coin, segment, target_cpk, target_epk): UnprovenOutput; ``` Creates a new output, targeted to a user's coin public key. Optionally the output contains a ciphertext encrypted to the user's encryption public key, which may be omitted *only* if the [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) is transferred to the recipient another way #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `undefined` | `number` ##### target\_cpk[​](#target_cpk "Direct link to target_cpk") `string` ##### target\_epk[​](#target_epk "Direct link to target_epk") `string` #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenOutput`](/api-reference/ledger/type-aliases/UnprovenOutput.md) *** ### newContractOwned()[​](#newcontractowned "Direct link to newContractOwned()") ``` static newContractOwned( coin, segment, contract): UnprovenOutput; ``` Creates a new output, targeted to a smart contract A contract must *also* explicitly receive a coin created in this way for the output to be valid #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### coin[​](#coin-1 "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) ##### segment[​](#segment-1 "Direct link to segment") `undefined` | `number` ##### contract[​](#contract "Direct link to contract") `string` #### Returns[​](#returns-4 "Direct link to Returns") [`UnprovenOutput`](/api-reference/ledger/type-aliases/UnprovenOutput.md) --- # ZswapSecretKeys > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapSecretKeys # Class: ZswapSecretKeys ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") ``` readonly coinPublicKey: string; ``` *** ### coinSecretKey[​](#coinsecretkey "Direct link to coinSecretKey") ``` readonly coinSecretKey: CoinSecretKey; ``` *** ### encryptionPublicKey[​](#encryptionpublickey "Direct link to encryptionPublicKey") ``` readonly encryptionPublicKey: string; ``` *** ### encryptionSecretKey[​](#encryptionsecretkey "Direct link to encryptionSecretKey") ``` readonly encryptionSecretKey: EncryptionSecretKey; ``` ## Methods[​](#methods "Direct link to Methods") ### clear()[​](#clear "Direct link to clear()") ``` clear(): void; ``` Clears the secret keys, so that they are no longer usable nor held in memory Note: it does not clear copies of the keys - which is particularly relevant for proof preimages Note: this will cause all other operations to fail #### Returns[​](#returns "Direct link to Returns") `void` *** ### fromSeed()[​](#fromseed "Direct link to fromSeed()") ``` static fromSeed(seed): ZswapSecretKeys; ``` Derives secret keys from a 32-byte seed #### Parameters[​](#parameters "Direct link to Parameters") ##### seed[​](#seed "Direct link to seed") `Uint8Array` #### Returns[​](#returns-1 "Direct link to Returns") `ZswapSecretKeys` *** ### fromSeedRng()[​](#fromseedrng "Direct link to fromSeedRng()") ``` static fromSeedRng(seed): ZswapSecretKeys; ``` Derives secret keys from a 32-byte seed using deprecated implementation. Use only for compatibility purposes #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### seed[​](#seed-1 "Direct link to seed") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `ZswapSecretKeys` --- # ZswapStateChanges > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapStateChanges # Class: ZswapStateChanges ## Properties[​](#properties "Direct link to Properties") ### receivedCoins[​](#receivedcoins "Direct link to receivedCoins") ``` readonly receivedCoins: QualifiedShieldedCoinInfo[]; ``` The coins that were received in this state change *** ### source[​](#source "Direct link to source") ``` readonly source: string; ``` The source of the state change, as a hex-encoded string *** ### spentCoins[​](#spentcoins "Direct link to spentCoins") ``` readonly spentCoins: QualifiedShieldedCoinInfo[]; ``` The coins that were spent in this state change --- # ZswapTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ZswapTransient # Class: ZswapTransient\

A shielded "transient"; an output that is immediately spent within the same transaction ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the transient *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address creating the transient, if applicable *** ### inputProof[​](#inputproof "Direct link to inputProof") ``` readonly inputProof: P; ``` The input proof of this transient *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the transient *** ### outputProof[​](#outputproof "Direct link to outputProof") ``` readonly outputProof: P; ``` The output proof of this transient ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array; ``` #### Returns[​](#returns "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize

(markerP, raw): ZswapTransient

; ``` #### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") ##### P[​](#p-1 "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### markerP[​](#markerp "Direct link to markerP") `P`\[`"instance"`] ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `ZswapTransient`<`P`> *** ### newFromContractOwnedOutput()[​](#newfromcontractownedoutput "Direct link to newFromContractOwnedOutput()") ``` static newFromContractOwnedOutput( coin, segment, output): UnprovenTransient; ``` Creates a new contract-owned transient, from a given output and its coin. The [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) should have an `mt_index` of `0` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `undefined` | `number` ##### output[​](#output "Direct link to output") [`UnprovenOutput`](/api-reference/ledger/type-aliases/UnprovenOutput.md) #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenTransient`](/api-reference/ledger/type-aliases/UnprovenTransient.md) --- # addressFromKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / addressFromKey # Function: addressFromKey() ``` function addressFromKey(key): string; ``` Converts a bare signature public key to its corresponding address. ## Parameters[​](#parameters "Direct link to Parameters") ### key[​](#key "Direct link to key") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # bigIntModFr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / bigIntModFr # Function: bigIntModFr() ``` function bigIntModFr(x): bigint; ``` Takes a bigint modulus the proof systems scalar field ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # bigIntToValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / bigIntToValue # Function: bigIntToValue() ``` function bigIntToValue(x): Value; ``` **`Internal`** Internal conversion between bigints and their field-aligned binary representation ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) --- # coinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / coinCommitment # Function: coinCommitment() ``` function coinCommitment(coin, coinPublicKey): string; ``` Calculate commitment of a coin owned by a user ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # coinNullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / coinNullifier # Function: coinNullifier() ``` function coinNullifier(coin, coinSecretKey): string; ``` Calculate nullifier of a coin owned by a user ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) ### coinSecretKey[​](#coinsecretkey "Direct link to coinSecretKey") [`CoinSecretKey`](/api-reference/ledger/classes/CoinSecretKey.md) ## Returns[​](#returns "Direct link to Returns") `string` --- # communicationCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / communicationCommitment # Function: communicationCommitment() ## Call Signature[​](#call-signature "Direct link to Call Signature") ``` function communicationCommitment( input, output, rand): string; ``` Computes the communication commitment corresponding to an input/output pair and randomness. ### Parameters[​](#parameters "Direct link to Parameters") #### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### rand[​](#rand "Direct link to rand") `string` ### Returns[​](#returns "Direct link to Returns") `string` ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") ``` function communicationCommitment( input, output, rand): string; ``` Computes the communication commitment corresponding to an input/output pair and randomness. ### Parameters[​](#parameters-1 "Direct link to Parameters") #### input[​](#input-1 "Direct link to input") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### output[​](#output-1 "Direct link to output") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) #### rand[​](#rand-1 "Direct link to rand") `string` ### Returns[​](#returns-1 "Direct link to Returns") `string` --- # communicationCommitmentRandomness > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / communicationCommitmentRandomness # Function: communicationCommitmentRandomness() ``` function communicationCommitmentRandomness(): string; ``` Samples a new [CommunicationCommitmentRand](/api-reference/ledger/type-aliases/CommunicationCommitmentRand.md) uniformly ## Returns[​](#returns "Direct link to Returns") `string` --- # createCheckPayload > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / createCheckPayload # Function: createCheckPayload() ``` function createCheckPayload(serializedPreimage, ir?): Uint8Array; ``` Creates a payload for checking a specific proof through the proof server ## Parameters[​](#parameters "Direct link to Parameters") ### serializedPreimage[​](#serializedpreimage "Direct link to serializedPreimage") `Uint8Array` ### ir?[​](#ir "Direct link to ir?") `Uint8Array`<`ArrayBufferLike`> ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # createProvingPayload > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / createProvingPayload # Function: createProvingPayload() ``` function createProvingPayload( serializedPreimage, overwriteBindingInput, keyMaterial?): Uint8Array; ``` Creates a payload for proving a specific proof through the proof server ## Parameters[​](#parameters "Direct link to Parameters") ### serializedPreimage[​](#serializedpreimage "Direct link to serializedPreimage") `Uint8Array` ### overwriteBindingInput[​](#overwritebindinginput "Direct link to overwriteBindingInput") `undefined` | `bigint` ### keyMaterial?[​](#keymaterial "Direct link to keyMaterial?") [`ProvingKeyMaterial`](/api-reference/ledger/type-aliases/ProvingKeyMaterial.md) ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # createProvingTransactionPayload > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / createProvingTransactionPayload # Function: ~~createProvingTransactionPayload()~~ ``` function createProvingTransactionPayload(transaction, proving_data): Uint8Array; ``` Creates a payload for proving a specific transaction through the proof server ## Parameters[​](#parameters "Direct link to Parameters") ### transaction[​](#transaction "Direct link to transaction") [`UnprovenTransaction`](/api-reference/ledger/type-aliases/UnprovenTransaction.md) ### proving\_data[​](#proving_data "Direct link to proving_data") `Map`<`string`, [`ProvingKeyMaterial`](/api-reference/ledger/type-aliases/ProvingKeyMaterial.md)> ## Returns[​](#returns "Direct link to Returns") `Uint8Array` ## Deprecated[​](#deprecated "Direct link to Deprecated") Use `Transaction.prove` instead. --- # createShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / createShieldedCoinInfo # Function: createShieldedCoinInfo() ``` function createShieldedCoinInfo(type_, value): ShieldedCoinInfo; ``` Creates a new [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md), sampling a uniform nonce ## Parameters[​](#parameters "Direct link to Parameters") ### type\_[​](#type_ "Direct link to type_") `string` ### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) --- # decodeCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / decodeCoinPublicKey # Function: decodeCoinPublicKey() ``` function decodeCoinPublicKey(pk): string; ``` Decode a [CoinPublicKey](/api-reference/ledger/type-aliases/CoinPublicKey.md) from a `Uint8Array` originating from Compact's `CoinPublicKey` type ## Parameters[​](#parameters "Direct link to Parameters") ### pk[​](#pk "Direct link to pk") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / decodeContractAddress # Function: decodeContractAddress() ``` function decodeContractAddress(addr): string; ``` Decode a [ContractAddress](/api-reference/ledger/type-aliases/ContractAddress.md) from a `Uint8Array` originating from Compact's `ContractAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / decodeQualifiedShieldedCoinInfo # Function: decodeQualifiedShieldedCoinInfo() ``` function decodeQualifiedShieldedCoinInfo(coin): QualifiedShieldedCoinInfo; ``` Decode a [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) from Compact's `QualifiedShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### mt\_index[​](#mt_index "Direct link to mt_index") `bigint` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`QualifiedShieldedCoinInfo`](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) --- # decodeRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / decodeRawTokenType # Function: decodeRawTokenType() ``` function decodeRawTokenType(tt): string; ``` Decode a raw [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md) from a `Uint8Array` originating from Compact's `RawTokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / decodeShieldedCoinInfo # Function: decodeShieldedCoinInfo() ``` function decodeShieldedCoinInfo(coin): ShieldedCoinInfo; ``` Decode a [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) from Compact's `ShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) --- # decodeUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / decodeUserAddress # Function: decodeUserAddress() ``` function decodeUserAddress(addr): string; ``` Decode a [UserAddress](/api-reference/ledger/type-aliases/UserAddress.md) from a `Uint8Array` originating from Compact's `UserAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # degradeToTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / degradeToTransient # Function: degradeToTransient() ``` function degradeToTransient(persistent): Value; ``` **`Internal`** Internal implementation of the degrade to transient primitive ## Parameters[​](#parameters "Direct link to Parameters") ### persistent[​](#persistent "Direct link to persistent") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [persistent](#degradetotransient) does not encode a 32-byte bytestring --- # dummyContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / dummyContractAddress # Function: dummyContractAddress() ``` function dummyContractAddress(): string; ``` A sample contract address ## Returns[​](#returns "Direct link to Returns") `string` --- # dummyUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / dummyUserAddress # Function: dummyUserAddress() ``` function dummyUserAddress(): string; ``` A sample user address ## Returns[​](#returns "Direct link to Returns") `string` --- # ecAdd > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ecAdd # Function: ecAdd() ``` function ecAdd(a, b): Value; ``` **`Internal`** Internal implementation of the elliptic curve addition primitive ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`Value`](/api-reference/ledger/type-aliases/Value.md) ### b[​](#b "Direct link to b") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If either input does not encode an elliptic curve point --- # ecMul > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ecMul # Function: ecMul() ``` function ecMul(a, b): Value; ``` **`Internal`** Internal implementation of the elliptic curve multiplication primitive ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`Value`](/api-reference/ledger/type-aliases/Value.md) ### b[​](#b "Direct link to b") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [a](#ecmul) does not encode an elliptic curve point or [b](#ecmul) does not encode a field element --- # ecMulGenerator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ecMulGenerator # Function: ecMulGenerator() ``` function ecMulGenerator(val): Value; ``` **`Internal`** Internal implementation of the elliptic curve generator multiplication primitive ## Parameters[​](#parameters "Direct link to Parameters") ### val[​](#val "Direct link to val") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") if [val](#ecmulgenerator) does not encode a field element --- # encodeCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / encodeCoinPublicKey # Function: encodeCoinPublicKey() ``` function encodeCoinPublicKey(pk): Uint8Array; ``` Encode a [CoinPublicKey](/api-reference/ledger/type-aliases/CoinPublicKey.md) into a `Uint8Array` for use in Compact's `CoinPublicKey` type ## Parameters[​](#parameters "Direct link to Parameters") ### pk[​](#pk "Direct link to pk") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / encodeContractAddress # Function: encodeContractAddress() ``` function encodeContractAddress(addr): Uint8Array; ``` Encode a [ContractAddress](/api-reference/ledger/type-aliases/ContractAddress.md) into a `Uint8Array` for use in Compact's `ContractAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / encodeQualifiedShieldedCoinInfo # Function: encodeQualifiedShieldedCoinInfo() ``` function encodeQualifiedShieldedCoinInfo(coin): { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; }; ``` Encode a [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) into a Compact's `QualifiedShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / encodeRawTokenType # Function: encodeRawTokenType() ``` function encodeRawTokenType(tt): Uint8Array; ``` Encode a raw [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md) into a `Uint8Array` for use in Compact's `RawTokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / encodeShieldedCoinInfo # Function: encodeShieldedCoinInfo() ``` function encodeShieldedCoinInfo(coin): { color: Uint8Array; nonce: Uint8Array; value: bigint; }; ``` Encode a [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) into a Compact's `ShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / encodeUserAddress # Function: encodeUserAddress() ``` function encodeUserAddress(addr): Uint8Array; ``` Encode a [UserAddress](/api-reference/ledger/type-aliases/UserAddress.md) into a `Uint8Array` for use in Compact's `UserAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # entryPointHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / entryPointHash # Function: entryPointHash() ``` function entryPointHash(entryPoint): string; ``` Computes the (hex-encoded) hash of a given contract entry point. Used in composable contracts to reference the called contract's entry point ID in-circuit. ## Parameters[​](#parameters "Direct link to Parameters") ### entryPoint[​](#entrypoint "Direct link to entryPoint") `string` | `Uint8Array`<`ArrayBufferLike`> ## Returns[​](#returns "Direct link to Returns") `string` --- # feeToken > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / feeToken # Function: feeToken() ``` function feeToken(): DustTokenType; ``` The system token type for fees ## Returns[​](#returns "Direct link to Returns") [`DustTokenType`](/api-reference/ledger/type-aliases/DustTokenType.md) --- # hashToCurve > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / hashToCurve # Function: hashToCurve() ``` function hashToCurve(align, val): Value; ``` **`Internal`** Internal implementation of the hash to curve primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/ledger/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](#hashtocurve) does not have alignment [align](#hashtocurve) --- # leafHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / leafHash # Function: leafHash() ``` function leafHash(value): AlignedValue; ``` **`Internal`** Internal implementation of the Merkle tree leaf hash primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### value[​](#value "Direct link to value") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) --- # maxAlignedSize > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / maxAlignedSize # Function: maxAlignedSize() ``` function maxAlignedSize(alignment): bigint; ``` **`Internal`** Internal implementation of the max aligned size primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### alignment[​](#alignment "Direct link to alignment") [`Alignment`](/api-reference/ledger/type-aliases/Alignment.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # maxField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / maxField # Function: maxField() ``` function maxField(): bigint; ``` Returns the maximum representable value in the proof systems scalar field (that is, 1 less than the prime modulus) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # nativeToken > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / nativeToken # Function: nativeToken() ``` function nativeToken(): UnshieldedTokenType; ``` The base/system token type ## Returns[​](#returns "Direct link to Returns") [`UnshieldedTokenType`](/api-reference/ledger/type-aliases/UnshieldedTokenType.md) --- # parseCheckResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / parseCheckResult # Function: parseCheckResult() ``` function parseCheckResult(result): (undefined | bigint)[]; ``` Parses the result of a proof-server check call ## Parameters[​](#parameters "Direct link to Parameters") ### result[​](#result "Direct link to result") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") (`undefined` | `bigint`)\[] --- # partitionTranscripts > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / partitionTranscripts # Function: partitionTranscripts() ``` function partitionTranscripts(calls, params): PartitionedTranscript[]; ``` Finalizes a set of programs against their initial contexts, resulting in guaranteed and fallible [Transcript](/api-reference/ledger/type-aliases/Transcript.md)s, optimally allocated, and heuristically covered for gas fees. ## Parameters[​](#parameters "Direct link to Parameters") ### calls[​](#calls "Direct link to calls") [`PreTranscript`](/api-reference/ledger/classes/PreTranscript.md)\[] ### params[​](#params "Direct link to params") [`LedgerParameters`](/api-reference/ledger/classes/LedgerParameters.md) ## Returns[​](#returns "Direct link to Returns") [`PartitionedTranscript`](/api-reference/ledger/type-aliases/PartitionedTranscript.md)\[] --- # persistentCommit > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / persistentCommit # Function: persistentCommit() ``` function persistentCommit( align, val, opening): Value; ``` **`Internal`** Internal implementation of the persistent commitment primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/ledger/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/ledger/type-aliases/Value.md) ### opening[​](#opening "Direct link to opening") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](#persistentcommit) does not have alignment [align](#persistentcommit), [opening](#persistentcommit) does not encode a 32-byte bytestring, or any component has a compress alignment --- # persistentHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / persistentHash # Function: persistentHash() ``` function persistentHash(align, val): Value; ``` **`Internal`** Internal implementation of the persistent hash primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/ledger/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](#persistenthash) does not have alignment [align](#persistenthash), or any component has a compress alignment --- # proofDataIntoSerializedPreimage > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / proofDataIntoSerializedPreimage # Function: proofDataIntoSerializedPreimage() ``` function proofDataIntoSerializedPreimage( input, output, public_transcript, private_transcript_outputs, key_location?): Uint8Array; ``` Converts input, output, and transcript information into a proof preimage suitable to pass to a `ProvingProvider`. The `key_location` parameter is a string used to identify the circuit by proving machinery, for backwards-compatibility, if unset it defaults to `'dummy'`. ## Parameters[​](#parameters "Direct link to Parameters") ### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ### public\_transcript[​](#public_transcript "Direct link to public_transcript") [`Op`](/api-reference/ledger/type-aliases/Op.md)<[`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)>\[] ### private\_transcript\_outputs[​](#private_transcript_outputs "Direct link to private_transcript_outputs") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md)\[] ### key\_location?[​](#key_location "Direct link to key_location?") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # rawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / rawTokenType # Function: rawTokenType() ``` function rawTokenType(domain_sep, contract): string; ``` Derives the raw [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md) associated with a particular [DomainSeparator](/api-reference/ledger/type-aliases/DomainSeparator.md) and contract. ## Parameters[​](#parameters "Direct link to Parameters") ### domain\_sep[​](#domain_sep "Direct link to domain_sep") [`DomainSeparator`](/api-reference/ledger/type-aliases/DomainSeparator.md) ### contract[​](#contract "Direct link to contract") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # runProgram > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / runProgram # Function: runProgram() ``` function runProgram( initial, ops, cost_model, gas_limit?): VmResults; ``` Runs a VM program against an initial stack, with an optional gas limit ## Parameters[​](#parameters "Direct link to Parameters") ### initial[​](#initial "Direct link to initial") [`VmStack`](/api-reference/ledger/classes/VmStack.md) ### ops[​](#ops "Direct link to ops") [`Op`](/api-reference/ledger/type-aliases/Op.md)<`null`>\[] ### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/ledger/classes/CostModel.md) ### gas\_limit?[​](#gas_limit "Direct link to gas_limit?") [`RunningCost`](/api-reference/ledger/type-aliases/RunningCost.md) ## Returns[​](#returns "Direct link to Returns") [`VmResults`](/api-reference/ledger/classes/VmResults.md) --- # runtimeCoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / runtimeCoinCommitment # Function: runtimeCoinCommitment() ``` function runtimeCoinCommitment(coin, recipient): AlignedValue; ``` **`Internal`** Internal implementation of the runtime's coin commitment primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ### recipient[​](#recipient "Direct link to recipient") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) --- # runtimeCoinNullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / runtimeCoinNullifier # Function: runtimeCoinNullifier() ``` function runtimeCoinNullifier(coin, sender_evidence): AlignedValue; ``` **`Internal`** Internal implementation of the runtime's coin nullifier primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ### sender\_evidence[​](#sender_evidence "Direct link to sender_evidence") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/ledger/type-aliases/AlignedValue.md) --- # sampleCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleCoinPublicKey # Function: sampleCoinPublicKey() ``` function sampleCoinPublicKey(): string; ``` Samples a dummy user coin public key, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleContractAddress # Function: sampleContractAddress() ``` function sampleContractAddress(): string; ``` Samples a uniform contract address, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleDustSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleDustSecretKey # Function: sampleDustSecretKey() ``` function sampleDustSecretKey(): DustSecretKey; ``` ## Returns[​](#returns "Direct link to Returns") [`DustSecretKey`](/api-reference/ledger/classes/DustSecretKey.md) --- # sampleEncryptionPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleEncryptionPublicKey # Function: sampleEncryptionPublicKey() ``` function sampleEncryptionPublicKey(): string; ``` Samples a dummy user encryption public key, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleIntentHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleIntentHash # Function: sampleIntentHash() ``` function sampleIntentHash(): string; ``` Samples a dummy user intent hash, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleRawTokenType # Function: sampleRawTokenType() ``` function sampleRawTokenType(): string; ``` Samples a uniform raw token type, for use in testing to construct both the shielded and unshielded token types. ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleSigningKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleSigningKey # Function: sampleSigningKey() ``` function sampleSigningKey(): string; ``` Randomly samples a [SigningKey](/api-reference/ledger/type-aliases/SigningKey.md). ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / sampleUserAddress # Function: sampleUserAddress() ``` function sampleUserAddress(): string; ``` Samples a uniform user address, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # shieldedToken > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / shieldedToken # Function: shieldedToken() ``` function shieldedToken(): ShieldedTokenType; ``` Default shielded token type for testing ## Returns[​](#returns "Direct link to Returns") [`ShieldedTokenType`](/api-reference/ledger/type-aliases/ShieldedTokenType.md) --- # signatureVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / signatureVerifyingKey # Function: signatureVerifyingKey() ``` function signatureVerifyingKey(sk): string; ``` Returns the verifying key for a given signing key ## Parameters[​](#parameters "Direct link to Parameters") ### sk[​](#sk "Direct link to sk") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # signData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / signData # Function: signData() ``` function signData(key, data): string; ``` Signs arbitrary data with the given signing key. WARNING: Do not expose access to this function for valuable keys for data that is not strictly controlled! ## Parameters[​](#parameters "Direct link to Parameters") ### key[​](#key "Direct link to key") `string` ### data[​](#data "Direct link to data") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # signingKeyFromBip340 > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / signingKeyFromBip340 # Function: signingKeyFromBip340() ``` function signingKeyFromBip340(data): string; ``` Creates a [SigningKey](/api-reference/ledger/type-aliases/SigningKey.md) from provided Bip340 private key. ## Parameters[​](#parameters "Direct link to Parameters") ### data[​](#data "Direct link to data") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # transientCommit > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / transientCommit # Function: transientCommit() ``` function transientCommit( align, val, opening): Value; ``` **`Internal`** Internal implementation of the transient commitment primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/ledger/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/ledger/type-aliases/Value.md) ### opening[​](#opening "Direct link to opening") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](#transientcommit) does not have alignment [align](#transientcommit), or [opening](#transientcommit) does not encode a field element --- # transientHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / transientHash # Function: transientHash() ``` function transientHash(align, val): Value; ``` **`Internal`** Internal implementation of the transient hash primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/ledger/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](#transienthash) does not have alignment [align](#transienthash) --- # unshieldedToken > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / unshieldedToken # Function: unshieldedToken() ``` function unshieldedToken(): UnshieldedTokenType; ``` Default unshielded token type for testing ## Returns[​](#returns "Direct link to Returns") [`UnshieldedTokenType`](/api-reference/ledger/type-aliases/UnshieldedTokenType.md) --- # updatedValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / updatedValue # Function: updatedValue() ``` function updatedValue( ctime, initialValue, genInfo, now, params): bigint; ``` ## Parameters[​](#parameters "Direct link to Parameters") ### ctime[​](#ctime "Direct link to ctime") `Date` ### initialValue[​](#initialvalue "Direct link to initialValue") `bigint` ### genInfo[​](#geninfo "Direct link to genInfo") [`DustGenerationInfo`](/api-reference/ledger/type-aliases/DustGenerationInfo.md) ### now[​](#now "Direct link to now") `Date` ### params[​](#params "Direct link to params") [`DustParameters`](/api-reference/ledger/classes/DustParameters.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # upgradeFromTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / upgradeFromTransient # Function: upgradeFromTransient() ``` function upgradeFromTransient(transient): Value; ``` **`Internal`** Internal implementation of the upgrade from transient primitive ## Parameters[​](#parameters "Direct link to Parameters") ### transient[​](#transient "Direct link to transient") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [transient](#upgradefromtransient) does not encode a field element --- # valueToBigInt > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / valueToBigInt # Function: valueToBigInt() ``` function valueToBigInt(x): bigint; ``` **`Internal`** Internal conversion between field-aligned binary values and bigints within the scalar field ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") [`Value`](/api-reference/ledger/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") `bigint` ## Throws[​](#throws "Direct link to Throws") If the value does not encode a field element --- # verifySignature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / verifySignature # Function: verifySignature() ``` function verifySignature( vk, data, signature): boolean; ``` Verifies if a signature is correct ## Parameters[​](#parameters "Direct link to Parameters") ### vk[​](#vk "Direct link to vk") `string` ### data[​](#data "Direct link to data") `Uint8Array` ### signature[​](#signature "Direct link to signature") `string` ## Returns[​](#returns "Direct link to Returns") `boolean` --- # globals > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** # @midnight/ledger v8.0.3 ## Classes[​](#classes "Direct link to Classes") * [Binding](/api-reference/ledger/classes/Binding.md) * [ChargedState](/api-reference/ledger/classes/ChargedState.md) * [ClaimRewardsTransaction](/api-reference/ledger/classes/ClaimRewardsTransaction.md) * [CoinSecretKey](/api-reference/ledger/classes/CoinSecretKey.md) * [ContractCall](/api-reference/ledger/classes/ContractCall.md) * [ContractCallPrototype](/api-reference/ledger/classes/ContractCallPrototype.md) * [ContractDeploy](/api-reference/ledger/classes/ContractDeploy.md) * [ContractMaintenanceAuthority](/api-reference/ledger/classes/ContractMaintenanceAuthority.md) * [ContractOperation](/api-reference/ledger/classes/ContractOperation.md) * [ContractOperationVersion](/api-reference/ledger/classes/ContractOperationVersion.md) * [ContractOperationVersionedVerifierKey](/api-reference/ledger/classes/ContractOperationVersionedVerifierKey.md) * [ContractState](/api-reference/ledger/classes/ContractState.md) * [CostModel](/api-reference/ledger/classes/CostModel.md) * [DustActions](/api-reference/ledger/classes/DustActions.md) * [DustGenerationState](/api-reference/ledger/classes/DustGenerationState.md) * [DustLocalState](/api-reference/ledger/classes/DustLocalState.md) * [DustLocalStateWithChanges](/api-reference/ledger/classes/DustLocalStateWithChanges.md) * [DustParameters](/api-reference/ledger/classes/DustParameters.md) * [DustRegistration](/api-reference/ledger/classes/DustRegistration.md) * [DustSecretKey](/api-reference/ledger/classes/DustSecretKey.md) * [DustSpend](/api-reference/ledger/classes/DustSpend.md) * [DustState](/api-reference/ledger/classes/DustState.md) * [DustStateChanges](/api-reference/ledger/classes/DustStateChanges.md) * [DustUtxoState](/api-reference/ledger/classes/DustUtxoState.md) * [EncryptionSecretKey](/api-reference/ledger/classes/EncryptionSecretKey.md) * [Event](/api-reference/ledger/classes/Event.md) * [Intent](/api-reference/ledger/classes/Intent.md) * [LedgerParameters](/api-reference/ledger/classes/LedgerParameters.md) * [LedgerState](/api-reference/ledger/classes/LedgerState.md) * [MaintenanceUpdate](/api-reference/ledger/classes/MaintenanceUpdate.md) * [MerkleTreeCollapsedUpdate](/api-reference/ledger/classes/MerkleTreeCollapsedUpdate.md) * [NoBinding](/api-reference/ledger/classes/NoBinding.md) * [NoProof](/api-reference/ledger/classes/NoProof.md) * [PreBinding](/api-reference/ledger/classes/PreBinding.md) * [PrePartitionContractCall](/api-reference/ledger/classes/PrePartitionContractCall.md) * [PreProof](/api-reference/ledger/classes/PreProof.md) * [PreTranscript](/api-reference/ledger/classes/PreTranscript.md) * [Proof](/api-reference/ledger/classes/Proof.md) * [QueryContext](/api-reference/ledger/classes/QueryContext.md) * [QueryResults](/api-reference/ledger/classes/QueryResults.md) * [ReplaceAuthority](/api-reference/ledger/classes/ReplaceAuthority.md) * [SignatureEnabled](/api-reference/ledger/classes/SignatureEnabled.md) * [SignatureErased](/api-reference/ledger/classes/SignatureErased.md) * [StateBoundedMerkleTree](/api-reference/ledger/classes/StateBoundedMerkleTree.md) * [StateMap](/api-reference/ledger/classes/StateMap.md) * [StateValue](/api-reference/ledger/classes/StateValue.md) * [SystemTransaction](/api-reference/ledger/classes/SystemTransaction.md) * [Transaction](/api-reference/ledger/classes/Transaction.md) * [TransactionContext](/api-reference/ledger/classes/TransactionContext.md) * [TransactionCostModel](/api-reference/ledger/classes/TransactionCostModel.md) * [TransactionResult](/api-reference/ledger/classes/TransactionResult.md) * [UnshieldedOffer](/api-reference/ledger/classes/UnshieldedOffer.md) * [UtxoMeta](/api-reference/ledger/classes/UtxoMeta.md) * [UtxoState](/api-reference/ledger/classes/UtxoState.md) * [VerifiedTransaction](/api-reference/ledger/classes/VerifiedTransaction.md) * [VerifierKeyInsert](/api-reference/ledger/classes/VerifierKeyInsert.md) * [VerifierKeyRemove](/api-reference/ledger/classes/VerifierKeyRemove.md) * [VmResults](/api-reference/ledger/classes/VmResults.md) * [VmStack](/api-reference/ledger/classes/VmStack.md) * [WellFormedStrictness](/api-reference/ledger/classes/WellFormedStrictness.md) * [ZswapChainState](/api-reference/ledger/classes/ZswapChainState.md) * [ZswapInput](/api-reference/ledger/classes/ZswapInput.md) * [ZswapLocalState](/api-reference/ledger/classes/ZswapLocalState.md) * [ZswapLocalStateWithChanges](/api-reference/ledger/classes/ZswapLocalStateWithChanges.md) * [ZswapOffer](/api-reference/ledger/classes/ZswapOffer.md) * [ZswapOutput](/api-reference/ledger/classes/ZswapOutput.md) * [ZswapSecretKeys](/api-reference/ledger/classes/ZswapSecretKeys.md) * [ZswapStateChanges](/api-reference/ledger/classes/ZswapStateChanges.md) * [ZswapTransient](/api-reference/ledger/classes/ZswapTransient.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md) * [Alignment](/api-reference/ledger/type-aliases/Alignment.md) * [AlignmentAtom](/api-reference/ledger/type-aliases/AlignmentAtom.md) * [AlignmentSegment](/api-reference/ledger/type-aliases/AlignmentSegment.md) * [Bindingish](/api-reference/ledger/type-aliases/Bindingish.md) * [BlockContext](/api-reference/ledger/type-aliases/BlockContext.md) * [CallContext](/api-reference/ledger/type-aliases/CallContext.md) * [ClaimKind](/api-reference/ledger/type-aliases/ClaimKind.md) * [CoinCommitment](/api-reference/ledger/type-aliases/CoinCommitment.md) * [CoinPublicKey](/api-reference/ledger/type-aliases/CoinPublicKey.md) * [CommunicationCommitment](/api-reference/ledger/type-aliases/CommunicationCommitment.md) * [CommunicationCommitmentRand](/api-reference/ledger/type-aliases/CommunicationCommitmentRand.md) * [ContractAction](/api-reference/ledger/type-aliases/ContractAction.md) * [ContractAddress](/api-reference/ledger/type-aliases/ContractAddress.md) * [DomainSeparator](/api-reference/ledger/type-aliases/DomainSeparator.md) * [DustCommitment](/api-reference/ledger/type-aliases/DustCommitment.md) * [DustGenerationInfo](/api-reference/ledger/type-aliases/DustGenerationInfo.md) * [DustGenerationUniquenessInfo](/api-reference/ledger/type-aliases/DustGenerationUniquenessInfo.md) * [DustInitialNonce](/api-reference/ledger/type-aliases/DustInitialNonce.md) * [DustNonce](/api-reference/ledger/type-aliases/DustNonce.md) * [DustNullifier](/api-reference/ledger/type-aliases/DustNullifier.md) * [DustOutput](/api-reference/ledger/type-aliases/DustOutput.md) * [DustPublicKey](/api-reference/ledger/type-aliases/DustPublicKey.md) * [DustTokenType](/api-reference/ledger/type-aliases/DustTokenType.md) * [Effects](/api-reference/ledger/type-aliases/Effects.md) * [EncodedStateValue](/api-reference/ledger/type-aliases/EncodedStateValue.md) * [EncPublicKey](/api-reference/ledger/type-aliases/EncPublicKey.md) * [ErasedTransactionResult](/api-reference/ledger/type-aliases/ErasedTransactionResult.md) * [FeePrices](/api-reference/ledger/type-aliases/FeePrices.md) * [FinalizedTransaction](/api-reference/ledger/type-aliases/FinalizedTransaction.md) * [Fr](/api-reference/ledger/type-aliases/Fr.md) * [GatherResult](/api-reference/ledger/type-aliases/GatherResult.md) * [IntentHash](/api-reference/ledger/type-aliases/IntentHash.md) * [Key](/api-reference/ledger/type-aliases/Key.md) * [Nonce](/api-reference/ledger/type-aliases/Nonce.md) * [NormalizedCost](/api-reference/ledger/type-aliases/NormalizedCost.md) * [Nullifier](/api-reference/ledger/type-aliases/Nullifier.md) * [Op](/api-reference/ledger/type-aliases/Op.md) * [PartitionedTranscript](/api-reference/ledger/type-aliases/PartitionedTranscript.md) * [ProofErasedTransaction](/api-reference/ledger/type-aliases/ProofErasedTransaction.md) * [Proofish](/api-reference/ledger/type-aliases/Proofish.md) * [ProvingKeyMaterial](/api-reference/ledger/type-aliases/ProvingKeyMaterial.md) * [ProvingProvider](/api-reference/ledger/type-aliases/ProvingProvider.md) * [PublicAddress](/api-reference/ledger/type-aliases/PublicAddress.md) * [QualifiedDustOutput](/api-reference/ledger/type-aliases/QualifiedDustOutput.md) * [QualifiedShieldedCoinInfo](/api-reference/ledger/type-aliases/QualifiedShieldedCoinInfo.md) * [RawTokenType](/api-reference/ledger/type-aliases/RawTokenType.md) * [RunningCost](/api-reference/ledger/type-aliases/RunningCost.md) * [SegmentSpecifier](/api-reference/ledger/type-aliases/SegmentSpecifier.md) * [ShieldedCoinInfo](/api-reference/ledger/type-aliases/ShieldedCoinInfo.md) * [ShieldedTokenType](/api-reference/ledger/type-aliases/ShieldedTokenType.md) * [Signature](/api-reference/ledger/type-aliases/Signature.md) * [SignatureVerifyingKey](/api-reference/ledger/type-aliases/SignatureVerifyingKey.md) * [Signaturish](/api-reference/ledger/type-aliases/Signaturish.md) * [SigningKey](/api-reference/ledger/type-aliases/SigningKey.md) * [SingleUpdate](/api-reference/ledger/type-aliases/SingleUpdate.md) * [SyntheticCost](/api-reference/ledger/type-aliases/SyntheticCost.md) * [TokenType](/api-reference/ledger/type-aliases/TokenType.md) * [TransactionHash](/api-reference/ledger/type-aliases/TransactionHash.md) * [TransactionId](/api-reference/ledger/type-aliases/TransactionId.md) * [Transcript](/api-reference/ledger/type-aliases/Transcript.md) * [UnprovenInput](/api-reference/ledger/type-aliases/UnprovenInput.md) * [UnprovenIntent](/api-reference/ledger/type-aliases/UnprovenIntent.md) * [UnprovenOffer](/api-reference/ledger/type-aliases/UnprovenOffer.md) * [UnprovenOutput](/api-reference/ledger/type-aliases/UnprovenOutput.md) * [UnprovenTransaction](/api-reference/ledger/type-aliases/UnprovenTransaction.md) * [UnprovenTransient](/api-reference/ledger/type-aliases/UnprovenTransient.md) * [UnshieldedTokenType](/api-reference/ledger/type-aliases/UnshieldedTokenType.md) * [UserAddress](/api-reference/ledger/type-aliases/UserAddress.md) * [Utxo](/api-reference/ledger/type-aliases/Utxo.md) * [UtxoOutput](/api-reference/ledger/type-aliases/UtxoOutput.md) * [UtxoSpend](/api-reference/ledger/type-aliases/UtxoSpend.md) * [Value](/api-reference/ledger/type-aliases/Value.md) ## Functions[​](#functions "Direct link to Functions") * [addressFromKey](/api-reference/ledger/functions/addressFromKey.md) * [bigIntModFr](/api-reference/ledger/functions/bigIntModFr.md) * [bigIntToValue](/api-reference/ledger/functions/bigIntToValue.md) * [coinCommitment](/api-reference/ledger/functions/coinCommitment.md) * [coinNullifier](/api-reference/ledger/functions/coinNullifier.md) * [communicationCommitment](/api-reference/ledger/functions/communicationCommitment.md) * [communicationCommitmentRandomness](/api-reference/ledger/functions/communicationCommitmentRandomness.md) * [createCheckPayload](/api-reference/ledger/functions/createCheckPayload.md) * [createProvingPayload](/api-reference/ledger/functions/createProvingPayload.md) * [~~createProvingTransactionPayload~~](/api-reference/ledger/functions/createProvingTransactionPayload.md) * [createShieldedCoinInfo](/api-reference/ledger/functions/createShieldedCoinInfo.md) * [decodeCoinPublicKey](/api-reference/ledger/functions/decodeCoinPublicKey.md) * [decodeContractAddress](/api-reference/ledger/functions/decodeContractAddress.md) * [decodeQualifiedShieldedCoinInfo](/api-reference/ledger/functions/decodeQualifiedShieldedCoinInfo.md) * [decodeRawTokenType](/api-reference/ledger/functions/decodeRawTokenType.md) * [decodeShieldedCoinInfo](/api-reference/ledger/functions/decodeShieldedCoinInfo.md) * [decodeUserAddress](/api-reference/ledger/functions/decodeUserAddress.md) * [degradeToTransient](/api-reference/ledger/functions/degradeToTransient.md) * [dummyContractAddress](/api-reference/ledger/functions/dummyContractAddress.md) * [dummyUserAddress](/api-reference/ledger/functions/dummyUserAddress.md) * [ecAdd](/api-reference/ledger/functions/ecAdd.md) * [ecMul](/api-reference/ledger/functions/ecMul.md) * [ecMulGenerator](/api-reference/ledger/functions/ecMulGenerator.md) * [encodeCoinPublicKey](/api-reference/ledger/functions/encodeCoinPublicKey.md) * [encodeContractAddress](/api-reference/ledger/functions/encodeContractAddress.md) * [encodeQualifiedShieldedCoinInfo](/api-reference/ledger/functions/encodeQualifiedShieldedCoinInfo.md) * [encodeRawTokenType](/api-reference/ledger/functions/encodeRawTokenType.md) * [encodeShieldedCoinInfo](/api-reference/ledger/functions/encodeShieldedCoinInfo.md) * [encodeUserAddress](/api-reference/ledger/functions/encodeUserAddress.md) * [entryPointHash](/api-reference/ledger/functions/entryPointHash.md) * [feeToken](/api-reference/ledger/functions/feeToken.md) * [hashToCurve](/api-reference/ledger/functions/hashToCurve.md) * [leafHash](/api-reference/ledger/functions/leafHash.md) * [maxAlignedSize](/api-reference/ledger/functions/maxAlignedSize.md) * [maxField](/api-reference/ledger/functions/maxField.md) * [nativeToken](/api-reference/ledger/functions/nativeToken.md) * [parseCheckResult](/api-reference/ledger/functions/parseCheckResult.md) * [partitionTranscripts](/api-reference/ledger/functions/partitionTranscripts.md) * [persistentCommit](/api-reference/ledger/functions/persistentCommit.md) * [persistentHash](/api-reference/ledger/functions/persistentHash.md) * [proofDataIntoSerializedPreimage](/api-reference/ledger/functions/proofDataIntoSerializedPreimage.md) * [rawTokenType](/api-reference/ledger/functions/rawTokenType.md) * [runProgram](/api-reference/ledger/functions/runProgram.md) * [runtimeCoinCommitment](/api-reference/ledger/functions/runtimeCoinCommitment.md) * [runtimeCoinNullifier](/api-reference/ledger/functions/runtimeCoinNullifier.md) * [sampleCoinPublicKey](/api-reference/ledger/functions/sampleCoinPublicKey.md) * [sampleContractAddress](/api-reference/ledger/functions/sampleContractAddress.md) * [sampleDustSecretKey](/api-reference/ledger/functions/sampleDustSecretKey.md) * [sampleEncryptionPublicKey](/api-reference/ledger/functions/sampleEncryptionPublicKey.md) * [sampleIntentHash](/api-reference/ledger/functions/sampleIntentHash.md) * [sampleRawTokenType](/api-reference/ledger/functions/sampleRawTokenType.md) * [sampleSigningKey](/api-reference/ledger/functions/sampleSigningKey.md) * [sampleUserAddress](/api-reference/ledger/functions/sampleUserAddress.md) * [shieldedToken](/api-reference/ledger/functions/shieldedToken.md) * [signatureVerifyingKey](/api-reference/ledger/functions/signatureVerifyingKey.md) * [signData](/api-reference/ledger/functions/signData.md) * [signingKeyFromBip340](/api-reference/ledger/functions/signingKeyFromBip340.md) * [transientCommit](/api-reference/ledger/functions/transientCommit.md) * [transientHash](/api-reference/ledger/functions/transientHash.md) * [unshieldedToken](/api-reference/ledger/functions/unshieldedToken.md) * [updatedValue](/api-reference/ledger/functions/updatedValue.md) * [upgradeFromTransient](/api-reference/ledger/functions/upgradeFromTransient.md) * [valueToBigInt](/api-reference/ledger/functions/valueToBigInt.md) * [verifySignature](/api-reference/ledger/functions/verifySignature.md) --- # AlignedValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / AlignedValue # Type Alias: AlignedValue ``` type AlignedValue = { alignment: Alignment; value: Value; }; ``` An onchain data value, in field-aligned binary format, annotated with its alignment. ## Properties[​](#properties "Direct link to Properties") ### alignment[​](#alignment "Direct link to alignment") ``` alignment: Alignment; ``` *** ### value[​](#value "Direct link to value") ``` value: Value; ``` --- # Alignment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Alignment # Type Alias: Alignment ``` type Alignment = AlignmentSegment[]; ``` The alignment of an onchain field-aligned binary data value. --- # AlignmentAtom > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / AlignmentAtom # Type Alias: AlignmentAtom ``` type AlignmentAtom = | { tag: "compress"; } | { tag: "field"; } | { length: number; tag: "bytes"; }; ``` A atom in a larger [Alignment](/api-reference/ledger/type-aliases/Alignment.md). --- # AlignmentSegment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / AlignmentSegment # Type Alias: AlignmentSegment ``` type AlignmentSegment = | { tag: "option"; value: Alignment[]; } | { tag: "atom"; value: AlignmentAtom; }; ``` A segment in a larger [Alignment](/api-reference/ledger/type-aliases/Alignment.md). --- # Bindingish > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Bindingish # Type Alias: Bindingish ``` type Bindingish = | Binding | PreBinding | NoBinding; ``` Whether an intent has binding cryptography applied or not. An intent's content can no longer be modified after it is [Binding](/api-reference/ledger/classes/Binding.md). --- # BlockContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / BlockContext # Type Alias: BlockContext ``` type BlockContext = { lastBlockTime: bigint; parentBlockHash: string; secondsSinceEpoch: bigint; secondsSinceEpochErr: number; }; ``` Context information about the block forwarded to [CallContext](/api-reference/ledger/type-aliases/CallContext.md). ## Properties[​](#properties "Direct link to Properties") ### lastBlockTime[​](#lastblocktime "Direct link to lastBlockTime") ``` lastBlockTime: bigint; ``` The [secondsSinceEpoch](#secondssinceepoch) of the previous block *** ### parentBlockHash[​](#parentblockhash "Direct link to parentBlockHash") ``` parentBlockHash: string; ``` The hash of the block prior to this transaction, as a hex-encoded string *** ### secondsSinceEpoch[​](#secondssinceepoch "Direct link to secondsSinceEpoch") ``` secondsSinceEpoch: bigint; ``` The seconds since the UNIX epoch that have elapsed *** ### secondsSinceEpochErr[​](#secondssinceepocherr "Direct link to secondsSinceEpochErr") ``` secondsSinceEpochErr: number; ``` The maximum error on [secondsSinceEpoch](#secondssinceepoch) that should occur, as a positive seconds value --- # CallContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CallContext # Type Alias: CallContext ``` type CallContext = { balance: Map; caller?: PublicAddress; comIndices: Map; lastBlockTime: bigint; ownAddress: ContractAddress; parentBlockHash: string; secondsSinceEpoch: bigint; secondsSinceEpochErr: number; }; ``` The context information of a call provided to the VM. ## Properties[​](#properties "Direct link to Properties") ### balance[​](#balance "Direct link to balance") ``` balance: Map; ``` The balances held by the called contract at the time it was called. *** ### caller?[​](#caller "Direct link to caller?") ``` optional caller: PublicAddress; ``` A public address identifying an entity. *** ### comIndices[​](#comindices "Direct link to comIndices") ``` comIndices: Map; ``` The commitment indices map accessible to the contract. *** ### lastBlockTime[​](#lastblocktime "Direct link to lastBlockTime") ``` lastBlockTime: bigint; ``` The [secondsSinceEpoch](#secondssinceepoch) of the previous block *** ### ownAddress[​](#ownaddress "Direct link to ownAddress") ``` ownAddress: ContractAddress; ``` *** ### parentBlockHash[​](#parentblockhash "Direct link to parentBlockHash") ``` parentBlockHash: string; ``` The hash of the block prior to this transaction, as a hex-encoded string *** ### secondsSinceEpoch[​](#secondssinceepoch "Direct link to secondsSinceEpoch") ``` secondsSinceEpoch: bigint; ``` The seconds since the UNIX epoch that have elapsed *** ### secondsSinceEpochErr[​](#secondssinceepocherr "Direct link to secondsSinceEpochErr") ``` secondsSinceEpochErr: number; ``` The maximum error on [secondsSinceEpoch](#secondssinceepoch) that should occur, as a positive seconds value --- # ClaimKind > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ClaimKind # Type Alias: ClaimKind ``` type ClaimKind = "Reward" | "CardanoBridge"; ``` --- # CoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CoinCommitment # Type Alias: CoinCommitment ``` type CoinCommitment = string; ``` A Zswap coin commitment, as a hex-encoded 256-bit bitstring --- # CoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CoinPublicKey # Type Alias: CoinPublicKey ``` type CoinPublicKey = string; ``` A user public key capable of receiving Zswap coins, as a hex-encoded 35-byte string --- # CommunicationCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CommunicationCommitment # Type Alias: CommunicationCommitment ``` type CommunicationCommitment = string; ``` A hex-encoded commitment of data shared between two contracts in a call --- # CommunicationCommitmentRand > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / CommunicationCommitmentRand # Type Alias: CommunicationCommitmentRand ``` type CommunicationCommitmentRand = string; ``` The hex-encoded randomness to [CommunicationCommitment](/api-reference/ledger/type-aliases/CommunicationCommitment.md) --- # ContractAction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractAction # Type Alias: ContractAction\

``` type ContractAction

= | ContractCall

| ContractDeploy | MaintenanceUpdate; ``` An interactions with a contract ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### P[​](#p "Direct link to P") `P` *extends* [`Proofish`](/api-reference/ledger/type-aliases/Proofish.md) --- # ContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ContractAddress # Type Alias: ContractAddress ``` type ContractAddress = string; ``` A contract address, as a hex-encoded 35-byte string --- # DomainSeparator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DomainSeparator # Type Alias: DomainSeparator ``` type DomainSeparator = Uint8Array; ``` A token domain seperator, the pre-stage of `TokenType`, as 32-byte bytearray --- # DustCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustCommitment # Type Alias: DustCommitment ``` type DustCommitment = bigint; ``` --- # DustGenerationInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustGenerationInfo # Type Alias: DustGenerationInfo ``` type DustGenerationInfo = { dtime: Date | undefined; nonce: DustInitialNonce; owner: DustPublicKey; value: bigint; }; ``` ## Properties[​](#properties "Direct link to Properties") ### dtime[​](#dtime "Direct link to dtime") ``` dtime: Date | undefined; ``` *** ### nonce[​](#nonce "Direct link to nonce") ``` nonce: DustInitialNonce; ``` *** ### owner[​](#owner "Direct link to owner") ``` owner: DustPublicKey; ``` *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # DustGenerationUniquenessInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustGenerationUniquenessInfo # Type Alias: DustGenerationUniquenessInfo ``` type DustGenerationUniquenessInfo = { nonce: DustInitialNonce; owner: DustPublicKey; value: bigint; }; ``` ## Properties[​](#properties "Direct link to Properties") ### nonce[​](#nonce "Direct link to nonce") ``` nonce: DustInitialNonce; ``` *** ### owner[​](#owner "Direct link to owner") ``` owner: DustPublicKey; ``` *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # DustInitialNonce > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustInitialNonce # Type Alias: DustInitialNonce ``` type DustInitialNonce = string; ``` --- # DustNonce > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustNonce # Type Alias: DustNonce ``` type DustNonce = bigint; ``` --- # DustNullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustNullifier # Type Alias: DustNullifier ``` type DustNullifier = bigint; ``` --- # DustOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustOutput # Type Alias: DustOutput ``` type DustOutput = { backingNight: DustInitialNonce; ctime: Date; initialValue: bigint; nonce: DustNonce; owner: DustPublicKey; seq: number; }; ``` ## Properties[​](#properties "Direct link to Properties") ### backingNight[​](#backingnight "Direct link to backingNight") ``` backingNight: DustInitialNonce; ``` *** ### ctime[​](#ctime "Direct link to ctime") ``` ctime: Date; ``` *** ### initialValue[​](#initialvalue "Direct link to initialValue") ``` initialValue: bigint; ``` *** ### nonce[​](#nonce "Direct link to nonce") ``` nonce: DustNonce; ``` *** ### owner[​](#owner "Direct link to owner") ``` owner: DustPublicKey; ``` *** ### seq[​](#seq "Direct link to seq") ``` seq: number; ``` --- # DustPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustPublicKey # Type Alias: DustPublicKey ``` type DustPublicKey = bigint; ``` --- # DustTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / DustTokenType # Type Alias: DustTokenType ``` type DustTokenType = { tag: "dust"; }; ``` Dust token type ## Properties[​](#properties "Direct link to Properties") ### tag[​](#tag "Direct link to tag") ``` tag: "dust"; ``` --- # Effects > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Effects # Type Alias: Effects ``` type Effects = { claimedContractCalls: [bigint, ContractAddress, string, Fr][]; claimedNullifiers: Nullifier[]; claimedShieldedReceives: CoinCommitment[]; claimedShieldedSpends: CoinCommitment[]; claimedUnshieldedSpends: Map<[TokenType, PublicAddress], bigint>; shieldedMints: Map; unshieldedInputs: Map; unshieldedMints: Map; unshieldedOutputs: Map; }; ``` The contract-external effects of a transcript. ## Properties[​](#properties "Direct link to Properties") ### claimedContractCalls[​](#claimedcontractcalls "Direct link to claimedContractCalls") ``` claimedContractCalls: [bigint, ContractAddress, string, Fr][]; ``` The contracts called from this contract. The values are, in order: * The sequence number of this call * The contract being called * The entry point being called * The communications commitment *** ### claimedNullifiers[​](#claimednullifiers "Direct link to claimedNullifiers") ``` claimedNullifiers: Nullifier[]; ``` The nullifiers (spends) this contract call requires *** ### claimedShieldedReceives[​](#claimedshieldedreceives "Direct link to claimedShieldedReceives") ``` claimedShieldedReceives: CoinCommitment[]; ``` The coin commitments (outputs) this contract call requires, as coins received *** ### claimedShieldedSpends[​](#claimedshieldedspends "Direct link to claimedShieldedSpends") ``` claimedShieldedSpends: CoinCommitment[]; ``` The coin commitments (outputs) this contract call requires, as coins sent *** ### claimedUnshieldedSpends[​](#claimedunshieldedspends "Direct link to claimedUnshieldedSpends") ``` claimedUnshieldedSpends: Map<[TokenType, PublicAddress], bigint>; ``` The unshielded UTXO outputs this contract expects to be present. *** ### shieldedMints[​](#shieldedmints "Direct link to shieldedMints") ``` shieldedMints: Map; ``` The shielded tokens minted in this call, as a map from hex-encoded 256-bit domain separators to unsigned 64-bit integers. *** ### unshieldedInputs[​](#unshieldedinputs "Direct link to unshieldedInputs") ``` unshieldedInputs: Map; ``` The unshielded inputs this contract expects. *** ### unshieldedMints[​](#unshieldedmints "Direct link to unshieldedMints") ``` unshieldedMints: Map; ``` The unshielded tokens minted in this call, as a map from hex-encoded 256-bit domain separators to unsigned 64-bit integers. *** ### unshieldedOutputs[​](#unshieldedoutputs "Direct link to unshieldedOutputs") ``` unshieldedOutputs: Map; ``` The unshielded outputs this contract authorizes. --- # EncodedStateValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / EncodedStateValue # Type Alias: EncodedStateValue ``` type EncodedStateValue = | { tag: "null"; } | { content: AlignedValue; tag: "cell"; } | { content: Map; tag: "map"; } | { content: EncodedStateValue[]; tag: "array"; } | { content: [number, Map]; tag: "boundedMerkleTree"; }; ``` An alternative encoding of [StateValue](/api-reference/ledger/classes/StateValue.md) for use in [Op](/api-reference/ledger/type-aliases/Op.md) for technical reasons --- # EncPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / EncPublicKey # Type Alias: EncPublicKey ``` type EncPublicKey = string; ``` An encryption public key, used to inform users of new coins sent to them --- # ErasedTransactionResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ErasedTransactionResult # Type Alias: ErasedTransactionResult ``` type ErasedTransactionResult = { successfulSegments?: Map; type: "success" | "partialSuccess" | "failure"; }; ``` The result status of applying a transaction, without error message ## Properties[​](#properties "Direct link to Properties") ### successfulSegments?[​](#successfulsegments "Direct link to successfulSegments?") ``` optional successfulSegments: Map; ``` *** ### type[​](#type "Direct link to type") ``` type: "success" | "partialSuccess" | "failure"; ``` --- # FeePrices > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / FeePrices # Type Alias: FeePrices ``` type FeePrices = { blockUsageFactor: number; computeFactor: number; overallPrice: number; readFactor: number; writeFactor: number; }; ``` The fee prices for transaction ## Properties[​](#properties "Direct link to Properties") ### blockUsageFactor[​](#blockusagefactor "Direct link to blockUsageFactor") ``` blockUsageFactor: number; ``` The price factor of block usage. *** ### computeFactor[​](#computefactor "Direct link to computeFactor") ``` computeFactor: number; ``` The price factor of time spent in single-threaded compute. *** ### overallPrice[​](#overallprice "Direct link to overallPrice") ``` overallPrice: number; ``` The overall price of a full block in an average cost dimension. *** ### readFactor[​](#readfactor "Direct link to readFactor") ``` readFactor: number; ``` The price factor of time spent reading from disk. *** ### writeFactor[​](#writefactor "Direct link to writeFactor") ``` writeFactor: number; ``` The price factor of time spent writing to disk. --- # FinalizedTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / FinalizedTransaction # Type Alias: FinalizedTransaction ``` type FinalizedTransaction = Transaction; ``` A transaction that has been proven and finalized. --- # Fr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Fr # Type Alias: Fr ``` type Fr = Uint8Array; ``` An internal encoding of a value of the proof systems scalar field --- # GatherResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / GatherResult # Type Alias: GatherResult ``` type GatherResult = | { content: AlignedValue; tag: "read"; } | { content: EncodedStateValue; tag: "log"; }; ``` An individual result of observing the results of a non-verifying VM program execution --- # IntentHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / IntentHash # Type Alias: IntentHash ``` type IntentHash = string; ``` The hash of an intent, as a hex-encoded 256-bit bytestring --- # Key > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Key # Type Alias: Key ``` type Key = | { tag: "value"; value: AlignedValue; } | { tag: "stack"; }; ``` A key used to index into an array or map in the onchain VM --- # Nonce > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Nonce # Type Alias: Nonce ``` type Nonce = string; ``` A Zswap nonce, as a hex-encoded 256-bit string --- # NormalizedCost > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / NormalizedCost # Type Alias: NormalizedCost ``` type NormalizedCost = { blockUsage: number; bytesChurned: number; bytesWritten: number; computeTime: number; readTime: number; }; ``` A normalized form of [SyntheticCost](/api-reference/ledger/type-aliases/SyntheticCost.md). ## Properties[​](#properties "Direct link to Properties") ### blockUsage[​](#blockusage "Direct link to blockUsage") ``` blockUsage: number; ``` The number of bytes of blockspace used *** ### bytesChurned[​](#byteschurned "Direct link to bytesChurned") ``` bytesChurned: number; ``` The number of (modelled) bytes written temporarily or overwritten. *** ### bytesWritten[​](#byteswritten "Direct link to bytesWritten") ``` bytesWritten: number; ``` The net number of (modelled) bytes written, i.e. max(0, absolute written bytes less deleted bytes). *** ### computeTime[​](#computetime "Direct link to computeTime") ``` computeTime: number; ``` The amount of (modelled) time spent in single-threaded compute, measured in picoseconds. *** ### readTime[​](#readtime "Direct link to readTime") ``` readTime: number; ``` The amount of (modelled) time spent reading from disk, measured in picoseconds. --- # Nullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Nullifier # Type Alias: Nullifier ``` type Nullifier = string; ``` A Zswap nullifier, as a hex-encoded 256-bit bitstring --- # Op > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Op # Type Alias: Op\ ``` type Op = | { noop: { n: number; }; } | "lt" | "eq" | "type" | "size" | "new" | "and" | "or" | "neg" | "log" | "root" | "pop" | { popeq: { cached: boolean; result: R; }; } | { addi: { immediate: number; }; } | { subi: { immediate: number; }; } | { push: { storage: boolean; value: EncodedStateValue; }; } | { branch: { skip: number; }; } | { jmp: { skip: number; }; } | "add" | "sub" | { concat: { cached: boolean; n: number; }; } | "member" | { rem: { cached: boolean; }; } | { dup: { n: number; }; } | { swap: { n: number; }; } | { idx: { cached: boolean; path: Key[]; pushPath: boolean; }; } | { ins: { cached: boolean; n: number; }; } | "ckpt"; ``` An individual operation in the onchain VM ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### R[​](#r "Direct link to R") `R` `null` or [AlignedValue](/api-reference/ledger/type-aliases/AlignedValue.md), for gathering and verifying mode respectively --- # PartitionedTranscript > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / PartitionedTranscript # Type Alias: PartitionedTranscript ``` type PartitionedTranscript = [ | Transcript | undefined, | Transcript | undefined]; ``` --- # ProofErasedTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ProofErasedTransaction # Type Alias: ProofErasedTransaction ``` type ProofErasedTransaction = Transaction; ``` A transaction with proofs erased. --- # Proofish > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Proofish # Type Alias: Proofish ``` type Proofish = | Proof | PreProof | NoProof; ``` How proofs are currently being represented, between: * Actual zero-knowledge proofs, as should be transmitted to the network * The data required to *produce* proofs, for constructing and preparing transactions. * Proofs not being provided, largely for testing use or replaying already validated transactions. --- # ProvingKeyMaterial > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ProvingKeyMaterial # Type Alias: ProvingKeyMaterial ``` type ProvingKeyMaterial = { ir: Uint8Array; proverKey: Uint8Array; verifierKey: Uint8Array; }; ``` Contains the raw file contents required for proving ## Properties[​](#properties "Direct link to Properties") ### ir[​](#ir "Direct link to ir") ``` ir: Uint8Array; ``` *** ### proverKey[​](#proverkey "Direct link to proverKey") ``` proverKey: Uint8Array; ``` *** ### verifierKey[​](#verifierkey "Direct link to verifierKey") ``` verifierKey: Uint8Array; ``` --- # ProvingProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ProvingProvider # Type Alias: ProvingProvider ``` type ProvingProvider = { check: Promise<(undefined | bigint)[]>; prove: Promise>; }; ``` ## Methods[​](#methods "Direct link to Methods") ### check()[​](#check "Direct link to check()") ``` check(serializedPreimage, keyLocation): Promise<(undefined | bigint)[]>; ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### serializedPreimage[​](#serializedpreimage "Direct link to serializedPreimage") `Uint8Array` ##### keyLocation[​](#keylocation "Direct link to keyLocation") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<(`undefined` | `bigint`)\[]> *** ### prove()[​](#prove "Direct link to prove()") ``` prove( serializedPreimage, keyLocation, overwriteBindingInput?): Promise>; ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### serializedPreimage[​](#serializedpreimage-1 "Direct link to serializedPreimage") `Uint8Array` ##### keyLocation[​](#keylocation-1 "Direct link to keyLocation") `string` ##### overwriteBindingInput?[​](#overwritebindinginput "Direct link to overwriteBindingInput?") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> --- # PublicAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / PublicAddress # Type Alias: PublicAddress ``` type PublicAddress = | { address: UserAddress; tag: "user"; } | { address: ContractAddress; tag: "contract"; }; ``` A public address that an entity can be identified by --- # QualifiedDustOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / QualifiedDustOutput # Type Alias: QualifiedDustOutput ``` type QualifiedDustOutput = { backingNight: DustInitialNonce; ctime: Date; initialValue: bigint; mtIndex: bigint; nonce: DustNonce; owner: DustPublicKey; seq: number; }; ``` ## Properties[​](#properties "Direct link to Properties") ### backingNight[​](#backingnight "Direct link to backingNight") ``` backingNight: DustInitialNonce; ``` *** ### ctime[​](#ctime "Direct link to ctime") ``` ctime: Date; ``` *** ### initialValue[​](#initialvalue "Direct link to initialValue") ``` initialValue: bigint; ``` *** ### mtIndex[​](#mtindex "Direct link to mtIndex") ``` mtIndex: bigint; ``` *** ### nonce[​](#nonce "Direct link to nonce") ``` nonce: DustNonce; ``` *** ### owner[​](#owner "Direct link to owner") ``` owner: DustPublicKey; ``` *** ### seq[​](#seq "Direct link to seq") ``` seq: number; ``` --- # QualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / QualifiedShieldedCoinInfo # Type Alias: QualifiedShieldedCoinInfo ``` type QualifiedShieldedCoinInfo = { mt_index: bigint; nonce: Nonce; type: RawTokenType; value: bigint; }; ``` Information required to spend an existing coin, alongside authorization of the owner ## Properties[​](#properties "Direct link to Properties") ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` The coin's location in the chain's Merkle tree of coin commitments Bounded to be a non-negative 64-bit integer *** ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The coin's type, identifying the currency it represents *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # RawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / RawTokenType # Type Alias: RawTokenType ``` type RawTokenType = string; ``` The internal identifier attached to a [TokenType](/api-reference/ledger/type-aliases/TokenType.md), as a hex-encoded string. --- # RunningCost > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / RunningCost # Type Alias: RunningCost ``` type RunningCost = { bytesDeleted: bigint; bytesWritten: bigint; computeTime: bigint; readTime: bigint; }; ``` A running tally of synthetic resource costs. ## Properties[​](#properties "Direct link to Properties") ### bytesDeleted[​](#bytesdeleted "Direct link to bytesDeleted") ``` bytesDeleted: bigint; ``` The number of (modelled) bytes deleted. *** ### bytesWritten[​](#byteswritten "Direct link to bytesWritten") ``` bytesWritten: bigint; ``` The number of (modelled) bytes written. *** ### computeTime[​](#computetime "Direct link to computeTime") ``` computeTime: bigint; ``` The amount of (modelled) time spent in single-threaded compute, measured in picoseconds. *** ### readTime[​](#readtime "Direct link to readTime") ``` readTime: bigint; ``` The amount of (modelled) time spent reading from disk, measured in picoseconds. --- # SegmentSpecifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SegmentSpecifier # Type Alias: SegmentSpecifier ``` type SegmentSpecifier = | { tag: "first"; } | { tag: "guaranteedOnly"; } | { tag: "random"; } | { tag: "specific"; value: number; }; ``` Specifies where something should execute in a transaction. Options are: * As the first thing (alias for `{ tag: 'specific', value: 1 }`) * In any physical segment, but only utilising the guaranteed logical segment * In a random segment (ideal for merging with other intents) * In a specific directly provided segment (in the range 1..65535) --- # ShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ShieldedCoinInfo # Type Alias: ShieldedCoinInfo ``` type ShieldedCoinInfo = { nonce: Nonce; type: RawTokenType; value: bigint; }; ``` Information required to create a new coin, alongside details about the recipient ## Properties[​](#properties "Direct link to Properties") ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The coin's type, identifying the currency it represents *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # ShieldedTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / ShieldedTokenType # Type Alias: ShieldedTokenType ``` type ShieldedTokenType = { raw: RawTokenType; tag: "shielded"; }; ``` Shielded token type (or color), as a hex-encoded 35-byte string ## Properties[​](#properties "Direct link to Properties") ### raw[​](#raw "Direct link to raw") ``` raw: RawTokenType; ``` *** ### tag[​](#tag "Direct link to tag") ``` tag: "shielded"; ``` --- # Signature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Signature # Type Alias: Signature ``` type Signature = string; ``` A hex-encoded signature BIP-340 signature, with a 3-byte version prefix --- # SignatureVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SignatureVerifyingKey # Type Alias: SignatureVerifyingKey ``` type SignatureVerifyingKey = string; ``` A hex-encoded signature BIP-340 verifying key, with a 3-byte version prefix --- # Signaturish > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Signaturish # Type Alias: Signaturish ``` type Signaturish = | SignatureEnabled | SignatureErased; ``` --- # SigningKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SigningKey # Type Alias: SigningKey ``` type SigningKey = string; ``` A hex-encoded signature BIP-340 signing key, with a 3-byte version prefix --- # SingleUpdate > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SingleUpdate # Type Alias: SingleUpdate ``` type SingleUpdate = | ReplaceAuthority | VerifierKeyRemove | VerifierKeyInsert; ``` A single update instruction in a [MaintenanceUpdate](/api-reference/ledger/classes/MaintenanceUpdate.md). --- # SyntheticCost > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / SyntheticCost # Type Alias: SyntheticCost ``` type SyntheticCost = { blockUsage: bigint; bytesChurned: bigint; bytesWritten: bigint; computeTime: bigint; readTime: bigint; }; ``` A modelled cost of a transaction or block. ## Properties[​](#properties "Direct link to Properties") ### blockUsage[​](#blockusage "Direct link to blockUsage") ``` blockUsage: bigint; ``` The number of bytes of blockspace used *** ### bytesChurned[​](#byteschurned "Direct link to bytesChurned") ``` bytesChurned: bigint; ``` The number of (modelled) bytes written temporarily or overwritten. *** ### bytesWritten[​](#byteswritten "Direct link to bytesWritten") ``` bytesWritten: bigint; ``` The net number of (modelled) bytes written, i.e. max(0, absolute written bytes less deleted bytes). *** ### computeTime[​](#computetime "Direct link to computeTime") ``` computeTime: bigint; ``` The amount of (modelled) time spent in single-threaded compute, measured in picoseconds. *** ### readTime[​](#readtime "Direct link to readTime") ``` readTime: bigint; ``` The amount of (modelled) time spent reading from disk, measured in picoseconds. --- # TokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / TokenType # Type Alias: TokenType ``` type TokenType = | UnshieldedTokenType | ShieldedTokenType | DustTokenType; ``` A token type (or color), as a hex-encoded 35-byte string, shielded, unshielded, or Dust --- # TransactionHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / TransactionHash # Type Alias: TransactionHash ``` type TransactionHash = string; ``` The hash of a transaction, as a hex-encoded 256-bit bytestring --- # TransactionId > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / TransactionId # Type Alias: TransactionId ``` type TransactionId = string; ``` A transaction identifier, used to index merged transactions --- # Transcript > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Transcript # Type Alias: Transcript\ ``` type Transcript = { effects: Effects; gas: RunningCost; program: Op[]; }; ``` A transcript of operations, to be recorded in a transaction ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### R[​](#r "Direct link to R") `R` ## Properties[​](#properties "Direct link to Properties") ### effects[​](#effects "Direct link to effects") ``` effects: Effects; ``` The effects of the transcript, which are checked before execution, and must match those constructed by [program](#program) *** ### gas[​](#gas "Direct link to gas") ``` gas: RunningCost; ``` The execution budget for this transcript, which [program](#program) must not exceed *** ### program[​](#program "Direct link to program") ``` program: Op[]; ``` The sequence of operations that this transcript captured --- # UnprovenInput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnprovenInput # Type Alias: UnprovenInput ``` type UnprovenInput = ZswapInput; ``` A type representing a transaction that has not been proven yet --- # UnprovenIntent > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnprovenIntent # Type Alias: UnprovenIntent ``` type UnprovenIntent = Intent; ``` A type representing an intent that has not been proven yet. --- # UnprovenOffer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnprovenOffer # Type Alias: UnprovenOffer ``` type UnprovenOffer = ZswapOffer; ``` A type representing an offer that has not been proven yet. --- # UnprovenOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnprovenOutput # Type Alias: UnprovenOutput ``` type UnprovenOutput = ZswapOutput; ``` A type representing a transaction output that has not been proven yet. --- # UnprovenTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnprovenTransaction # Type Alias: UnprovenTransaction ``` type UnprovenTransaction = Transaction; ``` A transaction that has not yet been proven. --- # UnprovenTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnprovenTransient # Type Alias: UnprovenTransient ``` type UnprovenTransient = ZswapTransient; ``` A type representing a transaction transient that has not been proven yet. --- # UnshieldedTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UnshieldedTokenType # Type Alias: UnshieldedTokenType ``` type UnshieldedTokenType = { raw: RawTokenType; tag: "unshielded"; }; ``` Unshielded token type (or color), as a hex-encoded 35-byte string ## Properties[​](#properties "Direct link to Properties") ### raw[​](#raw "Direct link to raw") ``` raw: RawTokenType; ``` *** ### tag[​](#tag "Direct link to tag") ``` tag: "unshielded"; ``` --- # UserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UserAddress # Type Alias: UserAddress ``` type UserAddress = string; ``` A user public key address, as a hex-encoded 35-byte string --- # Utxo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Utxo # Type Alias: Utxo ``` type Utxo = { intentHash: IntentHash; outputNo: number; owner: UserAddress; type: RawTokenType; value: bigint; }; ``` An unspent transaction output ## Properties[​](#properties "Direct link to Properties") ### intentHash[​](#intenthash "Direct link to intentHash") ``` intentHash: IntentHash; ``` The hash of the intent outputting this UTXO *** ### outputNo[​](#outputno "Direct link to outputNo") ``` outputNo: number; ``` The output number of this UTXO in its parent [Intent](/api-reference/ledger/classes/Intent.md). *** ### owner[​](#owner "Direct link to owner") ``` owner: UserAddress; ``` The address owning these tokens. *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The token type of this UTXO *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The amount of tokens this UTXO represents --- # UtxoOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UtxoOutput # Type Alias: UtxoOutput ``` type UtxoOutput = { owner: UserAddress; type: RawTokenType; value: bigint; }; ``` An output appearing in an [Intent](/api-reference/ledger/classes/Intent.md). ## Properties[​](#properties "Direct link to Properties") ### owner[​](#owner "Direct link to owner") ``` owner: UserAddress; ``` The address owning these tokens. *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The token type of this UTXO *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The amount of tokens this UTXO represents --- # UtxoSpend > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / UtxoSpend # Type Alias: UtxoSpend ``` type UtxoSpend = { intentHash: IntentHash; outputNo: number; owner: SignatureVerifyingKey; type: RawTokenType; value: bigint; }; ``` An input appearing in an [Intent](/api-reference/ledger/classes/Intent.md), or a user's local book-keeping. ## Properties[​](#properties "Direct link to Properties") ### intentHash[​](#intenthash "Direct link to intentHash") ``` intentHash: IntentHash; ``` The hash of the intent outputting this UTXO *** ### outputNo[​](#outputno "Direct link to outputNo") ``` outputNo: number; ``` The output number of this UTXO in its parent [Intent](/api-reference/ledger/classes/Intent.md). *** ### owner[​](#owner "Direct link to owner") ``` owner: SignatureVerifyingKey; ``` The signing key owning these tokens. *** ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The token type of this UTXO *** ### value[​](#value "Direct link to value") ``` value: bigint; ``` The amount of tokens this UTXO represents --- # Value > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/ledger v8.0.3**](/api-reference/ledger.md) *** [@midnight/ledger](/api-reference/ledger/globals.md) / Value # Type Alias: Value ``` type Value = Uint8Array[]; ``` An onchain data value, in field-aligned binary format. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Indexer API v4 The Midnight Indexer API exposes a GraphQL API that enables clients to query and subscribe to blockchain data—blocks, transactions, contracts, DUST generation, and shielded/unshielded transaction events, indexed from the Midnight blockchain. These capabilities facilitate both historical lookups and real-time monitoring. ## Version information[​](#version-information "Direct link to Version information") * **Current API version**: v4. Disclaimer The examples provided here are illustrative and might need updating if the API changes. Always consider [`indexer-api/graphql/schema-v4.graphql`](https://github.com/midnightntwrk/midnight-indexer/blob/v4.0.1/indexer-api/graphql/schema-v4.graphql) as the primary source of truth. Adjust queries as necessary to match the latest schema. ## GraphQL schema[​](#graphql-schema "Direct link to GraphQL schema") The GraphQL schema is defined in [`indexer-api/graphql/schema-v4.graphql`](https://github.com/midnightntwrk/midnight-indexer/blob/v4.0.1/indexer-api/graphql/schema-v4.graphql). It specifies all queries, mutations, subscriptions, and their types, including arguments and return structures. ## Overview of operations[​](#overview-of-operations "Direct link to Overview of operations") * **Queries**: Fetch blocks, transactions, contract actions, and DUST generation status. Examples: * Retrieve the latest block or a specific block by hash or height. * Look up transactions by their hash or identifier. * Inspect the current state of a contract action at a given block or transaction offset. * Query unshielded token balances held by contracts. * Query DUST generation status for Cardano stake keys. * **Mutations**: Manage wallet sessions. * `connect(viewingKey: ViewingKey!)`: Creates a session associated with a viewing key. * `disconnect(sessionId: HexEncoded!)`: Ends a previously established session. * **Subscriptions**: Receive real-time updates. * `blocks`: Stream newly indexed blocks. * `contractActions(address, offset)`: Stream contract actions. * `shieldedTransactions(sessionId, ...)`: Stream shielded transaction updates, including relevant transactions and optional progress updates. * `unshieldedTransactions(address)`: Stream unshielded transaction events for a specific address. * `dustLedgerEvents(id)`: Stream DUST ledger events. * `zswapLedgerEvents(id)`: Stream Zswap ledger events. ## API endpoints[​](#api-endpoints "Direct link to API endpoints") The Midnight Indexer API provides two types of endpoints for different use cases. ### HTTP endpoint (queries and mutations)[​](#http-endpoint-queries-and-mutations "Direct link to HTTP endpoint (queries and mutations)") Use the HTTP endpoint for one-time queries and mutations. This endpoint supports standard GraphQL queries for fetching data and mutations for managing wallet sessions. ``` POST https://:/api/v4/graphql Content-Type: application/json ``` ### WebSocket endpoint (subscriptions)[​](#websocket-endpoint-subscriptions "Direct link to WebSocket endpoint (subscriptions)") Use the WebSocket endpoint for real-time data streaming. This endpoint enables subscriptions to blocks, transactions, and other events as they occur on the blockchain. ``` wss://:/api/v4/graphql/ws Sec-WebSocket-Protocol: graphql-transport-ws ``` ## Core scalars[​](#core-scalars "Direct link to Core scalars") The API uses custom scalar types to represent blockchain-specific data formats. Understanding these types is important for creating queries and interpreting responses. * `HexEncoded`: Hex-encoded bytes used for hashes, addresses, and session IDs. * `ViewingKey`: A viewing key in hex or Bech32 format for wallet sessions. * `Unit`: An empty return type for mutations that do not return data. * `UnshieldedAddress`: An unshielded address in Bech32m format, such as `mn_addr_test1...`. Used for unshielded token operations. ## Input types[​](#input-types "Direct link to Input types") The following input types are used to specify query parameters for blocks, transactions, and contract actions. ### BlockOffset (oneOf)[​](#blockoffset-oneof "Direct link to BlockOffset (oneOf)") Used to specify a block by either hash or height: * `hash`: HexEncoded - The block hash * `height`: Int - The block height ### TransactionOffset (oneOf)[​](#transactionoffset-oneof "Direct link to TransactionOffset (oneOf)") Used to specify a transaction by either hash or identifier: * `hash`: HexEncoded - The transaction hash * `identifier`: HexEncoded - The transaction identifier ### ContractActionOffset (oneOf)[​](#contractactionoffset-oneof "Direct link to ContractActionOffset (oneOf)") Used to specify a contract action location: * `blockOffset`: BlockOffset - Query by block (hash or height) * `transactionOffset`: TransactionOffset - Query by transaction (hash or identifier) ## Example queries and mutations[​](#example-queries-and-mutations "Direct link to Example queries and mutations") note These are examples only. To confirm the exact field names and structure, refer to the [schema file](https://github.com/midnightntwrk/midnight-indexer/blob/release/3.0.0/indexer-api/graphql/schema-v3.graphql). ### block(offset: BlockOffset): Block[​](#blockoffset-blockoffset-block "Direct link to block(offset: BlockOffset): Block") Query a block by offset. If no offset is provided, then the latest block is returned. #### Query by height[​](#query-by-height "Direct link to Query by height") ``` query { block(offset: { height: 3 }) { hash height protocolVersion timestamp author parent { hash } transactions { id hash transactionResult { status segments { id success } } } } } ``` ### transactions(offset: TransactionOffset!): \[Transaction!]\![​](#transactionsoffset-transactionoffset-transaction "Direct link to transactions(offset: TransactionOffset!): \[Transaction!]!") Fetch transactions by hash or by identifier. Returns an array of transactions matching the criteria. note The `fees` field is now available on transactions, providing both `paidFees` and `estimatedFees` information. #### Example: Query transactions by hash[​](#example-query-transactions-by-hash "Direct link to Example: Query transactions by hash") This example demonstrates how to retrieve transactions starting from a specific transaction hash using the `hash` offset parameter. ``` query { transactions(offset: { hash: "3031323..." }) { id hash protocolVersion merkleTreeRoot block { height hash } identifiers raw contractActions { __typename ... on ContractDeploy { address state zswapState unshieldedBalances { tokenType amount } } ... on ContractCall { address state entryPoint zswapState unshieldedBalances { tokenType amount } } ... on ContractUpdate { address state zswapState unshieldedBalances { tokenType amount } } } fees { paidFees estimatedFees } transactionResult { status segments { id success } } unshieldedCreatedOutputs { owner value tokenType intentHash outputIndex } unshieldedSpentOutputs { owner value tokenType intentHash outputIndex } } } ``` #### Example: Query transactions by identifier[​](#example-query-transactions-by-identifier "Direct link to Example: Query transactions by identifier") This example shows how to filter transactions using a specific identifier, retrieving both the created and spent unshielded outputs. ``` query { transactions(offset: { identifier: "abc123..." }) { id hash unshieldedCreatedOutputs { owner value tokenType } unshieldedSpentOutputs { owner value tokenType } } } ``` ### contractAction(address: HexEncoded!, offset: ContractActionOffset): ContractAction[​](#contractactionaddress-hexencoded-offset-contractactionoffset-contractaction "Direct link to contractAction(address: HexEncoded!, offset: ContractActionOffset): ContractAction") Retrieve the latest known contract action at a given offset (by block or transaction). If no offset is provided, then it returns the latest state. #### Example: Query latest contract action[​](#example-query-latest-contract-action "Direct link to Example: Query latest contract action") This example retrieves the most recent contract action for a given address without specifying an offset, which returns the latest state. ``` query { contractAction(address: "3031323...") { __typename ... on ContractDeploy { address state zswapState unshieldedBalances { tokenType amount } } ... on ContractCall { address state zswapState entryPoint unshieldedBalances { tokenType amount } } ... on ContractUpdate { address state zswapState unshieldedBalances { tokenType amount } } } } ``` #### Example: Query contract action by block height[​](#example-query-contract-action-by-block-height "Direct link to Example: Query contract action by block height") This example demonstrates how to retrieve a contract action at a specific block height using the `blockOffset` parameter. ``` query { contractAction( address: "3031323...", offset: { blockOffset: { height: 10 } } ) { __typename ... on ContractDeploy { address state zswapState unshieldedBalances { tokenType amount } } ... on ContractCall { address state zswapState entryPoint unshieldedBalances { tokenType amount } } ... on ContractUpdate { address state zswapState unshieldedBalances { tokenType amount } } } } ``` ### dustGenerationStatus(cardanoRewardAddresses: \[CardanoRewardAddress!]!): \[DustGenerationStatus!]\![​](#dustgenerationstatuscardanorewardaddresses-cardanorewardaddress-dustgenerationstatus "Direct link to dustGenerationStatus(cardanoRewardAddresses: \[CardanoRewardAddress!]!): \[DustGenerationStatus!]!") Query DUST generation status for one or more Cardano stake keys. #### Example: Query DUST generation status[​](#example-query-dust-generation-status "Direct link to Example: Query DUST generation status") This example demonstrates how to check the DUST generation status for Cardano stake keys, including registration status, Night balance, generation rate, and current capacity. ``` query { dustGenerationStatus( cardanoRewardAddresses: [ "stake_test1uqtgpdz0chm6jnxx7erfd7rhqfud7t4ajazx8es8xk8x3ts06psdv" ] ) { cardanoRewardAddress dustAddress registered nightBalance generationRate currentCapacity } } ``` The response includes several fields that provide information about DUST generation status and capacity. #### DUST generation parameters[​](#dust-generation-parameters "Direct link to DUST generation parameters") * Generation rate: 8,267 Specks per Star per second. * Maximum capacity: 5 DUST per NIGHT. * The `registered` field indicates if stake key is registered via NativeTokenObservation pallet. * Registration data comes from Cardano mainnet via bridge. Important note on `currentCapacity` The `currentCapacity` field represents the maximum DUST generation capacity based on the Night UTXO balance and elapsed time. This value: * Is accurate until the first DUST fee payment * Might be higher than actual balance after fee payments * Cannot track spent DUST because fee payments are shielded transactions For accurate DUST balance after fee payments, query the connected wallet directly via wallet SDK or DApp Connector API. Use `currentCapacity` as an approximation when wallet connection is unavailable. ## Contract action types[​](#contract-action-types "Direct link to Contract action types") Contract actions represent operations performed on smart contracts within transactions. All ContractAction types implement a common interface and share several fields. ### Common fields[​](#common-fields "Direct link to Common fields") All ContractAction types (ContractDeploy, ContractCall, ContractUpdate) implement the ContractAction interface with these common fields: * `address`: The contract address (HexEncoded) * `state`: The contract state (HexEncoded) * `zswapState`: The contract-specific zswap state at this action (HexEncoded) * `transaction`: The transaction that contains this action ### Action types[​](#action-types "Direct link to Action types") Contract actions can be one of three types: * **ContractDeploy**: Initial contract deployment * **ContractCall**: Invocation of a contract's entry point * **ContractUpdate**: State update to an existing contract Each type implements the ContractAction interface but may have additional fields. For example, ContractCall includes an `entryPoint` field and a reference to its associated `deploy`. ### Unshielded balances[​](#unshielded-balances "Direct link to Unshielded balances") All contract action types include an `unshieldedBalances` field that returns the token balances held by the contract: * **ContractDeploy**: Always returns empty balances because contracts are deployed with a zero balance. * **ContractCall**: Returns balances after the call execution. These balances might be modified by `unshielded_inputs` or `unshielded_outputs` during the call. * **ContractUpdate**: Returns balances after the maintenance update has been applied. #### ContractBalance type[​](#contractbalance-type "Direct link to ContractBalance type") The ContractBalance type represents token holdings for a contract: ``` type ContractBalance { tokenType: HexEncoded! # Token type identifier amount: String! # Balance amount (supports u128 values) } ``` ## Block type[​](#block-type "Direct link to Block type") The Block type represents a blockchain block: * `hash`: The block hash (HexEncoded) * `height`: The block height (Int!) * `protocolVersion`: The protocol version (Int!) * `timestamp`: The UNIX timestamp (Int!) * `author`: The block author (HexEncoded, optional) * `parent`: Reference to the parent block (Block, optional) * `transactions`: Array of transactions within this block (\[Transaction!]!) ## Transaction type[​](#transaction-type "Direct link to Transaction type") The Transaction type represents a blockchain transaction with its associated data: * `id`: The transaction ID (Int!) * `hash`: The transaction hash (HexEncoded) * `protocolVersion`: The protocol version (Int!) * `transactionResult`: The result of applying the transaction to the ledger state * `fees`: Fee information including both paid and estimated fees * `identifiers`: Transaction identifiers array (\[HexEncoded!]!) * `raw`: The raw transaction content (HexEncoded) * `merkleTreeRoot`: The merkle-tree root (HexEncoded) * `block`: Reference to the block containing this transaction * `contractActions`: Array of contract actions within this transaction * `unshieldedCreatedOutputs`: UTXOs created by this transaction * `unshieldedSpentOutputs`: UTXOs spent by this transaction ### TransactionResult type[​](#transactionresult-type "Direct link to TransactionResult type") The result of applying a transaction to the ledger state: * `status`: TransactionResultStatus (SUCCESS, PARTIAL\_SUCCESS, or FAILURE) * `segments`: Optional array of segment results for partial success cases ### TransactionFees type[​](#transactionfees-type "Direct link to TransactionFees type") Fee information for a transaction: * `paidFees`: The actual fees paid for this transaction in DUST (String) * `estimatedFees`: The estimated fees that were calculated for this transaction in DUST (String) ## Unshielded token types[​](#unshielded-token-types "Direct link to Unshielded token types") Unshielded tokens are publicly visible on-chain assets that can be tracked and queried. The following types represent unshielded UTXOs and their associated data. ### UnshieldedUtxo[​](#unshieldedutxo "Direct link to UnshieldedUtxo") Represents an unshielded UTXO (Unspent Transaction Output): * `owner`: The owner's address in Bech32m format * `intentHash`: The hash of the intent that created this output (HexEncoded) * `value`: The UTXO value as a string (to support u128) * `tokenType`: The token type identifier (HexEncoded) * `outputIndex`: The index of this output within its creating transaction * `createdAtTransaction`: Reference to the transaction that created this UTXO * `spentAtTransaction`: Reference to the transaction that spent this UTXO (null if unspent) ## DUST generation types[​](#dust-generation-types "Direct link to DUST generation types") The following types provide information about DUST generation status, capacity, and related ledger events. ### DustGenerationStatus[​](#dustgenerationstatus "Direct link to DustGenerationStatus") DUST generation status for a Cardano stake key: * `cardanoRewardAddress`: The Bech32-encoded Cardano stake address, such as `stake_test1...` or `stake1...` * `dustAddress`: Associated DUST address if registered (HexEncoded, optional) * `registered`: Whether this stake key is registered (Boolean!) * `nightBalance`: NIGHT balance backing generation (String) * `generationRate`: Generation rate in Specks per second (String) * `currentCapacity`: Current DUST generation capacity in Specks - represents maximum possible balance, may be higher than actual balance after fee payments (String) ### DustLedgerEvent[​](#dustledgerevent "Direct link to DustLedgerEvent") DUST ledger events track changes to the DUST generation system. These events are emitted when DUST UTXOs are created, generation parameters are updated, or spends are processed. The following event types are available: * `DustInitialUtxo`: Initial DUST UTXO creation event * `DustGenerationDtimeUpdate`: DUST generation decay time update * `DustSpendProcessed`: DUST spend processing event * `ParamChange`: DUST parameter change event All DUST ledger event types share common fields: * `id`: Event ID (Int!) * `raw`: Raw event data (HexEncoded) * `maxId`: Maximum ID of all DUST events (Int!) ## Mutations[​](#mutations "Direct link to Mutations") Mutations allow the client to connect a wallet (establishing a session) and disconnect it. ### connect(viewingKey: ViewingKey!): HexEncoded\![​](#connectviewingkey-viewingkey-hexencoded "Direct link to connect(viewingKey: ViewingKey!): HexEncoded!") Establishes a session for a given wallet viewing key. Returns the session ID that can be used for shielded transaction subscriptions. #### Viewing key format support[​](#viewing-key-format-support "Direct link to Viewing key format support") The viewing key can be provided in either of two formats: * **Bech32m** (preferred): A base-32 encoded format with a human-readable prefix, for example, `mn_shield-esk_dev1...`. * **Hex** (fallback): A hex-encoded string representing the key bytes. #### Example: Connect with viewing key[​](#example-connect-with-viewing-key "Direct link to Example: Connect with viewing key") This example shows how to establish a session by connecting with a viewing key in Bech32m format. The server returns a session ID that you'll use for subsequent queries. ``` mutation { # Provide the bech32m format: connect(viewingKey: "mn_shield-esk1abcdef...") } ``` **Response**: ``` { "data": { "connect": "sessionIdHere" } } ``` Use this `sessionId` for shielded transactions subscriptions. ### disconnect(sessionId: HexEncoded!): Unit\![​](#disconnectsessionid-hexencoded-unit "Direct link to disconnect(sessionId: HexEncoded!): Unit!") Ends an existing session. Call this method when you no longer need to monitor shielded transactions for a particular wallet. #### Example: Disconnect session[​](#example-disconnect-session "Direct link to Example: Disconnect session") This example demonstrates how to terminate an active session using the session ID returned from the connect mutation. ``` mutation { disconnect(sessionId: "sessionIdHere") } ``` ## Subscriptions: Real-time updates[​](#subscriptions-real-time-updates "Direct link to Subscriptions: Real-time updates") Subscriptions use a WebSocket connection following the [GraphQL over WebSocket](https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md) protocol. After connecting and sending a `connection_init` message, the client can start subscription operations. ### Blocks subscription[​](#blocks-subscription "Direct link to Blocks subscription") `blocks(offset: BlockOffset): Block!` Subscribe to new blocks. The `offset` parameter lets you start receiving from a given block (by height or hash). If omitted, starts from the latest block. #### Example: Subscribe to blocks[​](#example-subscribe-to-blocks "Direct link to Example: Subscribe to blocks") This example shows how to subscribe to new blocks starting from block height 10, receiving real-time updates as new blocks are indexed. ``` { "id": "1", "type": "start", "payload": { "query": "subscription { blocks(offset: { height: 10 }) { hash height protocolVersion timestamp author parent { hash } transactions { id hash } } }" } } ``` When a new block is indexed, the client receives a `next` message. ### Contract actions subscription[​](#contract-actions-subscription "Direct link to Contract actions subscription") `contractActions(address: HexEncoded!, offset: BlockOffset): ContractAction!` Monitor smart contract activity by subscribing to contract actions for a specific address. New contract actions (calls, updates) are pushed as they occur. #### Example: Subscribe to contract actions[​](#example-subscribe-to-contract-actions "Direct link to Example: Subscribe to contract actions") This example demonstrates how to subscribe to contract actions for a specific address, receiving real-time notifications for deployments, calls, and updates. ``` { "id": "2", "type": "start", "payload": { "query": "subscription { contractActions(address:\"3031323...\", offset: { height: 1 }) { __typename ... on ContractDeploy { address state zswapState unshieldedBalances { tokenType amount } } ... on ContractCall { address state zswapState entryPoint unshieldedBalances { tokenType amount } } ... on ContractUpdate { address state zswapState unshieldedBalances { tokenType amount } } } }" } } ``` ### Shielded transactions subscription[​](#shielded-transactions-subscription "Direct link to Shielded transactions subscription") `shieldedTransactions(sessionId: HexEncoded!, index: Int, sendProgressUpdates: Boolean): ShieldedTransactionsEvent!` Subscribes to shielded transaction updates. This includes relevant transactions and possibly Merkle tree updates, as well as `ShieldedTransactionsProgress` events if `sendProgressUpdates` is set to `true`, which is also the default. The `index` parameter can be used to resume from a certain point. Adjust `index` and `offset` arguments as needed. #### Example: Subscribe to shielded transactions[​](#example-subscribe-to-shielded-transactions "Direct link to Example: Subscribe to shielded transactions") This example shows how to subscribe to shielded transactions for a specific session, starting from index 100 and receiving both transaction updates and progress notifications. ``` { "id": "3", "type": "start", "payload": { "query": "subscription { shieldedTransactions(sessionId: \"1CYq6ZsLmn\", index: 100) { __typename ... on ViewingUpdate { index update { __typename ... on MerkleTreeCollapsedUpdate { start end update protocolVersion } ... on RelevantTransaction { start end transaction { id hash } } } } ... on ShieldedTransactionsProgress { highestIndex highestRelevantIndex highestRelevantWalletIndex } } }" } } ``` The subscription returns events as they occur, with different event types providing transaction data and progress updates. #### Event types[​](#event-types "Direct link to Event types") The `ShieldedTransactionsEvent` union type can be one of the following: **ViewingUpdate**: Contains relevant transactions and/or collapsed Merkle tree updates. * `index`: Next start index into the zswap state (Int!) * `update`: Array of ZswapChainStateUpdate items (\[ZswapChainStateUpdate!]!) * `MerkleTreeCollapsedUpdate`: Merkle tree update * `start`: Start index (Int!) * `end`: End index (Int!) * `update`: Hex-encoded merkle-tree collapsed update (HexEncoded) * `protocolVersion`: Protocol version (Int!) * `RelevantTransaction`: Transaction relevant to the wallet * `start`: Start index (Int!) * `end`: End index (Int!) * `transaction`: The relevant transaction (Transaction!) **ShieldedTransactionsProgress**: Synchronization progress information. * `highestIndex`: The highest end index of all currently known transactions (Int!) * `highestRelevantIndex`: The highest end index of all currently known relevant transactions (Int!) * `highestRelevantWalletIndex`: The highest end index for this particular wallet (Int!) ### Unshielded transactions subscription[​](#unshielded-transactions-subscription "Direct link to Unshielded transactions subscription") `unshieldedTransactions(address: UnshieldedAddress!, transactionId: Int): UnshieldedTransactionsEvent!` Subscribes to unshielded transaction events for a specific address. Emits events whenever transactions involve unshielded UTXOs for the given address. #### Parameters[​](#parameters "Direct link to Parameters") * `address`: The unshielded address to monitor (must be in Bech32m format). * `transactionId`: Optional. The transaction ID to start from (defaults to 0). #### Example: Subscribe to unshielded transactions[​](#example-subscribe-to-unshielded-transactions "Direct link to Example: Subscribe to unshielded transactions") This example demonstrates how to subscribe to unshielded transactions for a specific address, receiving notifications about created and spent UTXOs along with progress updates. ``` { "id": "4", "type": "start", "payload": { "query": "subscription { unshieldedTransactions(address: \"mn_addr_test1...\") { __typename ... on UnshieldedTransaction { transaction { hash block { height } } createdUtxos { owner value tokenType intentHash outputIndex } spentUtxos { owner value tokenType intentHash outputIndex } } ... on UnshieldedTransactionsProgress { highestTransactionId } } }" } } ``` #### Event types[​](#event-types-1 "Direct link to Event types") * **UnshieldedTransaction**: When UTXOs are created or spent, includes transaction details and affected UTXOs * **UnshieldedTransactionsProgress**: Periodic synchronization progress updates #### UnshieldedTransactionsEvent[​](#unshieldedtransactionsevent "Direct link to UnshieldedTransactionsEvent") Event payload for the unshielded transaction subscription: * `UnshieldedTransaction`: Contains transaction details and UTXOs created/spent * `transaction`: The transaction that created and/or spent UTXOs * `createdUtxos`: UTXOs created in this transaction for the subscribed address * `spentUtxos`: UTXOs spent in this transaction for the subscribed address * `UnshieldedTransactionsProgress`: Progress information * `highestTransactionId`: The highest transaction ID of all currently known transactions for the subscribed address ### DUST ledger events subscription[​](#dust-ledger-events-subscription "Direct link to DUST ledger events subscription") `dustLedgerEvents(id: Int): DustLedgerEvent!` Subscribe to DUST ledger events. The `id` parameter allows resuming from a specific event. #### Example: Subscribe to DUST ledger events[​](#example-subscribe-to-dust-ledger-events "Direct link to Example: Subscribe to DUST ledger events") This example shows how to subscribe to DUST ledger events, receiving real-time updates about DUST-related operations on the blockchain. ``` { "id": "5", "type": "start", "payload": { "query": "subscription { dustLedgerEvents { id __typename ... on DustInitialUtxo { output { nonce } } raw maxId } }" } } ``` ### Zswap ledger events subscription[​](#zswap-ledger-events-subscription "Direct link to Zswap ledger events subscription") `zswapLedgerEvents(id: Int): ZswapLedgerEvent!` Subscribe to Zswap ledger events. The `id` parameter allows resuming from a specific event. #### Example: Subscribe to Zswap ledger events[​](#example-subscribe-to-zswap-ledger-events "Direct link to Example: Subscribe to Zswap ledger events") This example demonstrates how to subscribe to Zswap ledger events, receiving updates about shielded pool operations and state changes. ``` { "id": "6", "type": "start", "payload": { "query": "subscription { zswapLedgerEvents { id raw maxId } }" } } ``` ## Query limits configuration[​](#query-limits-configuration "Direct link to Query limits configuration") The server may apply limitations to queries (for example, `max-depth`, `max-fields`, `timeout`, and complexity cost). Requests that violate these limits return errors indicating the reason (too many fields, too deep, too costly, or timed out). ### Example error[​](#example-error "Direct link to Example error") ``` { "data": null, "errors": [ { "message": "Query has too many fields: 20. Max fields: 10." } ] } ``` ## Authentication[​](#authentication "Direct link to Authentication") Shielded transactions subscription requires a `sessionId` from the `connect` mutation. ## Regenerate the schema[​](#regenerate-the-schema "Direct link to Regenerate the schema") If you're using the Indexer API and modify the code defining the GraphQL schema, then you'll need to regenerate the schema file. Run the following command: ``` just generate-indexer-api-schema ``` This ensures the schema file stays aligned with code changes. ## Migrate from v1[​](#migrate-from-v1 "Direct link to Migrate from v1") If migrating from API v1, follow these steps: 1. Update endpoint URLs from `/v1/graphql` to `/v4/graphql` (though v1 redirects automatically). 2. Review field name changes (for example, `chainState` → `zswapState` in contract actions). 3. Test thoroughly, because some response structures might have changed. --- # include > For the complete documentation index, see [llms.txt](/llms.txt) Directs the executor to include this field or fragment only when the `if` argument is true. ``` directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`include.if`](#) ● [`Boolean!`](/api-reference/midnight-indexer/types/scalars/boolean.md) non-null scalar[​](#includeifboolean-- "Direct link to includeifboolean--") --- # skip > For the complete documentation index, see [llms.txt](/llms.txt) Directs the executor to skip this field or fragment when the `if` argument is true. ``` directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`skip.if`](#) ● [`Boolean!`](/api-reference/midnight-indexer/types/scalars/boolean.md) non-null scalar[​](#skipifboolean-- "Direct link to skipifboolean--") --- # connect > For the complete documentation index, see [llms.txt](/llms.txt) Connect the wallet with the given viewing key and return a session ID. ``` connect( viewingKey: ViewingKey! ): HexEncoded! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`connect.viewingKey`](#) ● [`ViewingKey!`](/api-reference/midnight-indexer/types/scalars/viewing-key.md) non-null scalar[​](#connectviewingkeyviewingkey-- "Direct link to connectviewingkeyviewingkey--") ### Type[​](#type "Direct link to Type") #### [`HexEncoded`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) scalar[​](#hexencoded- "Direct link to hexencoded-") --- # disconnect > For the complete documentation index, see [llms.txt](/llms.txt) Disconnect the wallet with the given session ID. ``` disconnect( sessionId: HexEncoded! ): Unit! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`disconnect.sessionId`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#disconnectsessionidhexencoded-- "Direct link to disconnectsessionidhexencoded--") ### Type[​](#type "Direct link to Type") #### [`Unit`](/api-reference/midnight-indexer/types/scalars/unit.md) scalar[​](#unit- "Direct link to unit-") --- # block > For the complete documentation index, see [llms.txt](/llms.txt) Find a block for the given optional offset; if not present, the latest block is returned. ``` block( offset: BlockOffset ): Block ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`block.offset`](#) ● [`BlockOffset`](/api-reference/midnight-indexer/types/inputs/block-offset.md) input[​](#blockoffsetblockoffset- "Direct link to blockoffsetblockoffset-") ### Type[​](#type "Direct link to Type") #### [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object[​](#block- "Direct link to block-") A block with its relevant data. --- # committee > For the complete documentation index, see [llms.txt](/llms.txt) Get committee membership for an epoch. ``` committee( epoch: Int! ): [CommitteeMember!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`committee.epoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#committeeepochint-- "Direct link to committeeepochint--") ### Type[​](#type "Direct link to Type") #### [`CommitteeMember`](/api-reference/midnight-indexer/types/objects/committee-member.md) object[​](#committeemember- "Direct link to committeemember-") Committee member for an epoch. --- # contractAction > For the complete documentation index, see [llms.txt](/llms.txt) Find a contract action for the given address and optional offset. ``` contractAction( address: HexEncoded! offset: ContractActionOffset ): ContractAction ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`contractAction.address`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractactionaddresshexencoded-- "Direct link to contractactionaddresshexencoded--") #### [`contractAction.offset`](#) ● [`ContractActionOffset`](/api-reference/midnight-indexer/types/inputs/contract-action-offset.md) input[​](#contractactionoffsetcontractactionoffset- "Direct link to contractactionoffsetcontractactionoffset-") ### Type[​](#type "Direct link to Type") #### [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface[​](#contractaction- "Direct link to contractaction-") A contract action. --- # currentEpochInfo > For the complete documentation index, see [llms.txt](/llms.txt) Get current epoch information. ``` currentEpochInfo: EpochInfo ``` ### Type[​](#type "Direct link to Type") #### [`EpochInfo`](/api-reference/midnight-indexer/types/objects/epoch-info.md) object[​](#epochinfo- "Direct link to epochinfo-") Current epoch information. --- # dParameterHistory > For the complete documentation index, see [llms.txt](/llms.txt) Get the full history of D-parameter changes for governance auditability. ``` dParameterHistory: [DParameterChange!]! ``` ### Type[​](#type "Direct link to Type") #### [`DParameterChange`](/api-reference/midnight-indexer/types/objects/dparameter-change.md) object[​](#dparameterchange- "Direct link to dparameterchange-") D-parameter change record for history queries. --- # dustGenerationStatus > For the complete documentation index, see [llms.txt](/llms.txt) Get DUST generation status for specific Cardano reward addresses. ``` dustGenerationStatus( cardanoRewardAddresses: [CardanoRewardAddress!]! ): [DustGenerationStatus!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`dustGenerationStatus.cardanoRewardAddresses`](#) ● [`[CardanoRewardAddress!]!`](/api-reference/midnight-indexer/types/scalars/cardano-reward-address.md) non-null scalar[​](#dustgenerationstatuscardanorewardaddressescardanorewardaddress-- "Direct link to dustgenerationstatuscardanorewardaddressescardanorewardaddress--") ### Type[​](#type "Direct link to Type") #### [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object[​](#dustgenerationstatus- "Direct link to dustgenerationstatus-") DUST generation status for a specific Cardano reward address. --- # epochPerformance > For the complete documentation index, see [llms.txt](/llms.txt) Get epoch performance for all SPOs. ``` epochPerformance( epoch: Int! limit: Int offset: Int ): [EpochPerf!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`epochPerformance.epoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochperformanceepochint-- "Direct link to epochperformanceepochint--") #### [`epochPerformance.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#epochperformancelimitint- "Direct link to epochperformancelimitint-") #### [`epochPerformance.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#epochperformanceoffsetint- "Direct link to epochperformanceoffsetint-") ### Type[​](#type "Direct link to Type") #### [`EpochPerf`](/api-reference/midnight-indexer/types/objects/epoch-perf.md) object[​](#epochperf- "Direct link to epochperf-") SPO performance for an epoch. --- # epochUtilization > For the complete documentation index, see [llms.txt](/llms.txt) Get epoch utilization (produced/expected ratio). ``` epochUtilization( epoch: Int! ): Float ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`epochUtilization.epoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochutilizationepochint-- "Direct link to epochutilizationepochint--") ### Type[​](#type "Direct link to Type") #### [`Float`](/api-reference/midnight-indexer/types/scalars/float.md) scalar[​](#float- "Direct link to float-") The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point). --- # poolMetadata > For the complete documentation index, see [llms.txt](/llms.txt) Get pool metadata by pool ID. ``` poolMetadata( poolIdHex: String! ): PoolMetadata ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`poolMetadata.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#poolmetadatapoolidhexstring-- "Direct link to poolmetadatapoolidhexstring--") ### Type[​](#type "Direct link to Type") #### [`PoolMetadata`](/api-reference/midnight-indexer/types/objects/pool-metadata.md) object[​](#poolmetadata- "Direct link to poolmetadata-") Pool metadata from Cardano. --- # poolMetadataList > For the complete documentation index, see [llms.txt](/llms.txt) List pool metadata with pagination. ``` poolMetadataList( limit: Int offset: Int withNameOnly: Boolean ): [PoolMetadata!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`poolMetadataList.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#poolmetadatalistlimitint- "Direct link to poolmetadatalistlimitint-") #### [`poolMetadataList.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#poolmetadatalistoffsetint- "Direct link to poolmetadatalistoffsetint-") #### [`poolMetadataList.withNameOnly`](#) ● [`Boolean`](/api-reference/midnight-indexer/types/scalars/boolean.md) scalar[​](#poolmetadatalistwithnameonlyboolean- "Direct link to poolmetadatalistwithnameonlyboolean-") ### Type[​](#type "Direct link to Type") #### [`PoolMetadata`](/api-reference/midnight-indexer/types/objects/pool-metadata.md) object[​](#poolmetadata- "Direct link to poolmetadata-") Pool metadata from Cardano. --- # registeredFirstValidEpochs > For the complete documentation index, see [llms.txt](/llms.txt) Get first valid epoch for each SPO identity. ``` registeredFirstValidEpochs( uptoEpoch: Int ): [FirstValidEpoch!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`registeredFirstValidEpochs.uptoEpoch`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#registeredfirstvalidepochsuptoepochint- "Direct link to registeredfirstvalidepochsuptoepochint-") ### Type[​](#type "Direct link to Type") #### [`FirstValidEpoch`](/api-reference/midnight-indexer/types/objects/first-valid-epoch.md) object[​](#firstvalidepoch- "Direct link to firstvalidepoch-") First valid epoch for an SPO identity. --- # registeredPresence > For the complete documentation index, see [llms.txt](/llms.txt) Get raw presence events for an epoch range. ``` registeredPresence( fromEpoch: Int! toEpoch: Int! ): [PresenceEvent!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`registeredPresence.fromEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredpresencefromepochint-- "Direct link to registeredpresencefromepochint--") #### [`registeredPresence.toEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredpresencetoepochint-- "Direct link to registeredpresencetoepochint--") ### Type[​](#type "Direct link to Type") #### [`PresenceEvent`](/api-reference/midnight-indexer/types/objects/presence-event.md) object[​](#presenceevent- "Direct link to presenceevent-") Presence event for an SPO in an epoch. --- # registeredSpoSeries > For the complete documentation index, see [llms.txt](/llms.txt) Get registration statistics for an epoch range. ``` registeredSpoSeries( fromEpoch: Int! toEpoch: Int! ): [RegisteredStat!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`registeredSpoSeries.fromEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredsposeriesfromepochint-- "Direct link to registeredsposeriesfromepochint--") #### [`registeredSpoSeries.toEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredsposeriestoepochint-- "Direct link to registeredsposeriestoepochint--") ### Type[​](#type "Direct link to Type") #### [`RegisteredStat`](/api-reference/midnight-indexer/types/objects/registered-stat.md) object[​](#registeredstat- "Direct link to registeredstat-") Registration statistics for an epoch. --- # registeredTotalsSeries > For the complete documentation index, see [llms.txt](/llms.txt) Get cumulative registration totals for an epoch range. ``` registeredTotalsSeries( fromEpoch: Int! toEpoch: Int! ): [RegisteredTotals!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`registeredTotalsSeries.fromEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredtotalsseriesfromepochint-- "Direct link to registeredtotalsseriesfromepochint--") #### [`registeredTotalsSeries.toEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredtotalsseriestoepochint-- "Direct link to registeredtotalsseriestoepochint--") ### Type[​](#type "Direct link to Type") #### [`RegisteredTotals`](/api-reference/midnight-indexer/types/objects/registered-totals.md) object[​](#registeredtotals- "Direct link to registeredtotals-") Cumulative registration totals for an epoch. --- # spoByPoolId > For the complete documentation index, see [llms.txt](/llms.txt) Get SPO with metadata by pool ID. ``` spoByPoolId( poolIdHex: String! ): Spo ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoByPoolId.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spobypoolidpoolidhexstring-- "Direct link to spobypoolidpoolidhexstring--") ### Type[​](#type "Direct link to Type") #### [`Spo`](/api-reference/midnight-indexer/types/objects/spo.md) object[​](#spo- "Direct link to spo-") SPO with optional metadata. --- # spoCompositeByPoolId > For the complete documentation index, see [llms.txt](/llms.txt) Get composite SPO data (identity + metadata + performance). ``` spoCompositeByPoolId( poolIdHex: String! ): SpoComposite ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoCompositeByPoolId.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spocompositebypoolidpoolidhexstring-- "Direct link to spocompositebypoolidpoolidhexstring--") ### Type[​](#type "Direct link to Type") #### [`SpoComposite`](/api-reference/midnight-indexer/types/objects/spo-composite.md) object[​](#spocomposite- "Direct link to spocomposite-") Composite SPO data (identity + metadata + performance). --- # spoCount > For the complete documentation index, see [llms.txt](/llms.txt) Get total count of SPOs. ``` spoCount: Int ``` ### Type[​](#type "Direct link to Type") #### [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#int- "Direct link to int-") The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. --- # spoIdentities > For the complete documentation index, see [llms.txt](/llms.txt) List SPO identities with pagination. ``` spoIdentities( limit: Int offset: Int ): [SpoIdentity!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoIdentities.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spoidentitieslimitint- "Direct link to spoidentitieslimitint-") #### [`spoIdentities.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spoidentitiesoffsetint- "Direct link to spoidentitiesoffsetint-") ### Type[​](#type "Direct link to Type") #### [`SpoIdentity`](/api-reference/midnight-indexer/types/objects/spo-identity.md) object[​](#spoidentity- "Direct link to spoidentity-") SPO identity information. --- # spoIdentityByPoolId > For the complete documentation index, see [llms.txt](/llms.txt) Get SPO identity by pool ID. ``` spoIdentityByPoolId( poolIdHex: String! ): SpoIdentity ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoIdentityByPoolId.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spoidentitybypoolidpoolidhexstring-- "Direct link to spoidentitybypoolidpoolidhexstring--") ### Type[​](#type "Direct link to Type") #### [`SpoIdentity`](/api-reference/midnight-indexer/types/objects/spo-identity.md) object[​](#spoidentity- "Direct link to spoidentity-") SPO identity information. --- # spoList > For the complete documentation index, see [llms.txt](/llms.txt) List SPOs with optional search. ``` spoList( limit: Int offset: Int search: String ): [Spo!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoList.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spolistlimitint- "Direct link to spolistlimitint-") #### [`spoList.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spolistoffsetint- "Direct link to spolistoffsetint-") #### [`spoList.search`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#spolistsearchstring- "Direct link to spolistsearchstring-") ### Type[​](#type "Direct link to Type") #### [`Spo`](/api-reference/midnight-indexer/types/objects/spo.md) object[​](#spo- "Direct link to spo-") SPO with optional metadata. --- # spoPerformanceBySpoSk > For the complete documentation index, see [llms.txt](/llms.txt) Get SPO performance by SPO key. ``` spoPerformanceBySpoSk( spoSkHex: String! limit: Int offset: Int ): [EpochPerf!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoPerformanceBySpoSk.spoSkHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spoperformancebysposksposkhexstring-- "Direct link to spoperformancebysposksposkhexstring--") #### [`spoPerformanceBySpoSk.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spoperformancebysposklimitint- "Direct link to spoperformancebysposklimitint-") #### [`spoPerformanceBySpoSk.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spoperformancebysposkoffsetint- "Direct link to spoperformancebysposkoffsetint-") ### Type[​](#type "Direct link to Type") #### [`EpochPerf`](/api-reference/midnight-indexer/types/objects/epoch-perf.md) object[​](#epochperf- "Direct link to epochperf-") SPO performance for an epoch. --- # spoPerformanceLatest > For the complete documentation index, see [llms.txt](/llms.txt) Get latest SPO performance entries. ``` spoPerformanceLatest( limit: Int offset: Int ): [EpochPerf!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`spoPerformanceLatest.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spoperformancelatestlimitint- "Direct link to spoperformancelatestlimitint-") #### [`spoPerformanceLatest.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#spoperformancelatestoffsetint- "Direct link to spoperformancelatestoffsetint-") ### Type[​](#type "Direct link to Type") #### [`EpochPerf`](/api-reference/midnight-indexer/types/objects/epoch-perf.md) object[​](#epochperf- "Direct link to epochperf-") SPO performance for an epoch. --- # stakeDistribution > For the complete documentation index, see [llms.txt](/llms.txt) Get stake distribution with search and ordering. ``` stakeDistribution( limit: Int offset: Int search: String orderByStakeDesc: Boolean ): [StakeShare!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`stakeDistribution.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#stakedistributionlimitint- "Direct link to stakedistributionlimitint-") #### [`stakeDistribution.offset`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#stakedistributionoffsetint- "Direct link to stakedistributionoffsetint-") #### [`stakeDistribution.search`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakedistributionsearchstring- "Direct link to stakedistributionsearchstring-") #### [`stakeDistribution.orderByStakeDesc`](#) ● [`Boolean`](/api-reference/midnight-indexer/types/scalars/boolean.md) scalar[​](#stakedistributionorderbystakedescboolean- "Direct link to stakedistributionorderbystakedescboolean-") ### Type[​](#type "Direct link to Type") #### [`StakeShare`](/api-reference/midnight-indexer/types/objects/stake-share.md) object[​](#stakeshare- "Direct link to stakeshare-") Stake share information for an SPO. Values are sourced from mainchain pool data (e.g., Blockfrost) and keyed by Cardano pool\_id. --- # stakePoolOperators > For the complete documentation index, see [llms.txt](/llms.txt) Get SPO identifiers ordered by performance. ``` stakePoolOperators( limit: Int ): [String!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`stakePoolOperators.limit`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#stakepooloperatorslimitint- "Direct link to stakepooloperatorslimitint-") ### Type[​](#type "Direct link to Type") #### [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#string- "Direct link to string-") The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. --- # termsAndConditionsHistory > For the complete documentation index, see [llms.txt](/llms.txt) Get the full history of Terms and Conditions changes for governance auditability. ``` termsAndConditionsHistory: [TermsAndConditionsChange!]! ``` ### Type[​](#type "Direct link to Type") #### [`TermsAndConditionsChange`](/api-reference/midnight-indexer/types/objects/terms-and-conditions-change.md) object[​](#termsandconditionschange- "Direct link to termsandconditionschange-") Terms and Conditions change record for history queries. --- # transactions > For the complete documentation index, see [llms.txt](/llms.txt) Find transactions for the given offset. ``` transactions( offset: TransactionOffset! ): [Transaction!]! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`transactions.offset`](#) ● [`TransactionOffset!`](/api-reference/midnight-indexer/types/inputs/transaction-offset.md) non-null input[​](#transactionsoffsettransactionoffset-- "Direct link to transactionsoffsettransactionoffset--") ### Type[​](#type "Direct link to Type") #### [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface[​](#transaction- "Direct link to transaction-") A Midnight transaction. --- # blocks > For the complete documentation index, see [llms.txt](/llms.txt) Subscribe to blocks starting at the given offset or at the latest block if the offset is omitted. ``` blocks( offset: BlockOffset ): Block! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`blocks.offset`](#) ● [`BlockOffset`](/api-reference/midnight-indexer/types/inputs/block-offset.md) input[​](#blocksoffsetblockoffset- "Direct link to blocksoffsetblockoffset-") ### Type[​](#type "Direct link to Type") #### [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object[​](#block- "Direct link to block-") A block with its relevant data. --- # contractActions > For the complete documentation index, see [llms.txt](/llms.txt) Subscribe to contract actions with the given address starting at the given offset or at the latest block if the offset is omitted. ``` contractActions( address: HexEncoded! offset: BlockOffset ): ContractAction! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`contractActions.address`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractactionsaddresshexencoded-- "Direct link to contractactionsaddresshexencoded--") #### [`contractActions.offset`](#) ● [`BlockOffset`](/api-reference/midnight-indexer/types/inputs/block-offset.md) input[​](#contractactionsoffsetblockoffset- "Direct link to contractactionsoffsetblockoffset-") ### Type[​](#type "Direct link to Type") #### [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface[​](#contractaction- "Direct link to contractaction-") A contract action. --- # dustLedgerEvents > For the complete documentation index, see [llms.txt](/llms.txt) Subscribe to dust ledger events starting at the given ID or at the very start if omitted. ``` dustLedgerEvents( id: Int ): DustLedgerEvent! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`dustLedgerEvents.id`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#dustledgereventsidint- "Direct link to dustledgereventsidint-") ### Type[​](#type "Direct link to Type") #### [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface[​](#dustledgerevent- "Direct link to dustledgerevent-") A dust related ledger event. --- # shieldedTransactions > For the complete documentation index, see [llms.txt](/llms.txt) Subscribe to shielded transaction events for the given session ID starting at the given index or at zero if omitted. ``` shieldedTransactions( sessionId: HexEncoded! index: Int ): ShieldedTransactionsEvent! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`shieldedTransactions.sessionId`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#shieldedtransactionssessionidhexencoded-- "Direct link to shieldedtransactionssessionidhexencoded--") #### [`shieldedTransactions.index`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#shieldedtransactionsindexint- "Direct link to shieldedtransactionsindexint-") ### Type[​](#type "Direct link to Type") #### [`ShieldedTransactionsEvent`](/api-reference/midnight-indexer/types/unions/shielded-transactions-event.md) union[​](#shieldedtransactionsevent- "Direct link to shieldedtransactionsevent-") An event of the shielded transactions subscription. --- # unshieldedTransactions > For the complete documentation index, see [llms.txt](/llms.txt) Subscribe unshielded transaction events for the given address and the given transaction ID or zero if omitted. ``` unshieldedTransactions( address: UnshieldedAddress! transactionId: Int ): UnshieldedTransactionsEvent! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`unshieldedTransactions.address`](#) ● [`UnshieldedAddress!`](/api-reference/midnight-indexer/types/scalars/unshielded-address.md) non-null scalar[​](#unshieldedtransactionsaddressunshieldedaddress-- "Direct link to unshieldedtransactionsaddressunshieldedaddress--") #### [`unshieldedTransactions.transactionId`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#unshieldedtransactionstransactionidint- "Direct link to unshieldedtransactionstransactionidint-") ### Type[​](#type "Direct link to Type") #### [`UnshieldedTransactionsEvent`](/api-reference/midnight-indexer/types/unions/unshielded-transactions-event.md) union[​](#unshieldedtransactionsevent- "Direct link to unshieldedtransactionsevent-") An event of the unshielded transactions subscription. --- # zswapLedgerEvents > For the complete documentation index, see [llms.txt](/llms.txt) Subscribe to zswap ledger events starting at the given ID or at the very start if omitted. ``` zswapLedgerEvents( id: Int ): ZswapLedgerEvent! ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`zswapLedgerEvents.id`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#zswapledgereventsidint- "Direct link to zswapledgereventsidint-") ### Type[​](#type "Direct link to Type") #### [`ZswapLedgerEvent`](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md) object[​](#zswapledgerevent- "Direct link to zswapledgerevent-") A zswap related ledger event. --- # deprecated > For the complete documentation index, see [llms.txt](/llms.txt) Marks an element of a GraphQL schema as no longer supported. ``` directive @deprecated( reason: String = "No longer supported" ) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | ENUM_VALUE ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`deprecated.reason`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#deprecatedreasonstring- "Direct link to deprecatedreasonstring-") Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/). --- # oneOf > For the complete documentation index, see [llms.txt](/llms.txt) Indicates that an Input Object is a OneOf Input Object (and thus requires exactly one of its field be provided) ``` directive @oneOf on INPUT_OBJECT ``` --- # specifiedBy > For the complete documentation index, see [llms.txt](/llms.txt) Exposes a URL that specifies the behavior of this scalar. ``` directive @specifiedBy(url: String!) on SCALAR ``` ### Arguments[​](#arguments "Direct link to Arguments") #### [`specifiedBy.url`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#specifiedbyurlstring-- "Direct link to specifiedbyurlstring--") The URL that specifies the behavior of this scalar. --- # TransactionResultStatus > For the complete documentation index, see [llms.txt](/llms.txt) The status of the transaction result: success, partial success or failure. ``` enum TransactionResultStatus { SUCCESS PARTIAL_SUCCESS FAILURE } ``` ### Values[​](#values "Direct link to Values") #### [`TransactionResultStatus.SUCCESS`](#)[​](#transactionresultstatussuccess "Direct link to transactionresultstatussuccess") #### [`TransactionResultStatus.PARTIAL_SUCCESS`](#)[​](#transactionresultstatuspartial_success "Direct link to transactionresultstatuspartial_success") #### [`TransactionResultStatus.FAILURE`](#)[​](#transactionresultstatusfailure "Direct link to transactionresultstatusfailure") ### Member Of[​](#member-of "Direct link to Member Of") [`TransactionResult`](/api-reference/midnight-indexer/types/objects/transaction-result.md) object --- # BlockOffset > For the complete documentation index, see [llms.txt](/llms.txt) Either a block hash or a block height. ``` input BlockOffset { hash: HexEncoded height: Int } ``` ### Fields[​](#fields "Direct link to Fields") #### [`BlockOffset.hash`](#) ● [`HexEncoded`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) scalar[​](#blockoffsethashhexencoded- "Direct link to blockoffsethashhexencoded-") A hex-encoded block hash. #### [`BlockOffset.height`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#blockoffsetheightint- "Direct link to blockoffsetheightint-") A block height. ### Member Of[​](#member-of "Direct link to Member Of") [`block`](/api-reference/midnight-indexer/operations/queries/block.md) query ● [`blocks`](/api-reference/midnight-indexer/operations/subscriptions/blocks.md) subscription ● [`ContractActionOffset`](/api-reference/midnight-indexer/types/inputs/contract-action-offset.md) input ● [`contractActions`](/api-reference/midnight-indexer/operations/subscriptions/contract-actions.md) subscription --- # ContractActionOffset > For the complete documentation index, see [llms.txt](/llms.txt) Either a block offset or a transaction offset. ``` input ContractActionOffset { blockOffset: BlockOffset transactionOffset: TransactionOffset } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ContractActionOffset.blockOffset`](#) ● [`BlockOffset`](/api-reference/midnight-indexer/types/inputs/block-offset.md) input[​](#contractactionoffsetblockoffsetblockoffset- "Direct link to contractactionoffsetblockoffsetblockoffset-") Either a block hash or a block height. #### [`ContractActionOffset.transactionOffset`](#) ● [`TransactionOffset`](/api-reference/midnight-indexer/types/inputs/transaction-offset.md) input[​](#contractactionoffsettransactionoffsettransactionoffset- "Direct link to contractactionoffsettransactionoffsettransactionoffset-") Either a transaction hash or a transaction identifier. ### Member Of[​](#member-of "Direct link to Member Of") [`contractAction`](/api-reference/midnight-indexer/operations/queries/contract-action.md) query --- # TransactionOffset > For the complete documentation index, see [llms.txt](/llms.txt) Either a transaction hash or a transaction identifier. ``` input TransactionOffset { hash: HexEncoded identifier: HexEncoded } ``` ### Fields[​](#fields "Direct link to Fields") #### [`TransactionOffset.hash`](#) ● [`HexEncoded`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) scalar[​](#transactionoffsethashhexencoded- "Direct link to transactionoffsethashhexencoded-") A hex-encoded transaction hash. #### [`TransactionOffset.identifier`](#) ● [`HexEncoded`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) scalar[​](#transactionoffsetidentifierhexencoded- "Direct link to transactionoffsetidentifierhexencoded-") A hex-encoded transaction identifier. ### Member Of[​](#member-of "Direct link to Member Of") [`ContractActionOffset`](/api-reference/midnight-indexer/types/inputs/contract-action-offset.md) input ● [`transactions`](/api-reference/midnight-indexer/operations/queries/transactions.md) query --- # ContractAction > For the complete documentation index, see [llms.txt](/llms.txt) A contract action. ``` interface ContractAction { address: HexEncoded! state: HexEncoded! zswapState: HexEncoded! transaction: Transaction! unshieldedBalances: [ContractBalance!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ContractAction.address`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractactionaddresshexencoded-- "Direct link to contractactionaddresshexencoded--") #### [`ContractAction.state`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractactionstatehexencoded-- "Direct link to contractactionstatehexencoded--") #### [`ContractAction.zswapState`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractactionzswapstatehexencoded-- "Direct link to contractactionzswapstatehexencoded--") #### [`ContractAction.transaction`](#) ● [`Transaction!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#contractactiontransactiontransaction-- "Direct link to contractactiontransactiontransaction--") #### [`ContractAction.unshieldedBalances`](#) ● [`[ContractBalance!]!`](/api-reference/midnight-indexer/types/objects/contract-balance.md) non-null object[​](#contractactionunshieldedbalancescontractbalance-- "Direct link to contractactionunshieldedbalancescontractbalance--") ### Returned By[​](#returned-by "Direct link to Returned By") [`contractAction`](/api-reference/midnight-indexer/operations/queries/contract-action.md) query ● [`contractActions`](/api-reference/midnight-indexer/operations/subscriptions/contract-actions.md) subscription ### Member Of[​](#member-of "Direct link to Member Of") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`ContractCall`](/api-reference/midnight-indexer/types/objects/contract-call.md) object ● [`ContractDeploy`](/api-reference/midnight-indexer/types/objects/contract-deploy.md) object ● [`ContractUpdate`](/api-reference/midnight-indexer/types/objects/contract-update.md) object --- # DustLedgerEvent > For the complete documentation index, see [llms.txt](/llms.txt) A dust related ledger event. ``` interface DustLedgerEvent { id: Int! raw: HexEncoded! maxId: Int! protocolVersion: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DustLedgerEvent.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustledgereventidint-- "Direct link to dustledgereventidint--") #### [`DustLedgerEvent.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#dustledgereventrawhexencoded-- "Direct link to dustledgereventrawhexencoded--") #### [`DustLedgerEvent.maxId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustledgereventmaxidint-- "Direct link to dustledgereventmaxidint--") #### [`DustLedgerEvent.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustledgereventprotocolversionint-- "Direct link to dustledgereventprotocolversionint--") ### Returned By[​](#returned-by "Direct link to Returned By") [`dustLedgerEvents`](/api-reference/midnight-indexer/operations/subscriptions/dust-ledger-events.md) subscription ### Member Of[​](#member-of "Direct link to Member Of") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`DustGenerationDtimeUpdate`](/api-reference/midnight-indexer/types/objects/dust-generation-dtime-update.md) object ● [`DustInitialUtxo`](/api-reference/midnight-indexer/types/objects/dust-initial-utxo.md) object ● [`DustSpendProcessed`](/api-reference/midnight-indexer/types/objects/dust-spend-processed.md) object ● [`ParamChange`](/api-reference/midnight-indexer/types/objects/param-change.md) object --- # Transaction > For the complete documentation index, see [llms.txt](/llms.txt) A Midnight transaction. ``` interface Transaction { id: Int! hash: HexEncoded! protocolVersion: Int! raw: HexEncoded! block: Block! contractActions: [ContractAction!]! unshieldedCreatedOutputs: [UnshieldedUtxo!]! unshieldedSpentOutputs: [UnshieldedUtxo!]! zswapLedgerEvents: [ZswapLedgerEvent!]! dustLedgerEvents: [DustLedgerEvent!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`Transaction.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#transactionidint-- "Direct link to transactionidint--") #### [`Transaction.hash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#transactionhashhexencoded-- "Direct link to transactionhashhexencoded--") #### [`Transaction.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#transactionprotocolversionint-- "Direct link to transactionprotocolversionint--") #### [`Transaction.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#transactionrawhexencoded-- "Direct link to transactionrawhexencoded--") #### [`Transaction.block`](#) ● [`Block!`](/api-reference/midnight-indexer/types/objects/block.md) non-null object[​](#transactionblockblock-- "Direct link to transactionblockblock--") #### [`Transaction.contractActions`](#) ● [`[ContractAction!]!`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) non-null interface[​](#transactioncontractactionscontractaction-- "Direct link to transactioncontractactionscontractaction--") #### [`Transaction.unshieldedCreatedOutputs`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#transactionunshieldedcreatedoutputsunshieldedutxo-- "Direct link to transactionunshieldedcreatedoutputsunshieldedutxo--") #### [`Transaction.unshieldedSpentOutputs`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#transactionunshieldedspentoutputsunshieldedutxo-- "Direct link to transactionunshieldedspentoutputsunshieldedutxo--") #### [`Transaction.zswapLedgerEvents`](#) ● [`[ZswapLedgerEvent!]!`](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md) non-null object[​](#transactionzswapledgereventszswapledgerevent-- "Direct link to transactionzswapledgereventszswapledgerevent--") #### [`Transaction.dustLedgerEvents`](#) ● [`[DustLedgerEvent!]!`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) non-null interface[​](#transactiondustledgereventsdustledgerevent-- "Direct link to transactiondustledgereventsdustledgerevent--") ### Returned By[​](#returned-by "Direct link to Returned By") [`transactions`](/api-reference/midnight-indexer/operations/queries/transactions.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object ● [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface ● [`ContractCall`](/api-reference/midnight-indexer/types/objects/contract-call.md) object ● [`ContractDeploy`](/api-reference/midnight-indexer/types/objects/contract-deploy.md) object ● [`ContractUpdate`](/api-reference/midnight-indexer/types/objects/contract-update.md) object ● [`UnshieldedTransaction`](/api-reference/midnight-indexer/types/objects/unshielded-transaction.md) object ● [`UnshieldedUtxo`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) object ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object --- # Block > For the complete documentation index, see [llms.txt](/llms.txt) A block with its relevant data. ``` type Block { hash: HexEncoded! height: Int! protocolVersion: Int! timestamp: Int! author: HexEncoded ledgerParameters: HexEncoded! parent: Block transactions: [Transaction!]! systemParameters: SystemParameters! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`Block.hash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#blockhashhexencoded-- "Direct link to blockhashhexencoded--") The block hash. #### [`Block.height`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#blockheightint-- "Direct link to blockheightint--") The block height. #### [`Block.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#blockprotocolversionint-- "Direct link to blockprotocolversionint--") The protocol version. #### [`Block.timestamp`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#blocktimestampint-- "Direct link to blocktimestampint--") The UNIX timestamp. #### [`Block.author`](#) ● [`HexEncoded`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) scalar[​](#blockauthorhexencoded- "Direct link to blockauthorhexencoded-") The hex-encoded block author. #### [`Block.ledgerParameters`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#blockledgerparametershexencoded-- "Direct link to blockledgerparametershexencoded--") The hex-encoded ledger parameters for this block. #### [`Block.parent`](#) ● [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object[​](#blockparentblock- "Direct link to blockparentblock-") The parent of this block. #### [`Block.transactions`](#) ● [`[Transaction!]!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#blocktransactionstransaction-- "Direct link to blocktransactionstransaction--") The transactions within this block. #### [`Block.systemParameters`](#) ● [`SystemParameters!`](/api-reference/midnight-indexer/types/objects/system-parameters.md) non-null object[​](#blocksystemparameterssystemparameters-- "Direct link to blocksystemparameterssystemparameters--") The system parameters (governance) at this block height. ### Returned By[​](#returned-by "Direct link to Returned By") [`block`](/api-reference/midnight-indexer/operations/queries/block.md) query ● [`blocks`](/api-reference/midnight-indexer/operations/subscriptions/blocks.md) subscription ### Member Of[​](#member-of "Direct link to Member Of") [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object ● [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface --- # CollapsedMerkleTree > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` type CollapsedMerkleTree { startIndex: Int! endIndex: Int! update: HexEncoded! protocolVersion: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`CollapsedMerkleTree.startIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#collapsedmerkletreestartindexint-- "Direct link to collapsedmerkletreestartindexint--") The zswap state start index. #### [`CollapsedMerkleTree.endIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#collapsedmerkletreeendindexint-- "Direct link to collapsedmerkletreeendindexint--") The zswap state end index. #### [`CollapsedMerkleTree.update`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#collapsedmerkletreeupdatehexencoded-- "Direct link to collapsedmerkletreeupdatehexencoded--") The hex-encoded value. #### [`CollapsedMerkleTree.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#collapsedmerkletreeprotocolversionint-- "Direct link to collapsedmerkletreeprotocolversionint--") The protocol version. ### Member Of[​](#member-of "Direct link to Member Of") [`RelevantTransaction`](/api-reference/midnight-indexer/types/objects/relevant-transaction.md) object --- # CommitteeMember > For the complete documentation index, see [llms.txt](/llms.txt) Committee member for an epoch. ``` type CommitteeMember { epochNo: Int! position: Int! sidechainPubkeyHex: String! expectedSlots: Int! auraPubkeyHex: String poolIdHex: String spoSkHex: String } ``` ### Fields[​](#fields "Direct link to Fields") #### [`CommitteeMember.epochNo`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#committeememberepochnoint-- "Direct link to committeememberepochnoint--") #### [`CommitteeMember.position`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#committeememberpositionint-- "Direct link to committeememberpositionint--") #### [`CommitteeMember.sidechainPubkeyHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#committeemembersidechainpubkeyhexstring-- "Direct link to committeemembersidechainpubkeyhexstring--") #### [`CommitteeMember.expectedSlots`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#committeememberexpectedslotsint-- "Direct link to committeememberexpectedslotsint--") #### [`CommitteeMember.auraPubkeyHex`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#committeememberaurapubkeyhexstring- "Direct link to committeememberaurapubkeyhexstring-") #### [`CommitteeMember.poolIdHex`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#committeememberpoolidhexstring- "Direct link to committeememberpoolidhexstring-") #### [`CommitteeMember.spoSkHex`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#committeemembersposkhexstring- "Direct link to committeemembersposkhexstring-") ### Returned By[​](#returned-by "Direct link to Returned By") [`committee`](/api-reference/midnight-indexer/operations/queries/committee.md) query --- # ContractBalance > For the complete documentation index, see [llms.txt](/llms.txt) Represents a token balance held by a contract. This type is exposed through the GraphQL API to allow clients to query unshielded token balances for any contract action (Deploy, Call, Update). ``` type ContractBalance { tokenType: HexEncoded! amount: String! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ContractBalance.tokenType`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractbalancetokentypehexencoded-- "Direct link to contractbalancetokentypehexencoded--") Hex-encoded token type identifier. #### [`ContractBalance.amount`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#contractbalanceamountstring-- "Direct link to contractbalanceamountstring--") Balance amount as string to support larger integer values (up to 16 bytes). ### Member Of[​](#member-of "Direct link to Member Of") [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface ● [`ContractCall`](/api-reference/midnight-indexer/types/objects/contract-call.md) object ● [`ContractDeploy`](/api-reference/midnight-indexer/types/objects/contract-deploy.md) object ● [`ContractUpdate`](/api-reference/midnight-indexer/types/objects/contract-update.md) object --- # ContractCall > For the complete documentation index, see [llms.txt](/llms.txt) A contract call. ``` type ContractCall implements ContractAction { address: HexEncoded! state: HexEncoded! zswapState: HexEncoded! entryPoint: String! transaction: Transaction! deploy: ContractDeploy! unshieldedBalances: [ContractBalance!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ContractCall.address`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractcalladdresshexencoded-- "Direct link to contractcalladdresshexencoded--") The hex-encoded serialized address. #### [`ContractCall.state`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractcallstatehexencoded-- "Direct link to contractcallstatehexencoded--") The hex-encoded serialized state. #### [`ContractCall.zswapState`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractcallzswapstatehexencoded-- "Direct link to contractcallzswapstatehexencoded--") The hex-encoded serialized contract-specific zswap state. #### [`ContractCall.entryPoint`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#contractcallentrypointstring-- "Direct link to contractcallentrypointstring--") The entry point. #### [`ContractCall.transaction`](#) ● [`Transaction!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#contractcalltransactiontransaction-- "Direct link to contractcalltransactiontransaction--") Transaction for this contract call. #### [`ContractCall.deploy`](#) ● [`ContractDeploy!`](/api-reference/midnight-indexer/types/objects/contract-deploy.md) non-null object[​](#contractcalldeploycontractdeploy-- "Direct link to contractcalldeploycontractdeploy--") Contract deploy for this contract call. #### [`ContractCall.unshieldedBalances`](#) ● [`[ContractBalance!]!`](/api-reference/midnight-indexer/types/objects/contract-balance.md) non-null object[​](#contractcallunshieldedbalancescontractbalance-- "Direct link to contractcallunshieldedbalancescontractbalance--") Unshielded token balances held by this contract. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface[​](#contractaction- "Direct link to contractaction-") A contract action. --- # ContractDeploy > For the complete documentation index, see [llms.txt](/llms.txt) A contract deployment. ``` type ContractDeploy implements ContractAction { address: HexEncoded! state: HexEncoded! zswapState: HexEncoded! transaction: Transaction! unshieldedBalances: [ContractBalance!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ContractDeploy.address`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractdeployaddresshexencoded-- "Direct link to contractdeployaddresshexencoded--") The hex-encoded serialized address. #### [`ContractDeploy.state`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractdeploystatehexencoded-- "Direct link to contractdeploystatehexencoded--") The hex-encoded serialized state. #### [`ContractDeploy.zswapState`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractdeployzswapstatehexencoded-- "Direct link to contractdeployzswapstatehexencoded--") The hex-encoded serialized contract-specific zswap state. #### [`ContractDeploy.transaction`](#) ● [`Transaction!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#contractdeploytransactiontransaction-- "Direct link to contractdeploytransactiontransaction--") Transaction for this contract deploy. #### [`ContractDeploy.unshieldedBalances`](#) ● [`[ContractBalance!]!`](/api-reference/midnight-indexer/types/objects/contract-balance.md) non-null object[​](#contractdeployunshieldedbalancescontractbalance-- "Direct link to contractdeployunshieldedbalancescontractbalance--") Unshielded token balances held by this contract. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface[​](#contractaction- "Direct link to contractaction-") A contract action. ### Member Of[​](#member-of "Direct link to Member Of") [`ContractCall`](/api-reference/midnight-indexer/types/objects/contract-call.md) object --- # ContractUpdate > For the complete documentation index, see [llms.txt](/llms.txt) A contract update. ``` type ContractUpdate implements ContractAction { address: HexEncoded! state: HexEncoded! zswapState: HexEncoded! transaction: Transaction! unshieldedBalances: [ContractBalance!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ContractUpdate.address`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractupdateaddresshexencoded-- "Direct link to contractupdateaddresshexencoded--") The hex-encoded serialized address. #### [`ContractUpdate.state`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractupdatestatehexencoded-- "Direct link to contractupdatestatehexencoded--") The hex-encoded serialized state. #### [`ContractUpdate.zswapState`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#contractupdatezswapstatehexencoded-- "Direct link to contractupdatezswapstatehexencoded--") The hex-encoded serialized contract-specific zswap state. #### [`ContractUpdate.transaction`](#) ● [`Transaction!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#contractupdatetransactiontransaction-- "Direct link to contractupdatetransactiontransaction--") Transaction for this contract update. #### [`ContractUpdate.unshieldedBalances`](#) ● [`[ContractBalance!]!`](/api-reference/midnight-indexer/types/objects/contract-balance.md) non-null object[​](#contractupdateunshieldedbalancescontractbalance-- "Direct link to contractupdateunshieldedbalancescontractbalance--") Unshielded token balances held by this contract after the update. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface[​](#contractaction- "Direct link to contractaction-") A contract action. --- # DParameter > For the complete documentation index, see [llms.txt](/llms.txt) The D-parameter controlling validator committee composition. ``` type DParameter { numPermissionedCandidates: Int! numRegisteredCandidates: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DParameter.numPermissionedCandidates`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dparameternumpermissionedcandidatesint-- "Direct link to dparameternumpermissionedcandidatesint--") Number of permissioned candidates. #### [`DParameter.numRegisteredCandidates`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dparameternumregisteredcandidatesint-- "Direct link to dparameternumregisteredcandidatesint--") Number of registered candidates. ### Member Of[​](#member-of "Direct link to Member Of") [`SystemParameters`](/api-reference/midnight-indexer/types/objects/system-parameters.md) object --- # DParameterChange > For the complete documentation index, see [llms.txt](/llms.txt) D-parameter change record for history queries. ``` type DParameterChange { blockHeight: Int! blockHash: HexEncoded! timestamp: Int! numPermissionedCandidates: Int! numRegisteredCandidates: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DParameterChange.blockHeight`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dparameterchangeblockheightint-- "Direct link to dparameterchangeblockheightint--") The block height where this parameter became effective. #### [`DParameterChange.blockHash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#dparameterchangeblockhashhexencoded-- "Direct link to dparameterchangeblockhashhexencoded--") The hex-encoded block hash where this parameter became effective. #### [`DParameterChange.timestamp`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dparameterchangetimestampint-- "Direct link to dparameterchangetimestampint--") The UNIX timestamp when this parameter became effective. #### [`DParameterChange.numPermissionedCandidates`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dparameterchangenumpermissionedcandidatesint-- "Direct link to dparameterchangenumpermissionedcandidatesint--") Number of permissioned candidates. #### [`DParameterChange.numRegisteredCandidates`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dparameterchangenumregisteredcandidatesint-- "Direct link to dparameterchangenumregisteredcandidatesint--") Number of registered candidates. ### Returned By[​](#returned-by "Direct link to Returned By") [`dParameterHistory`](/api-reference/midnight-indexer/operations/queries/d-parameter-history.md) query --- # DustGenerationDtimeUpdate > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` type DustGenerationDtimeUpdate implements DustLedgerEvent { id: Int! raw: HexEncoded! maxId: Int! protocolVersion: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DustGenerationDtimeUpdate.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustgenerationdtimeupdateidint-- "Direct link to dustgenerationdtimeupdateidint--") The ID of this dust ledger event. #### [`DustGenerationDtimeUpdate.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#dustgenerationdtimeupdaterawhexencoded-- "Direct link to dustgenerationdtimeupdaterawhexencoded--") The hex-encoded serialized event. #### [`DustGenerationDtimeUpdate.maxId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustgenerationdtimeupdatemaxidint-- "Direct link to dustgenerationdtimeupdatemaxidint--") The maximum ID of all dust ledger events. #### [`DustGenerationDtimeUpdate.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustgenerationdtimeupdateprotocolversionint-- "Direct link to dustgenerationdtimeupdateprotocolversionint--") The protocol version. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface[​](#dustledgerevent- "Direct link to dustledgerevent-") A dust related ledger event. --- # DustGenerationStatus > For the complete documentation index, see [llms.txt](/llms.txt) DUST generation status for a specific Cardano reward address. ``` type DustGenerationStatus { cardanoRewardAddress: CardanoRewardAddress! dustAddress: DustAddress registered: Boolean! nightBalance: String! generationRate: String! maxCapacity: String! currentCapacity: String! utxoTxHash: HexEncoded utxoOutputIndex: Int } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DustGenerationStatus.cardanoRewardAddress`](#) ● [`CardanoRewardAddress!`](/api-reference/midnight-indexer/types/scalars/cardano-reward-address.md) non-null scalar[​](#dustgenerationstatuscardanorewardaddresscardanorewardaddress-- "Direct link to dustgenerationstatuscardanorewardaddresscardanorewardaddress--") The Bech32-encoded Cardano reward address (e.g., stake\_test1... or stake1...). #### [`DustGenerationStatus.dustAddress`](#) ● [`DustAddress`](/api-reference/midnight-indexer/types/scalars/dust-address.md) scalar[​](#dustgenerationstatusdustaddressdustaddress- "Direct link to dustgenerationstatusdustaddressdustaddress-") The Bech32m-encoded associated DUST address if registered. #### [`DustGenerationStatus.registered`](#) ● [`Boolean!`](/api-reference/midnight-indexer/types/scalars/boolean.md) non-null scalar[​](#dustgenerationstatusregisteredboolean-- "Direct link to dustgenerationstatusregisteredboolean--") Whether this reward address is registered. #### [`DustGenerationStatus.nightBalance`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#dustgenerationstatusnightbalancestring-- "Direct link to dustgenerationstatusnightbalancestring--") NIGHT balance backing generation in STAR. #### [`DustGenerationStatus.generationRate`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#dustgenerationstatusgenerationratestring-- "Direct link to dustgenerationstatusgenerationratestring--") DUST generation rate in SPECK per second. #### [`DustGenerationStatus.maxCapacity`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#dustgenerationstatusmaxcapacitystring-- "Direct link to dustgenerationstatusmaxcapacitystring--") Maximum DUST capacity in SPECK. #### [`DustGenerationStatus.currentCapacity`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#dustgenerationstatuscurrentcapacitystring-- "Direct link to dustgenerationstatuscurrentcapacitystring--") Current generated DUST capacity in SPECK. #### [`DustGenerationStatus.utxoTxHash`](#) ● [`HexEncoded`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) scalar[​](#dustgenerationstatusutxotxhashhexencoded- "Direct link to dustgenerationstatusutxotxhashhexencoded-") Cardano UTXO transaction hash for update/unregister operations. #### [`DustGenerationStatus.utxoOutputIndex`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#dustgenerationstatusutxooutputindexint- "Direct link to dustgenerationstatusutxooutputindexint-") Cardano UTXO output index for update/unregister operations. ### Returned By[​](#returned-by "Direct link to Returned By") [`dustGenerationStatus`](/api-reference/midnight-indexer/operations/queries/dust-generation-status.md) query --- # DustInitialUtxo > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` type DustInitialUtxo implements DustLedgerEvent { id: Int! raw: HexEncoded! maxId: Int! protocolVersion: Int! output: DustOutput! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DustInitialUtxo.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustinitialutxoidint-- "Direct link to dustinitialutxoidint--") The ID of this dust ledger event. #### [`DustInitialUtxo.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#dustinitialutxorawhexencoded-- "Direct link to dustinitialutxorawhexencoded--") The hex-encoded serialized event. #### [`DustInitialUtxo.maxId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustinitialutxomaxidint-- "Direct link to dustinitialutxomaxidint--") The maximum ID of all dust ledger events. #### [`DustInitialUtxo.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustinitialutxoprotocolversionint-- "Direct link to dustinitialutxoprotocolversionint--") The protocol version. #### [`DustInitialUtxo.output`](#) ● [`DustOutput!`](/api-reference/midnight-indexer/types/objects/dust-output.md) non-null object[​](#dustinitialutxooutputdustoutput-- "Direct link to dustinitialutxooutputdustoutput--") The dust output. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface[​](#dustledgerevent- "Direct link to dustledgerevent-") A dust related ledger event. --- # DustOutput > For the complete documentation index, see [llms.txt](/llms.txt) A dust output. ``` type DustOutput { nonce: HexEncoded! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DustOutput.nonce`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#dustoutputnoncehexencoded-- "Direct link to dustoutputnoncehexencoded--") The hex-encoded 32-byte nonce. ### Member Of[​](#member-of "Direct link to Member Of") [`DustInitialUtxo`](/api-reference/midnight-indexer/types/objects/dust-initial-utxo.md) object --- # DustSpendProcessed > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` type DustSpendProcessed implements DustLedgerEvent { id: Int! raw: HexEncoded! maxId: Int! protocolVersion: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`DustSpendProcessed.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustspendprocessedidint-- "Direct link to dustspendprocessedidint--") The ID of this dust ledger event. #### [`DustSpendProcessed.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#dustspendprocessedrawhexencoded-- "Direct link to dustspendprocessedrawhexencoded--") The hex-encoded serialized event. #### [`DustSpendProcessed.maxId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustspendprocessedmaxidint-- "Direct link to dustspendprocessedmaxidint--") The maximum ID of all dust ledger events. #### [`DustSpendProcessed.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#dustspendprocessedprotocolversionint-- "Direct link to dustspendprocessedprotocolversionint--") The protocol version. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface[​](#dustledgerevent- "Direct link to dustledgerevent-") A dust related ledger event. --- # EpochInfo > For the complete documentation index, see [llms.txt](/llms.txt) Current epoch information. ``` type EpochInfo { epochNo: Int! durationSeconds: Int! elapsedSeconds: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`EpochInfo.epochNo`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochinfoepochnoint-- "Direct link to epochinfoepochnoint--") #### [`EpochInfo.durationSeconds`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochinfodurationsecondsint-- "Direct link to epochinfodurationsecondsint--") #### [`EpochInfo.elapsedSeconds`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochinfoelapsedsecondsint-- "Direct link to epochinfoelapsedsecondsint--") ### Returned By[​](#returned-by "Direct link to Returned By") [`currentEpochInfo`](/api-reference/midnight-indexer/operations/queries/current-epoch-info.md) query --- # EpochPerf > For the complete documentation index, see [llms.txt](/llms.txt) SPO performance for an epoch. ``` type EpochPerf { epochNo: Int! spoSkHex: String! produced: Int! expected: Int! identityLabel: String stakeSnapshot: String poolIdHex: String validatorClass: String } ``` ### Fields[​](#fields "Direct link to Fields") #### [`EpochPerf.epochNo`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochperfepochnoint-- "Direct link to epochperfepochnoint--") #### [`EpochPerf.spoSkHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#epochperfsposkhexstring-- "Direct link to epochperfsposkhexstring--") #### [`EpochPerf.produced`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochperfproducedint-- "Direct link to epochperfproducedint--") #### [`EpochPerf.expected`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#epochperfexpectedint-- "Direct link to epochperfexpectedint--") #### [`EpochPerf.identityLabel`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#epochperfidentitylabelstring- "Direct link to epochperfidentitylabelstring-") #### [`EpochPerf.stakeSnapshot`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#epochperfstakesnapshotstring- "Direct link to epochperfstakesnapshotstring-") #### [`EpochPerf.poolIdHex`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#epochperfpoolidhexstring- "Direct link to epochperfpoolidhexstring-") #### [`EpochPerf.validatorClass`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#epochperfvalidatorclassstring- "Direct link to epochperfvalidatorclassstring-") ### Returned By[​](#returned-by "Direct link to Returned By") [`epochPerformance`](/api-reference/midnight-indexer/operations/queries/epoch-performance.md) query ● [`spoPerformanceBySpoSk`](/api-reference/midnight-indexer/operations/queries/spo-performance-by-spo-sk.md) query ● [`spoPerformanceLatest`](/api-reference/midnight-indexer/operations/queries/spo-performance-latest.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`SpoComposite`](/api-reference/midnight-indexer/types/objects/spo-composite.md) object --- # FirstValidEpoch > For the complete documentation index, see [llms.txt](/llms.txt) First valid epoch for an SPO identity. ``` type FirstValidEpoch { idKey: String! firstValidEpoch: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`FirstValidEpoch.idKey`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#firstvalidepochidkeystring-- "Direct link to firstvalidepochidkeystring--") #### [`FirstValidEpoch.firstValidEpoch`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#firstvalidepochfirstvalidepochint-- "Direct link to firstvalidepochfirstvalidepochint--") ### Returned By[​](#returned-by "Direct link to Returned By") [`registeredFirstValidEpochs`](/api-reference/midnight-indexer/operations/queries/registered-first-valid-epochs.md) query --- # ParamChange > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` type ParamChange implements DustLedgerEvent { id: Int! raw: HexEncoded! maxId: Int! protocolVersion: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ParamChange.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#paramchangeidint-- "Direct link to paramchangeidint--") The ID of this dust ledger event. #### [`ParamChange.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#paramchangerawhexencoded-- "Direct link to paramchangerawhexencoded--") The hex-encoded serialized event. #### [`ParamChange.maxId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#paramchangemaxidint-- "Direct link to paramchangemaxidint--") The maximum ID of all dust ledger events. #### [`ParamChange.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#paramchangeprotocolversionint-- "Direct link to paramchangeprotocolversionint--") The protocol version. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface[​](#dustledgerevent- "Direct link to dustledgerevent-") A dust related ledger event. --- # PoolMetadata > For the complete documentation index, see [llms.txt](/llms.txt) Pool metadata from Cardano. ``` type PoolMetadata { poolIdHex: String! hexId: String name: String ticker: String homepageUrl: String logoUrl: String } ``` ### Fields[​](#fields "Direct link to Fields") #### [`PoolMetadata.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#poolmetadatapoolidhexstring-- "Direct link to poolmetadatapoolidhexstring--") #### [`PoolMetadata.hexId`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#poolmetadatahexidstring- "Direct link to poolmetadatahexidstring-") #### [`PoolMetadata.name`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#poolmetadatanamestring- "Direct link to poolmetadatanamestring-") #### [`PoolMetadata.ticker`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#poolmetadatatickerstring- "Direct link to poolmetadatatickerstring-") #### [`PoolMetadata.homepageUrl`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#poolmetadatahomepageurlstring- "Direct link to poolmetadatahomepageurlstring-") #### [`PoolMetadata.logoUrl`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#poolmetadatalogourlstring- "Direct link to poolmetadatalogourlstring-") ### Returned By[​](#returned-by "Direct link to Returned By") [`poolMetadata`](/api-reference/midnight-indexer/operations/queries/pool-metadata.md) query ● [`poolMetadataList`](/api-reference/midnight-indexer/operations/queries/pool-metadata-list.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`SpoComposite`](/api-reference/midnight-indexer/types/objects/spo-composite.md) object --- # PresenceEvent > For the complete documentation index, see [llms.txt](/llms.txt) Presence event for an SPO in an epoch. ``` type PresenceEvent { epochNo: Int! idKey: String! source: String! status: String } ``` ### Fields[​](#fields "Direct link to Fields") #### [`PresenceEvent.epochNo`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#presenceeventepochnoint-- "Direct link to presenceeventepochnoint--") #### [`PresenceEvent.idKey`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#presenceeventidkeystring-- "Direct link to presenceeventidkeystring--") #### [`PresenceEvent.source`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#presenceeventsourcestring-- "Direct link to presenceeventsourcestring--") #### [`PresenceEvent.status`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#presenceeventstatusstring- "Direct link to presenceeventstatusstring-") ### Returned By[​](#returned-by "Direct link to Returned By") [`registeredPresence`](/api-reference/midnight-indexer/operations/queries/registered-presence.md) query --- # RegisteredStat > For the complete documentation index, see [llms.txt](/llms.txt) Registration statistics for an epoch. ``` type RegisteredStat { epochNo: Int! federatedValidCount: Int! federatedInvalidCount: Int! registeredValidCount: Int! registeredInvalidCount: Int! dparam: Float } ``` ### Fields[​](#fields "Direct link to Fields") #### [`RegisteredStat.epochNo`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredstatepochnoint-- "Direct link to registeredstatepochnoint--") #### [`RegisteredStat.federatedValidCount`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredstatfederatedvalidcountint-- "Direct link to registeredstatfederatedvalidcountint--") #### [`RegisteredStat.federatedInvalidCount`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredstatfederatedinvalidcountint-- "Direct link to registeredstatfederatedinvalidcountint--") #### [`RegisteredStat.registeredValidCount`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredstatregisteredvalidcountint-- "Direct link to registeredstatregisteredvalidcountint--") #### [`RegisteredStat.registeredInvalidCount`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredstatregisteredinvalidcountint-- "Direct link to registeredstatregisteredinvalidcountint--") #### [`RegisteredStat.dparam`](#) ● [`Float`](/api-reference/midnight-indexer/types/scalars/float.md) scalar[​](#registeredstatdparamfloat- "Direct link to registeredstatdparamfloat-") ### Returned By[​](#returned-by "Direct link to Returned By") [`registeredSpoSeries`](/api-reference/midnight-indexer/operations/queries/registered-spo-series.md) query --- # RegisteredTotals > For the complete documentation index, see [llms.txt](/llms.txt) Cumulative registration totals for an epoch. ``` type RegisteredTotals { epochNo: Int! totalRegistered: Int! newlyRegistered: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`RegisteredTotals.epochNo`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredtotalsepochnoint-- "Direct link to registeredtotalsepochnoint--") #### [`RegisteredTotals.totalRegistered`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredtotalstotalregisteredint-- "Direct link to registeredtotalstotalregisteredint--") #### [`RegisteredTotals.newlyRegistered`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#registeredtotalsnewlyregisteredint-- "Direct link to registeredtotalsnewlyregisteredint--") ### Returned By[​](#returned-by "Direct link to Returned By") [`registeredTotalsSeries`](/api-reference/midnight-indexer/operations/queries/registered-totals-series.md) query --- # RegularTransaction > For the complete documentation index, see [llms.txt](/llms.txt) A regular Midnight transaction. ``` type RegularTransaction implements Transaction { id: Int! hash: HexEncoded! protocolVersion: Int! raw: HexEncoded! transactionResult: TransactionResult! identifiers: [HexEncoded!]! merkleTreeRoot: HexEncoded! startIndex: Int! endIndex: Int! fees: TransactionFees! block: Block! contractActions: [ContractAction!]! unshieldedCreatedOutputs: [UnshieldedUtxo!]! unshieldedSpentOutputs: [UnshieldedUtxo!]! zswapLedgerEvents: [ZswapLedgerEvent!]! dustLedgerEvents: [DustLedgerEvent!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`RegularTransaction.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#regulartransactionidint-- "Direct link to regulartransactionidint--") The transaction ID. #### [`RegularTransaction.hash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#regulartransactionhashhexencoded-- "Direct link to regulartransactionhashhexencoded--") The hex-encoded transaction hash. #### [`RegularTransaction.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#regulartransactionprotocolversionint-- "Direct link to regulartransactionprotocolversionint--") The protocol version. #### [`RegularTransaction.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#regulartransactionrawhexencoded-- "Direct link to regulartransactionrawhexencoded--") The hex-encoded serialized transaction content. #### [`RegularTransaction.transactionResult`](#) ● [`TransactionResult!`](/api-reference/midnight-indexer/types/objects/transaction-result.md) non-null object[​](#regulartransactiontransactionresulttransactionresult-- "Direct link to regulartransactiontransactionresulttransactionresult--") The result of applying this transaction to the ledger state. #### [`RegularTransaction.identifiers`](#) ● [`[HexEncoded!]!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#regulartransactionidentifiershexencoded-- "Direct link to regulartransactionidentifiershexencoded--") The hex-encoded serialized transaction identifiers. #### [`RegularTransaction.merkleTreeRoot`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#regulartransactionmerkletreeroothexencoded-- "Direct link to regulartransactionmerkletreeroothexencoded--") The hex-encoded serialized merkle-tree root. #### [`RegularTransaction.startIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#regulartransactionstartindexint-- "Direct link to regulartransactionstartindexint--") The zswap state start index. #### [`RegularTransaction.endIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#regulartransactionendindexint-- "Direct link to regulartransactionendindexint--") The zswap state end index. #### [`RegularTransaction.fees`](#) ● [`TransactionFees!`](/api-reference/midnight-indexer/types/objects/transaction-fees.md) non-null object[​](#regulartransactionfeestransactionfees-- "Direct link to regulartransactionfeestransactionfees--") Fee information for this transaction. #### [`RegularTransaction.block`](#) ● [`Block!`](/api-reference/midnight-indexer/types/objects/block.md) non-null object[​](#regulartransactionblockblock-- "Direct link to regulartransactionblockblock--") The block for this transaction. #### [`RegularTransaction.contractActions`](#) ● [`[ContractAction!]!`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) non-null interface[​](#regulartransactioncontractactionscontractaction-- "Direct link to regulartransactioncontractactionscontractaction--") The contract actions for this transaction. #### [`RegularTransaction.unshieldedCreatedOutputs`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#regulartransactionunshieldedcreatedoutputsunshieldedutxo-- "Direct link to regulartransactionunshieldedcreatedoutputsunshieldedutxo--") Unshielded UTXOs created by this transaction. #### [`RegularTransaction.unshieldedSpentOutputs`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#regulartransactionunshieldedspentoutputsunshieldedutxo-- "Direct link to regulartransactionunshieldedspentoutputsunshieldedutxo--") Unshielded UTXOs spent (consumed) by this transaction. #### [`RegularTransaction.zswapLedgerEvents`](#) ● [`[ZswapLedgerEvent!]!`](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md) non-null object[​](#regulartransactionzswapledgereventszswapledgerevent-- "Direct link to regulartransactionzswapledgereventszswapledgerevent--") Zswap ledger events of this transaction. #### [`RegularTransaction.dustLedgerEvents`](#) ● [`[DustLedgerEvent!]!`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) non-null interface[​](#regulartransactiondustledgereventsdustledgerevent-- "Direct link to regulartransactiondustledgereventsdustledgerevent--") Dust ledger events of this transaction. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface[​](#transaction- "Direct link to transaction-") A Midnight transaction. ### Member Of[​](#member-of "Direct link to Member Of") [`RelevantTransaction`](/api-reference/midnight-indexer/types/objects/relevant-transaction.md) object --- # RelevantTransaction > For the complete documentation index, see [llms.txt](/llms.txt) A transaction relevant for the subscribing wallet and an optional collapsed merkle tree. ``` type RelevantTransaction { transaction: RegularTransaction! collapsedMerkleTree: CollapsedMerkleTree } ``` ### Fields[​](#fields "Direct link to Fields") #### [`RelevantTransaction.transaction`](#) ● [`RegularTransaction!`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) non-null object[​](#relevanttransactiontransactionregulartransaction-- "Direct link to relevanttransactiontransactionregulartransaction--") A transaction relevant for the subscribing wallet. #### [`RelevantTransaction.collapsedMerkleTree`](#) ● [`CollapsedMerkleTree`](/api-reference/midnight-indexer/types/objects/collapsed-merkle-tree.md) object[​](#relevanttransactioncollapsedmerkletreecollapsedmerkletree- "Direct link to relevanttransactioncollapsedmerkletreecollapsedmerkletree-") An optional collapsed merkle tree. ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`ShieldedTransactionsEvent`](/api-reference/midnight-indexer/types/unions/shielded-transactions-event.md) union --- # Segment > For the complete documentation index, see [llms.txt](/llms.txt) One of many segments for a partially successful transaction result showing success for some segment. ``` type Segment { id: Int! success: Boolean! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`Segment.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#segmentidint-- "Direct link to segmentidint--") Segment ID. #### [`Segment.success`](#) ● [`Boolean!`](/api-reference/midnight-indexer/types/scalars/boolean.md) non-null scalar[​](#segmentsuccessboolean-- "Direct link to segmentsuccessboolean--") Successful or not. ### Member Of[​](#member-of "Direct link to Member Of") [`TransactionResult`](/api-reference/midnight-indexer/types/objects/transaction-result.md) object --- # ShieldedTransactionsProgress > For the complete documentation index, see [llms.txt](/llms.txt) Information about the shielded transactions indexing progress. ``` type ShieldedTransactionsProgress { highestEndIndex: Int! highestCheckedEndIndex: Int! highestRelevantEndIndex: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ShieldedTransactionsProgress.highestEndIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#shieldedtransactionsprogresshighestendindexint-- "Direct link to shieldedtransactionsprogresshighestendindexint--") The highest zswap state end index (see `endIndex` of `Transaction`) of all transactions. It represents the known state of the blockchain. A value of zero (completely unlikely) means that no shielded transactions have been indexed yet. #### [`ShieldedTransactionsProgress.highestCheckedEndIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#shieldedtransactionsprogresshighestcheckedendindexint-- "Direct link to shieldedtransactionsprogresshighestcheckedendindexint--") The highest zswap state end index (see `endIndex` of `Transaction`) of all transactions checked for relevance. Initially less than and eventually (when some wallet has been fully indexed) equal to `highest_end_index`. A value of zero (very unlikely) means that no wallet has subscribed before and indexing for the subscribing wallet has not yet started. #### [`ShieldedTransactionsProgress.highestRelevantEndIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#shieldedtransactionsprogresshighestrelevantendindexint-- "Direct link to shieldedtransactionsprogresshighestrelevantendindexint--") The highest zswap state end index (see `endIndex` of `Transaction`) of all relevant transactions for the subscribing wallet. Usually less than `highest_checked_end_index` unless the latest checked transaction is relevant for the subscribing wallet. A value of zero means that no relevant transactions have been indexed for the subscribing wallet. ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`ShieldedTransactionsEvent`](/api-reference/midnight-indexer/types/unions/shielded-transactions-event.md) union --- # Spo > For the complete documentation index, see [llms.txt](/llms.txt) SPO with optional metadata. ``` type Spo { poolIdHex: String! validatorClass: String! sidechainPubkeyHex: String! auraPubkeyHex: String name: String ticker: String homepageUrl: String logoUrl: String } ``` ### Fields[​](#fields "Direct link to Fields") #### [`Spo.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spopoolidhexstring-- "Direct link to spopoolidhexstring--") #### [`Spo.validatorClass`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spovalidatorclassstring-- "Direct link to spovalidatorclassstring--") #### [`Spo.sidechainPubkeyHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#sposidechainpubkeyhexstring-- "Direct link to sposidechainpubkeyhexstring--") #### [`Spo.auraPubkeyHex`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#spoaurapubkeyhexstring- "Direct link to spoaurapubkeyhexstring-") #### [`Spo.name`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#sponamestring- "Direct link to sponamestring-") #### [`Spo.ticker`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#spotickerstring- "Direct link to spotickerstring-") #### [`Spo.homepageUrl`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#spohomepageurlstring- "Direct link to spohomepageurlstring-") #### [`Spo.logoUrl`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#spologourlstring- "Direct link to spologourlstring-") ### Returned By[​](#returned-by "Direct link to Returned By") [`spoByPoolId`](/api-reference/midnight-indexer/operations/queries/spo-by-pool-id.md) query ● [`spoList`](/api-reference/midnight-indexer/operations/queries/spo-list.md) query --- # SpoComposite > For the complete documentation index, see [llms.txt](/llms.txt) Composite SPO data (identity + metadata + performance). ``` type SpoComposite { identity: SpoIdentity metadata: PoolMetadata performance: [EpochPerf!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`SpoComposite.identity`](#) ● [`SpoIdentity`](/api-reference/midnight-indexer/types/objects/spo-identity.md) object[​](#spocompositeidentityspoidentity- "Direct link to spocompositeidentityspoidentity-") #### [`SpoComposite.metadata`](#) ● [`PoolMetadata`](/api-reference/midnight-indexer/types/objects/pool-metadata.md) object[​](#spocompositemetadatapoolmetadata- "Direct link to spocompositemetadatapoolmetadata-") #### [`SpoComposite.performance`](#) ● [`[EpochPerf!]!`](/api-reference/midnight-indexer/types/objects/epoch-perf.md) non-null object[​](#spocompositeperformanceepochperf-- "Direct link to spocompositeperformanceepochperf--") ### Returned By[​](#returned-by "Direct link to Returned By") [`spoCompositeByPoolId`](/api-reference/midnight-indexer/operations/queries/spo-composite-by-pool-id.md) query --- # SpoIdentity > For the complete documentation index, see [llms.txt](/llms.txt) SPO identity information. ``` type SpoIdentity { poolIdHex: String! mainchainPubkeyHex: String! sidechainPubkeyHex: String! auraPubkeyHex: String validatorClass: String! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`SpoIdentity.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spoidentitypoolidhexstring-- "Direct link to spoidentitypoolidhexstring--") #### [`SpoIdentity.mainchainPubkeyHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spoidentitymainchainpubkeyhexstring-- "Direct link to spoidentitymainchainpubkeyhexstring--") #### [`SpoIdentity.sidechainPubkeyHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spoidentitysidechainpubkeyhexstring-- "Direct link to spoidentitysidechainpubkeyhexstring--") #### [`SpoIdentity.auraPubkeyHex`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#spoidentityaurapubkeyhexstring- "Direct link to spoidentityaurapubkeyhexstring-") #### [`SpoIdentity.validatorClass`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#spoidentityvalidatorclassstring-- "Direct link to spoidentityvalidatorclassstring--") ### Returned By[​](#returned-by "Direct link to Returned By") [`spoIdentities`](/api-reference/midnight-indexer/operations/queries/spo-identities.md) query ● [`spoIdentityByPoolId`](/api-reference/midnight-indexer/operations/queries/spo-identity-by-pool-id.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`SpoComposite`](/api-reference/midnight-indexer/types/objects/spo-composite.md) object --- # StakeShare > For the complete documentation index, see [llms.txt](/llms.txt) Stake share information for an SPO. Values are sourced from mainchain pool data (e.g., Blockfrost) and keyed by Cardano pool\_id. ``` type StakeShare { poolIdHex: String! name: String ticker: String homepageUrl: String logoUrl: String liveStake: String activeStake: String liveDelegators: Int liveSaturation: Float declaredPledge: String livePledge: String stakeShare: Float } ``` ### Fields[​](#fields "Direct link to Fields") #### [`StakeShare.poolIdHex`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#stakesharepoolidhexstring-- "Direct link to stakesharepoolidhexstring--") Cardano pool ID (56-character hex string). #### [`StakeShare.name`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharenamestring- "Direct link to stakesharenamestring-") Pool name from metadata. #### [`StakeShare.ticker`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharetickerstring- "Direct link to stakesharetickerstring-") Pool ticker from metadata. #### [`StakeShare.homepageUrl`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharehomepageurlstring- "Direct link to stakesharehomepageurlstring-") Pool homepage URL from metadata. #### [`StakeShare.logoUrl`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharelogourlstring- "Direct link to stakesharelogourlstring-") Pool logo URL from metadata. #### [`StakeShare.liveStake`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharelivestakestring- "Direct link to stakesharelivestakestring-") Current live stake in lovelace. #### [`StakeShare.activeStake`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakeshareactivestakestring- "Direct link to stakeshareactivestakestring-") Current active stake in lovelace. #### [`StakeShare.liveDelegators`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#stakesharelivedelegatorsint- "Direct link to stakesharelivedelegatorsint-") Number of live delegators. #### [`StakeShare.liveSaturation`](#) ● [`Float`](/api-reference/midnight-indexer/types/scalars/float.md) scalar[​](#stakesharelivesaturationfloat- "Direct link to stakesharelivesaturationfloat-") Saturation ratio (0.0 to 1.0+). #### [`StakeShare.declaredPledge`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharedeclaredpledgestring- "Direct link to stakesharedeclaredpledgestring-") Declared pledge in lovelace. #### [`StakeShare.livePledge`](#) ● [`String`](/api-reference/midnight-indexer/types/scalars/string.md) scalar[​](#stakesharelivepledgestring- "Direct link to stakesharelivepledgestring-") Current live pledge in lovelace. #### [`StakeShare.stakeShare`](#) ● [`Float`](/api-reference/midnight-indexer/types/scalars/float.md) scalar[​](#stakesharestakesharefloat- "Direct link to stakesharestakesharefloat-") Stake share as a fraction of total stake. ### Returned By[​](#returned-by "Direct link to Returned By") [`stakeDistribution`](/api-reference/midnight-indexer/operations/queries/stake-distribution.md) query --- # SystemParameters > For the complete documentation index, see [llms.txt](/llms.txt) System parameters at a specific block height. ``` type SystemParameters { dParameter: DParameter! termsAndConditions: TermsAndConditions } ``` ### Fields[​](#fields "Direct link to Fields") #### [`SystemParameters.dParameter`](#) ● [`DParameter!`](/api-reference/midnight-indexer/types/objects/dparameter.md) non-null object[​](#systemparametersdparameterdparameter-- "Direct link to systemparametersdparameterdparameter--") The D-parameter controlling validator committee composition. #### [`SystemParameters.termsAndConditions`](#) ● [`TermsAndConditions`](/api-reference/midnight-indexer/types/objects/terms-and-conditions.md) object[​](#systemparameterstermsandconditionstermsandconditions- "Direct link to systemparameterstermsandconditionstermsandconditions-") The current Terms and Conditions, if any have been set. ### Member Of[​](#member-of "Direct link to Member Of") [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object --- # SystemTransaction > For the complete documentation index, see [llms.txt](/llms.txt) A system Midnight transaction. ``` type SystemTransaction implements Transaction { id: Int! hash: HexEncoded! protocolVersion: Int! raw: HexEncoded! block: Block! contractActions: [ContractAction!]! unshieldedCreatedOutputs: [UnshieldedUtxo!]! unshieldedSpentOutputs: [UnshieldedUtxo!]! zswapLedgerEvents: [ZswapLedgerEvent!]! dustLedgerEvents: [DustLedgerEvent!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`SystemTransaction.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#systemtransactionidint-- "Direct link to systemtransactionidint--") The transaction ID. #### [`SystemTransaction.hash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#systemtransactionhashhexencoded-- "Direct link to systemtransactionhashhexencoded--") The hex-encoded transaction hash. #### [`SystemTransaction.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#systemtransactionprotocolversionint-- "Direct link to systemtransactionprotocolversionint--") The protocol version. #### [`SystemTransaction.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#systemtransactionrawhexencoded-- "Direct link to systemtransactionrawhexencoded--") The hex-encoded serialized transaction content. #### [`SystemTransaction.block`](#) ● [`Block!`](/api-reference/midnight-indexer/types/objects/block.md) non-null object[​](#systemtransactionblockblock-- "Direct link to systemtransactionblockblock--") The block for this transaction. #### [`SystemTransaction.contractActions`](#) ● [`[ContractAction!]!`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) non-null interface[​](#systemtransactioncontractactionscontractaction-- "Direct link to systemtransactioncontractactionscontractaction--") The contract actions for this transaction. #### [`SystemTransaction.unshieldedCreatedOutputs`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#systemtransactionunshieldedcreatedoutputsunshieldedutxo-- "Direct link to systemtransactionunshieldedcreatedoutputsunshieldedutxo--") Unshielded UTXOs created by this transaction. #### [`SystemTransaction.unshieldedSpentOutputs`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#systemtransactionunshieldedspentoutputsunshieldedutxo-- "Direct link to systemtransactionunshieldedspentoutputsunshieldedutxo--") Unshielded UTXOs spent (consumed) by this transaction. #### [`SystemTransaction.zswapLedgerEvents`](#) ● [`[ZswapLedgerEvent!]!`](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md) non-null object[​](#systemtransactionzswapledgereventszswapledgerevent-- "Direct link to systemtransactionzswapledgereventszswapledgerevent--") Zswap ledger events of this transaction. #### [`SystemTransaction.dustLedgerEvents`](#) ● [`[DustLedgerEvent!]!`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) non-null interface[​](#systemtransactiondustledgereventsdustledgerevent-- "Direct link to systemtransactiondustledgereventsdustledgerevent--") Dust ledger events of this transaction. ### Interfaces[​](#interfaces "Direct link to Interfaces") #### [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface[​](#transaction- "Direct link to transaction-") A Midnight transaction. --- # TermsAndConditions > For the complete documentation index, see [llms.txt](/llms.txt) Terms and Conditions agreement. ``` type TermsAndConditions { hash: HexEncoded! url: String! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`TermsAndConditions.hash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#termsandconditionshashhexencoded-- "Direct link to termsandconditionshashhexencoded--") The hex-encoded hash of the Terms and Conditions document. #### [`TermsAndConditions.url`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#termsandconditionsurlstring-- "Direct link to termsandconditionsurlstring--") The URL where the Terms and Conditions can be found. ### Member Of[​](#member-of "Direct link to Member Of") [`SystemParameters`](/api-reference/midnight-indexer/types/objects/system-parameters.md) object --- # TermsAndConditionsChange > For the complete documentation index, see [llms.txt](/llms.txt) Terms and Conditions change record for history queries. ``` type TermsAndConditionsChange { blockHeight: Int! blockHash: HexEncoded! timestamp: Int! hash: HexEncoded! url: String! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`TermsAndConditionsChange.blockHeight`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#termsandconditionschangeblockheightint-- "Direct link to termsandconditionschangeblockheightint--") The block height where this T\&C version became effective. #### [`TermsAndConditionsChange.blockHash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#termsandconditionschangeblockhashhexencoded-- "Direct link to termsandconditionschangeblockhashhexencoded--") The hex-encoded block hash where this T\&C version became effective. #### [`TermsAndConditionsChange.timestamp`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#termsandconditionschangetimestampint-- "Direct link to termsandconditionschangetimestampint--") The UNIX timestamp when this T\&C version became effective. #### [`TermsAndConditionsChange.hash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#termsandconditionschangehashhexencoded-- "Direct link to termsandconditionschangehashhexencoded--") The hex-encoded hash of the Terms and Conditions document. #### [`TermsAndConditionsChange.url`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#termsandconditionschangeurlstring-- "Direct link to termsandconditionschangeurlstring--") The URL where the Terms and Conditions can be found. ### Returned By[​](#returned-by "Direct link to Returned By") [`termsAndConditionsHistory`](/api-reference/midnight-indexer/operations/queries/terms-and-conditions-history.md) query --- # TransactionFees > For the complete documentation index, see [llms.txt](/llms.txt) Fees information for a transaction, including both paid and estimated fees. ``` type TransactionFees { paidFees: String! estimatedFees: String! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`TransactionFees.paidFees`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#transactionfeespaidfeesstring-- "Direct link to transactionfeespaidfeesstring--") The actual fees paid for this transaction in DUST. #### [`TransactionFees.estimatedFees`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#transactionfeesestimatedfeesstring-- "Direct link to transactionfeesestimatedfeesstring--") The estimated fees that was calculated for this transaction in DUST. ### Member Of[​](#member-of "Direct link to Member Of") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object --- # TransactionResult > For the complete documentation index, see [llms.txt](/llms.txt) The result of applying a transaction to the ledger state. In case of a partial success (status), there will be segments. ``` type TransactionResult { status: TransactionResultStatus! segments: [Segment!] } ``` ### Fields[​](#fields "Direct link to Fields") #### [`TransactionResult.status`](#) ● [`TransactionResultStatus!`](/api-reference/midnight-indexer/types/enums/transaction-result-status.md) non-null enum[​](#transactionresultstatustransactionresultstatus-- "Direct link to transactionresultstatustransactionresultstatus--") #### [`TransactionResult.segments`](#) ● [`[Segment!]`](/api-reference/midnight-indexer/types/objects/segment.md) list object[​](#transactionresultsegmentssegment-- "Direct link to transactionresultsegmentssegment--") ### Member Of[​](#member-of "Direct link to Member Of") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object --- # UnshieldedTransaction > For the complete documentation index, see [llms.txt](/llms.txt) A transaction that created and/or spent UTXOs alongside these and other information. ``` type UnshieldedTransaction { transaction: Transaction! createdUtxos: [UnshieldedUtxo!]! spentUtxos: [UnshieldedUtxo!]! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`UnshieldedTransaction.transaction`](#) ● [`Transaction!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#unshieldedtransactiontransactiontransaction-- "Direct link to unshieldedtransactiontransactiontransaction--") The transaction that created and/or spent UTXOs. #### [`UnshieldedTransaction.createdUtxos`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#unshieldedtransactioncreatedutxosunshieldedutxo-- "Direct link to unshieldedtransactioncreatedutxosunshieldedutxo--") UTXOs created in the above transaction, possibly empty. #### [`UnshieldedTransaction.spentUtxos`](#) ● [`[UnshieldedUtxo!]!`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) non-null object[​](#unshieldedtransactionspentutxosunshieldedutxo-- "Direct link to unshieldedtransactionspentutxosunshieldedutxo--") UTXOs spent in the above transaction, possibly empty. ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`UnshieldedTransactionsEvent`](/api-reference/midnight-indexer/types/unions/unshielded-transactions-event.md) union --- # UnshieldedTransactionsProgress > For the complete documentation index, see [llms.txt](/llms.txt) Information about the unshielded indexing progress. ``` type UnshieldedTransactionsProgress { highestTransactionId: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`UnshieldedTransactionsProgress.highestTransactionId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#unshieldedtransactionsprogresshighesttransactionidint-- "Direct link to unshieldedtransactionsprogresshighesttransactionidint--") The highest transaction ID of all currently known transactions for a subscribed address. ### Implemented By[​](#implemented-by "Direct link to Implemented By") [`UnshieldedTransactionsEvent`](/api-reference/midnight-indexer/types/unions/unshielded-transactions-event.md) union --- # UnshieldedUtxo > For the complete documentation index, see [llms.txt](/llms.txt) Represents an unshielded UTXO. ``` type UnshieldedUtxo { owner: UnshieldedAddress! tokenType: HexEncoded! value: String! intentHash: HexEncoded! outputIndex: Int! ctime: Int initialNonce: HexEncoded! registeredForDustGeneration: Boolean! createdAtTransaction: Transaction! spentAtTransaction: Transaction } ``` ### Fields[​](#fields "Direct link to Fields") #### [`UnshieldedUtxo.owner`](#) ● [`UnshieldedAddress!`](/api-reference/midnight-indexer/types/scalars/unshielded-address.md) non-null scalar[​](#unshieldedutxoownerunshieldedaddress-- "Direct link to unshieldedutxoownerunshieldedaddress--") Owner Bech32m-encoded address. #### [`UnshieldedUtxo.tokenType`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#unshieldedutxotokentypehexencoded-- "Direct link to unshieldedutxotokentypehexencoded--") Token hex-encoded serialized token type. #### [`UnshieldedUtxo.value`](#) ● [`String!`](/api-reference/midnight-indexer/types/scalars/string.md) non-null scalar[​](#unshieldedutxovaluestring-- "Direct link to unshieldedutxovaluestring--") UTXO value (quantity) as a string to support u128. #### [`UnshieldedUtxo.intentHash`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#unshieldedutxointenthashhexencoded-- "Direct link to unshieldedutxointenthashhexencoded--") The hex-encoded serialized intent hash. #### [`UnshieldedUtxo.outputIndex`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#unshieldedutxooutputindexint-- "Direct link to unshieldedutxooutputindexint--") Index of this output within its creating transaction. #### [`UnshieldedUtxo.ctime`](#) ● [`Int`](/api-reference/midnight-indexer/types/scalars/int.md) scalar[​](#unshieldedutxoctimeint- "Direct link to unshieldedutxoctimeint-") The creation time in seconds. #### [`UnshieldedUtxo.initialNonce`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#unshieldedutxoinitialnoncehexencoded-- "Direct link to unshieldedutxoinitialnoncehexencoded--") The hex-encoded initial nonce for DUST generation tracking. #### [`UnshieldedUtxo.registeredForDustGeneration`](#) ● [`Boolean!`](/api-reference/midnight-indexer/types/scalars/boolean.md) non-null scalar[​](#unshieldedutxoregisteredfordustgenerationboolean-- "Direct link to unshieldedutxoregisteredfordustgenerationboolean--") Whether this UTXO is registered for DUST generation. #### [`UnshieldedUtxo.createdAtTransaction`](#) ● [`Transaction!`](/api-reference/midnight-indexer/types/interfaces/transaction.md) non-null interface[​](#unshieldedutxocreatedattransactiontransaction-- "Direct link to unshieldedutxocreatedattransactiontransaction--") Transaction that created this UTXO. #### [`UnshieldedUtxo.spentAtTransaction`](#) ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface[​](#unshieldedutxospentattransactiontransaction- "Direct link to unshieldedutxospentattransactiontransaction-") Transaction that spent this UTXO. ### Member Of[​](#member-of "Direct link to Member Of") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface ● [`UnshieldedTransaction`](/api-reference/midnight-indexer/types/objects/unshielded-transaction.md) object --- # ZswapLedgerEvent > For the complete documentation index, see [llms.txt](/llms.txt) A zswap related ledger event. ``` type ZswapLedgerEvent { id: Int! raw: HexEncoded! maxId: Int! protocolVersion: Int! } ``` ### Fields[​](#fields "Direct link to Fields") #### [`ZswapLedgerEvent.id`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#zswapledgereventidint-- "Direct link to zswapledgereventidint--") The ID of this zswap ledger event. #### [`ZswapLedgerEvent.raw`](#) ● [`HexEncoded!`](/api-reference/midnight-indexer/types/scalars/hex-encoded.md) non-null scalar[​](#zswapledgereventrawhexencoded-- "Direct link to zswapledgereventrawhexencoded--") The hex-encoded serialized event. #### [`ZswapLedgerEvent.maxId`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#zswapledgereventmaxidint-- "Direct link to zswapledgereventmaxidint--") The maximum ID of all zswap ledger events. #### [`ZswapLedgerEvent.protocolVersion`](#) ● [`Int!`](/api-reference/midnight-indexer/types/scalars/int.md) non-null scalar[​](#zswapledgereventprotocolversionint-- "Direct link to zswapledgereventprotocolversionint--") The protocol version. ### Returned By[​](#returned-by "Direct link to Returned By") [`zswapLedgerEvents`](/api-reference/midnight-indexer/operations/subscriptions/zswap-ledger-events.md) subscription ### Member Of[​](#member-of "Direct link to Member Of") [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface --- # Boolean > For the complete documentation index, see [llms.txt](/llms.txt) The `Boolean` scalar type represents `true` or `false`. ``` scalar Boolean ``` ### Member Of[​](#member-of "Direct link to Member Of") [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object ● [`include`](/api-reference/midnight-indexer/operations/directives/include.md) directive ● [`poolMetadataList`](/api-reference/midnight-indexer/operations/queries/pool-metadata-list.md) query ● [`Segment`](/api-reference/midnight-indexer/types/objects/segment.md) object ● [`skip`](/api-reference/midnight-indexer/operations/directives/skip.md) directive ● [`stakeDistribution`](/api-reference/midnight-indexer/operations/queries/stake-distribution.md) query ● [`UnshieldedUtxo`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) object --- # CardanoRewardAddress > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` scalar CardanoRewardAddress ``` ### Member Of[​](#member-of "Direct link to Member Of") [`dustGenerationStatus`](/api-reference/midnight-indexer/operations/queries/dust-generation-status.md) query ● [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object --- # DustAddress > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` scalar DustAddress ``` ### Member Of[​](#member-of "Direct link to Member Of") [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object --- # Float > For the complete documentation index, see [llms.txt](/llms.txt) The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point). ``` scalar Float ``` ### Returned By[​](#returned-by "Direct link to Returned By") [`epochUtilization`](/api-reference/midnight-indexer/operations/queries/epoch-utilization.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`RegisteredStat`](/api-reference/midnight-indexer/types/objects/registered-stat.md) object ● [`StakeShare`](/api-reference/midnight-indexer/types/objects/stake-share.md) object --- # HexEncoded > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` scalar HexEncoded ``` ### Returned By[​](#returned-by "Direct link to Returned By") [`connect`](/api-reference/midnight-indexer/operations/mutations/connect.md) mutation ### Member Of[​](#member-of "Direct link to Member Of") [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object ● [`BlockOffset`](/api-reference/midnight-indexer/types/inputs/block-offset.md) input ● [`CollapsedMerkleTree`](/api-reference/midnight-indexer/types/objects/collapsed-merkle-tree.md) object ● [`contractAction`](/api-reference/midnight-indexer/operations/queries/contract-action.md) query ● [`ContractAction`](/api-reference/midnight-indexer/types/interfaces/contract-action.md) interface ● [`contractActions`](/api-reference/midnight-indexer/operations/subscriptions/contract-actions.md) subscription ● [`ContractBalance`](/api-reference/midnight-indexer/types/objects/contract-balance.md) object ● [`ContractCall`](/api-reference/midnight-indexer/types/objects/contract-call.md) object ● [`ContractDeploy`](/api-reference/midnight-indexer/types/objects/contract-deploy.md) object ● [`ContractUpdate`](/api-reference/midnight-indexer/types/objects/contract-update.md) object ● [`disconnect`](/api-reference/midnight-indexer/operations/mutations/disconnect.md) mutation ● [`DParameterChange`](/api-reference/midnight-indexer/types/objects/dparameter-change.md) object ● [`DustGenerationDtimeUpdate`](/api-reference/midnight-indexer/types/objects/dust-generation-dtime-update.md) object ● [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object ● [`DustInitialUtxo`](/api-reference/midnight-indexer/types/objects/dust-initial-utxo.md) object ● [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface ● [`DustOutput`](/api-reference/midnight-indexer/types/objects/dust-output.md) object ● [`DustSpendProcessed`](/api-reference/midnight-indexer/types/objects/dust-spend-processed.md) object ● [`ParamChange`](/api-reference/midnight-indexer/types/objects/param-change.md) object ● [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`shieldedTransactions`](/api-reference/midnight-indexer/operations/subscriptions/shielded-transactions.md) subscription ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`TermsAndConditions`](/api-reference/midnight-indexer/types/objects/terms-and-conditions.md) object ● [`TermsAndConditionsChange`](/api-reference/midnight-indexer/types/objects/terms-and-conditions-change.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface ● [`TransactionOffset`](/api-reference/midnight-indexer/types/inputs/transaction-offset.md) input ● [`UnshieldedUtxo`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) object ● [`ZswapLedgerEvent`](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md) object --- # Int > For the complete documentation index, see [llms.txt](/llms.txt) The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. ``` scalar Int ``` ### Returned By[​](#returned-by "Direct link to Returned By") [`spoCount`](/api-reference/midnight-indexer/operations/queries/spo-count.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`Block`](/api-reference/midnight-indexer/types/objects/block.md) object ● [`BlockOffset`](/api-reference/midnight-indexer/types/inputs/block-offset.md) input ● [`CollapsedMerkleTree`](/api-reference/midnight-indexer/types/objects/collapsed-merkle-tree.md) object ● [`committee`](/api-reference/midnight-indexer/operations/queries/committee.md) query ● [`CommitteeMember`](/api-reference/midnight-indexer/types/objects/committee-member.md) object ● [`DParameter`](/api-reference/midnight-indexer/types/objects/dparameter.md) object ● [`DParameterChange`](/api-reference/midnight-indexer/types/objects/dparameter-change.md) object ● [`DustGenerationDtimeUpdate`](/api-reference/midnight-indexer/types/objects/dust-generation-dtime-update.md) object ● [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object ● [`DustInitialUtxo`](/api-reference/midnight-indexer/types/objects/dust-initial-utxo.md) object ● [`DustLedgerEvent`](/api-reference/midnight-indexer/types/interfaces/dust-ledger-event.md) interface ● [`dustLedgerEvents`](/api-reference/midnight-indexer/operations/subscriptions/dust-ledger-events.md) subscription ● [`DustSpendProcessed`](/api-reference/midnight-indexer/types/objects/dust-spend-processed.md) object ● [`EpochInfo`](/api-reference/midnight-indexer/types/objects/epoch-info.md) object ● [`EpochPerf`](/api-reference/midnight-indexer/types/objects/epoch-perf.md) object ● [`epochPerformance`](/api-reference/midnight-indexer/operations/queries/epoch-performance.md) query ● [`epochUtilization`](/api-reference/midnight-indexer/operations/queries/epoch-utilization.md) query ● [`FirstValidEpoch`](/api-reference/midnight-indexer/types/objects/first-valid-epoch.md) object ● [`ParamChange`](/api-reference/midnight-indexer/types/objects/param-change.md) object ● [`poolMetadataList`](/api-reference/midnight-indexer/operations/queries/pool-metadata-list.md) query ● [`PresenceEvent`](/api-reference/midnight-indexer/types/objects/presence-event.md) object ● [`registeredFirstValidEpochs`](/api-reference/midnight-indexer/operations/queries/registered-first-valid-epochs.md) query ● [`registeredPresence`](/api-reference/midnight-indexer/operations/queries/registered-presence.md) query ● [`registeredSpoSeries`](/api-reference/midnight-indexer/operations/queries/registered-spo-series.md) query ● [`RegisteredStat`](/api-reference/midnight-indexer/types/objects/registered-stat.md) object ● [`RegisteredTotals`](/api-reference/midnight-indexer/types/objects/registered-totals.md) object ● [`registeredTotalsSeries`](/api-reference/midnight-indexer/operations/queries/registered-totals-series.md) query ● [`RegularTransaction`](/api-reference/midnight-indexer/types/objects/regular-transaction.md) object ● [`Segment`](/api-reference/midnight-indexer/types/objects/segment.md) object ● [`shieldedTransactions`](/api-reference/midnight-indexer/operations/subscriptions/shielded-transactions.md) subscription ● [`ShieldedTransactionsProgress`](/api-reference/midnight-indexer/types/objects/shielded-transactions-progress.md) object ● [`spoIdentities`](/api-reference/midnight-indexer/operations/queries/spo-identities.md) query ● [`spoList`](/api-reference/midnight-indexer/operations/queries/spo-list.md) query ● [`spoPerformanceBySpoSk`](/api-reference/midnight-indexer/operations/queries/spo-performance-by-spo-sk.md) query ● [`spoPerformanceLatest`](/api-reference/midnight-indexer/operations/queries/spo-performance-latest.md) query ● [`stakeDistribution`](/api-reference/midnight-indexer/operations/queries/stake-distribution.md) query ● [`stakePoolOperators`](/api-reference/midnight-indexer/operations/queries/stake-pool-operators.md) query ● [`StakeShare`](/api-reference/midnight-indexer/types/objects/stake-share.md) object ● [`SystemTransaction`](/api-reference/midnight-indexer/types/objects/system-transaction.md) object ● [`TermsAndConditionsChange`](/api-reference/midnight-indexer/types/objects/terms-and-conditions-change.md) object ● [`Transaction`](/api-reference/midnight-indexer/types/interfaces/transaction.md) interface ● [`unshieldedTransactions`](/api-reference/midnight-indexer/operations/subscriptions/unshielded-transactions.md) subscription ● [`UnshieldedTransactionsProgress`](/api-reference/midnight-indexer/types/objects/unshielded-transactions-progress.md) object ● [`UnshieldedUtxo`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) object ● [`ZswapLedgerEvent`](/api-reference/midnight-indexer/types/objects/zswap-ledger-event.md) object ● [`zswapLedgerEvents`](/api-reference/midnight-indexer/operations/subscriptions/zswap-ledger-events.md) subscription --- # String > For the complete documentation index, see [llms.txt](/llms.txt) The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. ``` scalar String ``` ### Returned By[​](#returned-by "Direct link to Returned By") [`stakePoolOperators`](/api-reference/midnight-indexer/operations/queries/stake-pool-operators.md) query ### Member Of[​](#member-of "Direct link to Member Of") [`CommitteeMember`](/api-reference/midnight-indexer/types/objects/committee-member.md) object ● [`ContractBalance`](/api-reference/midnight-indexer/types/objects/contract-balance.md) object ● [`ContractCall`](/api-reference/midnight-indexer/types/objects/contract-call.md) object ● [`deprecated`](/api-reference/midnight-indexer/types/directives/deprecated.md) directive ● [`DustGenerationStatus`](/api-reference/midnight-indexer/types/objects/dust-generation-status.md) object ● [`EpochPerf`](/api-reference/midnight-indexer/types/objects/epoch-perf.md) object ● [`FirstValidEpoch`](/api-reference/midnight-indexer/types/objects/first-valid-epoch.md) object ● [`poolMetadata`](/api-reference/midnight-indexer/operations/queries/pool-metadata.md) query ● [`PoolMetadata`](/api-reference/midnight-indexer/types/objects/pool-metadata.md) object ● [`PresenceEvent`](/api-reference/midnight-indexer/types/objects/presence-event.md) object ● [`specifiedBy`](/api-reference/midnight-indexer/types/directives/specified-by.md) directive ● [`Spo`](/api-reference/midnight-indexer/types/objects/spo.md) object ● [`spoByPoolId`](/api-reference/midnight-indexer/operations/queries/spo-by-pool-id.md) query ● [`spoCompositeByPoolId`](/api-reference/midnight-indexer/operations/queries/spo-composite-by-pool-id.md) query ● [`SpoIdentity`](/api-reference/midnight-indexer/types/objects/spo-identity.md) object ● [`spoIdentityByPoolId`](/api-reference/midnight-indexer/operations/queries/spo-identity-by-pool-id.md) query ● [`spoList`](/api-reference/midnight-indexer/operations/queries/spo-list.md) query ● [`spoPerformanceBySpoSk`](/api-reference/midnight-indexer/operations/queries/spo-performance-by-spo-sk.md) query ● [`stakeDistribution`](/api-reference/midnight-indexer/operations/queries/stake-distribution.md) query ● [`StakeShare`](/api-reference/midnight-indexer/types/objects/stake-share.md) object ● [`TermsAndConditions`](/api-reference/midnight-indexer/types/objects/terms-and-conditions.md) object ● [`TermsAndConditionsChange`](/api-reference/midnight-indexer/types/objects/terms-and-conditions-change.md) object ● [`TransactionFees`](/api-reference/midnight-indexer/types/objects/transaction-fees.md) object ● [`UnshieldedUtxo`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) object --- # Unit > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` scalar Unit ``` ### Returned By[​](#returned-by "Direct link to Returned By") [`disconnect`](/api-reference/midnight-indexer/operations/mutations/disconnect.md) mutation --- # UnshieldedAddress > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` scalar UnshieldedAddress ``` ### Member Of[​](#member-of "Direct link to Member Of") [`unshieldedTransactions`](/api-reference/midnight-indexer/operations/subscriptions/unshielded-transactions.md) subscription ● [`UnshieldedUtxo`](/api-reference/midnight-indexer/types/objects/unshielded-utxo.md) object --- # ViewingKey > For the complete documentation index, see [llms.txt](/llms.txt) No description ``` scalar ViewingKey ``` ### Member Of[​](#member-of "Direct link to Member Of") [`connect`](/api-reference/midnight-indexer/operations/mutations/connect.md) mutation --- # ShieldedTransactionsEvent > For the complete documentation index, see [llms.txt](/llms.txt) An event of the shielded transactions subscription. ``` union ShieldedTransactionsEvent = | RelevantTransaction | ShieldedTransactionsProgress ``` ### Possible types[​](#possible-types "Direct link to Possible types") #### [`ShieldedTransactionsEvent.RelevantTransaction`](/api-reference/midnight-indexer/types/objects/relevant-transaction.md) object[​](#shieldedtransactionseventrelevanttransaction- "Direct link to shieldedtransactionseventrelevanttransaction-") A transaction relevant for the subscribing wallet and an optional collapsed merkle tree. #### [`ShieldedTransactionsEvent.ShieldedTransactionsProgress`](/api-reference/midnight-indexer/types/objects/shielded-transactions-progress.md) object[​](#shieldedtransactionseventshieldedtransactionsprogress- "Direct link to shieldedtransactionseventshieldedtransactionsprogress-") Information about the shielded transactions indexing progress. ### Returned By[​](#returned-by "Direct link to Returned By") [`shieldedTransactions`](/api-reference/midnight-indexer/operations/subscriptions/shielded-transactions.md) subscription --- # UnshieldedTransactionsEvent > For the complete documentation index, see [llms.txt](/llms.txt) An event of the unshielded transactions subscription. ``` union UnshieldedTransactionsEvent = | UnshieldedTransaction | UnshieldedTransactionsProgress ``` ### Possible types[​](#possible-types "Direct link to Possible types") #### [`UnshieldedTransactionsEvent.UnshieldedTransaction`](/api-reference/midnight-indexer/types/objects/unshielded-transaction.md) object[​](#unshieldedtransactionseventunshieldedtransaction- "Direct link to unshieldedtransactionseventunshieldedtransaction-") A transaction that created and/or spent UTXOs alongside these and other information. #### [`UnshieldedTransactionsEvent.UnshieldedTransactionsProgress`](/api-reference/midnight-indexer/types/objects/unshielded-transactions-progress.md) object[​](#unshieldedtransactionseventunshieldedtransactionsprogress- "Direct link to unshieldedtransactionseventunshieldedtransactionsprogress-") Information about the unshielded indexing progress. ### Returned By[​](#returned-by "Direct link to Returned By") [`unshieldedTransactions`](/api-reference/midnight-indexer/operations/subscriptions/unshielded-transactions.md) subscription --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight JS API **Midnight.js API Reference v4.0.4** *** # Midnight.js TypeScript framework for building privacy-preserving dApps on the Midnight blockchain. Midnight.js provides tools for deploying and interacting with smart contracts, managing encrypted private state, generating zero-knowledge proofs, and submitting transactions to the Midnight network. ## Architecture[​](#architecture "Direct link to Architecture") Midnight.js uses a **modular provider pattern** where each capability is pluggable: ``` MidnightProviders ├── privateStateProvider — Encrypted local state storage ├── publicDataProvider — Blockchain data queries via GraphQL ├── zkConfigProvider — ZK artifact retrieval (prover/verifier keys) ├── proofProvider — Zero-knowledge proof generation ├── walletProvider — Transaction balancing and signing ├── midnightProvider — Transaction submission to the network └── loggerProvider — Optional diagnostics logging ``` ## Packages[​](#packages "Direct link to Packages") ### Core[​](#core "Direct link to Core") | Package | Purpose | | ---------------------------------------- | ----------------------------------------------------------------- | | `@midnight-ntwrk/midnight-js-types` | Shared types, interfaces, and provider contracts | | `@midnight-ntwrk/midnight-js-contracts` | Contract deployment, circuit calls, and transaction submission | | `@midnight-ntwrk/midnight-js-network-id` | Network identifier configuration for runtime and ledger WASM APIs | | `@midnight-ntwrk/midnight-js-utils` | Shared utilities (hex encoding, bech32m, assertions) | ### Providers[​](#providers "Direct link to Providers") | Package | Purpose | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `@midnight-ntwrk/midnight-js-indexer-public-data-provider` | GraphQL-based blockchain data provider (queries and subscriptions) | | `@midnight-ntwrk/midnight-js-level-private-state-provider` | AES-256-GCM encrypted persistent state storage via [LevelDB](https://github.com/Level/level) | | `@midnight-ntwrk/midnight-js-http-client-proof-provider` | HTTP client for the Midnight proof server | | `@midnight-ntwrk/midnight-js-fetch-zk-config-provider` | Browser-compatible ZK artifact provider using the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | | `@midnight-ntwrk/midnight-js-node-zk-config-provider` | Node.js filesystem-based ZK artifact provider | | `@midnight-ntwrk/midnight-js-logger-provider` | Application-specific [Pino](https://github.com/pinojs/pino) logger configuration | ### Tooling[​](#tooling "Direct link to Tooling") | Package | Purpose | | ------------------------------------- | ------------------------------------------------- | | `@midnight-ntwrk/midnight-js-compact` | Compact compiler manager for contract compilation | ## Quick Start[​](#quick-start "Direct link to Quick Start") ### 1. Configure the network[​](#1-configure-the-network "Direct link to 1. Configure the network") ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('testnet'); ``` ### 2. Assemble providers[​](#2-assemble-providers "Direct link to 2. Assemble providers") ``` import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { FetchZkConfigProvider } from '@midnight-ntwrk/midnight-js-fetch-zk-config-provider'; const zkConfigProvider = new FetchZkConfigProvider(zkArtifactsUrl); const providers: MidnightProviders = { privateStateProvider: levelPrivateStateProvider({ privateStoragePasswordProvider: () => password, accountId: walletAddress, }), publicDataProvider: indexerPublicDataProvider(queryUrl, subscriptionUrl), zkConfigProvider, proofProvider: httpClientProofProvider(proofServerUrl, zkConfigProvider), walletProvider, // from @midnight-ntwrk/wallet-sdk-facade midnightProvider, // from @midnight-ntwrk/wallet-sdk-facade }; ``` ### 3. Deploy and interact with a contract[​](#3-deploy-and-interact-with-a-contract "Direct link to 3. Deploy and interact with a contract") ``` import { deployContract, findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; const deployed = await deployContract(providers, { compiledContract, privateStateId: 'my-state', initialPrivateState: { counter: 0n }, }); const result = await deployed.callTx.increment(); ``` ### 4. Query state[​](#4-query-state "Direct link to 4. Query state") ``` import { getStates, getPublicStates } from '@midnight-ntwrk/midnight-js-contracts'; const states = await getStates(providers, contractAddress, privateStateId); const publicStates = await getPublicStates(providers, contractAddress); ``` ## Key Concepts[​](#key-concepts "Direct link to Key Concepts") ### Contract Model[​](#contract-model "Direct link to Contract Model") | Term | Description | | ----------------- | ---------------------------------------------------------------------------------- | | **Circuit** | Smart contract function that executes locally and generates a zero-knowledge proof | | **Witness** | Private computation that runs on the end-user's device | | **Private state** | User-local state updated by circuits — never stored on-chain | | **Ledger state** | On-chain public contract state | ### ZK Artifacts[​](#zk-artifacts "Direct link to ZK Artifacts") | Artifact | Role | | ---------------- | ---------------------------------------------------------------- | | **Prover key** | Binary used to create zero-knowledge proofs | | **Verifier key** | Binary used for on-chain proof verification | | **ZKIR** | Zero-Knowledge Intermediate Representation of compiled contracts | ### Transaction Flow[​](#transaction-flow "Direct link to Transaction Flow") ``` 1. Execute circuit locally → Unproven transaction 2. Generate ZK proofs → ProofProvider 3. Balance transaction → WalletProvider 4. Submit to network → MidnightProvider 5. Wait for finalization → PublicDataProvider ``` ### Transaction Status[​](#transaction-status "Direct link to Transaction Status") | Status | Meaning | | ----------------- | ----------------------------------------------------- | | `SucceedEntirely` | All transaction segments succeeded | | `FailFallible` | Guaranteed portion succeeded, fallible portion failed | | `FailEntirely` | Transaction is invalid | ## Private State Security[​](#private-state-security "Direct link to Private State Security") * **Encryption**: AES-256-GCM at rest * **Key derivation**: PBKDF2-SHA256 (600,000 iterations) * **Isolation**: Account-scoped storage keyed by SHA-256 hash of wallet address * **No built-in recovery**: Production deployments require a backup strategy --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js # Midnight.js Barrel package that provides a single entry point to the core components of Midnight.js. Import all core modules from one package instead of installing them individually. ## Installation[​](#installation "Direct link to Installation") ``` yarn add @midnight-ntwrk/midnight-js ``` ## Quick Start[​](#quick-start "Direct link to Quick Start") ``` import { contracts, networkId, types, utils } from '@midnight-ntwrk/midnight-js'; networkId.setNetworkId('testnet'); const deployed = await contracts.deployContract(providers, { compiledContract: myContract, privateStateId: 'my-state', initialPrivateState: { counter: 0n } }); ``` ## Modules[​](#modules "Direct link to Modules") | Module | Package | Description | | ----------- | ---------------------------------------- | ------------------------------------------------ | | `contracts` | `@midnight-ntwrk/midnight-js-contracts` | Contract deployment and interaction utilities | | `networkId` | `@midnight-ntwrk/midnight-js-network-id` | Network identifier management | | `protocol` | `@midnight-ntwrk/midnight-js-protocol` | Version-agnostic protocol type re-exports | | `types` | `@midnight-ntwrk/midnight-js-types` | Shared types, interfaces, and provider contracts | | `utils` | `@midnight-ntwrk/midnight-js-utils` | Hex encoding, address validation, and utilities | ## Sub-path Imports[​](#sub-path-imports "Direct link to Sub-path Imports") Each module is also available as a sub-path import for tree-shaking: ``` import { deployContract, findDeployedContract } from '@midnight-ntwrk/midnight-js/contracts'; import { setNetworkId, getNetworkId } from '@midnight-ntwrk/midnight-js/network-id'; import { type ProofProvider, type WalletProvider } from '@midnight-ntwrk/midnight-js/types'; import { toHex, fromHex } from '@midnight-ntwrk/midnight-js/utils'; ``` ## Exports[​](#exports "Direct link to Exports") ``` // Namespace imports (all modules) import { contracts, networkId, types, utils } from '@midnight-ntwrk/midnight-js'; // Sub-path imports (individual modules) import { ... } from '@midnight-ntwrk/midnight-js/contracts'; import { ... } from '@midnight-ntwrk/midnight-js/network-id'; import { ... } from '@midnight-ntwrk/midnight-js/types'; import { ... } from '@midnight-ntwrk/midnight-js/utils'; ``` ## Resources[​](#resources "Direct link to Resources") * [Midnight Network](https://midnight.network) * [Developer Hub](https://midnight.network/developer-hub) ## Terms & License[​](#terms--license "Direct link to Terms & License") By using this package, you agree to [Midnight's Terms and Conditions](https://midnight.network/static/terms.pdf) and [Privacy Policy](https://midnight.network/static/privacy-policy.pdf). Licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-contracts [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-contracts # @midnight-ntwrk/midnight-js-contracts ## Classes[​](#classes "Direct link to Classes") * [CallTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/CallTxFailedError.md) * [ContractTypeError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/ContractTypeError.md) * [DeployTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/DeployTxFailedError.md) * [IncompleteCallTxPrivateStateConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/IncompleteCallTxPrivateStateConfig.md) * [IncompleteFindContractPrivateStateConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/IncompleteFindContractPrivateStateConfig.md) * [InsertVerifierKeyTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/InsertVerifierKeyTxFailedError.md) * [RemoveVerifierKeyTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/RemoveVerifierKeyTxFailedError.md) * [ReplaceMaintenanceAuthorityTxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/ReplaceMaintenanceAuthorityTxFailedError.md) * [TxFailedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md) ## Interfaces[​](#interfaces "Direct link to Interfaces") * [ContractMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/ContractMaintenanceTxInterface.md) * [TransactionContext](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/TransactionContext.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [CallOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptions.md) * [CallOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsBase.md) * [CallOptionsProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsProviderDataDependencies.md) * [CallOptionsWithArguments](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithArguments.md) * [CallOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithPrivateState.md) * [CallOptionsWithProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithProviderDataDependencies.md) * [CallResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md) * [CallResultPrivate](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResultPrivate.md) * [CallResultPublic](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResultPublic.md) * [CallTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptions.md) * [CallTxOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsBase.md) * [CallTxOptionsWithPrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsWithPrivateStateId.md) * [CircuitCallTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitCallTxInterface.md) * [CircuitMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md) * [CircuitMaintenanceTxInterfaces](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterfaces.md) * [ContractConstructorOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptions.md) * [ContractConstructorOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsBase.md) * [ContractConstructorOptionsProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsProviderDataDependencies.md) * [ContractConstructorOptionsWithArguments](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithArguments.md) * [ContractConstructorOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithPrivateState.md) * [ContractConstructorOptionsWithProviderDataDependencies](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithProviderDataDependencies.md) * [ContractConstructorResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorResult.md) * [ContractProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md) * [ContractStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md) * [DeployContractOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptions.md) * [DeployContractOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsBase.md) * [DeployContractOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsWithPrivateState.md) * [DeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md) * [DeployTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptions.md) * [DeployTxOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md) * [DeployTxOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md) * [DeployTxOptionsWithPrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateStateId.md) * [FinalizedCallTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md) * [FinalizedDeployTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md) * [FinalizedDeployTxDataBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxDataBase.md) * [FindDeployedContractOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptions.md) * [FindDeployedContractOptionsBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsBase.md) * [FindDeployedContractOptionsExistingPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsExistingPrivateState.md) * [FindDeployedContractOptionsStorePrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsStorePrivateState.md) * [FoundContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md) * [PublicContractStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) * [ScopedTransactionOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ScopedTransactionOptions.md) * [SubmittedCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmittedCallTx.md) * [SubmitTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxOptions.md) * [SubmitTxProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxProviders.md) * [UnprovenCallTxProvidersBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersBase.md) * [UnprovenCallTxProvidersWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersWithPrivateState.md) * [UnprovenDeployTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenDeployTxOptions.md) * [UnprovenDeployTxProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenDeployTxProviders.md) * [UnsubmittedCallTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md) * [UnsubmittedDeployTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md) * [UnsubmittedDeployTxDataBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxDataBase.md) * [UnsubmittedDeployTxPrivateData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxPrivateData.md) * [UnsubmittedDeployTxPublicData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxPublicData.md) * [UnsubmittedTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedTxData.md) ## Variables[​](#variables "Direct link to Variables") * [withContractScopedTransaction](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/variables/withContractScopedTransaction.md) ## Functions[​](#functions "Direct link to Functions") * [createCallTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCallTxOptions.md) * [createCircuitCallTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCircuitCallTxInterface.md) * [createCircuitMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCircuitMaintenanceTxInterface.md) * [createCircuitMaintenanceTxInterfaces](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createCircuitMaintenanceTxInterfaces.md) * [createContractMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createContractMaintenanceTxInterface.md) * [createUnprovenCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenCallTx.md) * [createUnprovenCallTxFromInitialStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenCallTxFromInitialStates.md) * [createUnprovenDeployTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenDeployTx.md) * [createUnprovenDeployTxFromVerifierKeys](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenDeployTxFromVerifierKeys.md) * [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md) * [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md) * [getPublicStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/getPublicStates.md) * [getStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/getStates.md) * [getUnshieldedBalances](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/getUnshieldedBalances.md) * [submitCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitCallTx.md) * [submitCallTxAsync](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitCallTxAsync.md) * [submitDeployTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitDeployTx.md) * [submitInsertVerifierKeyTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitInsertVerifierKeyTx.md) * [submitRemoveVerifierKeyTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitRemoveVerifierKeyTx.md) * [submitReplaceAuthorityTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitReplaceAuthorityTx.md) * [submitTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTx.md) * [submitTxAsync](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTxAsync.md) * [verifierKeysEqual](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/verifierKeysEqual.md) * [verifyContractState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/verifyContractState.md) --- # CallTxFailedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallTxFailedError # Class: CallTxFailedError An error indicating that a call transaction was not successfully applied by the consensus node. ## Extends[​](#extends "Direct link to Extends") * [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new CallTxFailedError**(`finalizedTxData`, `circuitId`): `CallTxFailedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` The finalization data of the call transaction that failed. ##### circuitId[​](#circuitid "Direct link to circuitId") `string` | `string`\[] The name of the circuit that was called to build the transaction. #### Returns[​](#returns "Direct link to Returns") `CallTxFailedError` #### Overrides[​](#overrides "Direct link to Overrides") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid-1 "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`circuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#circuitid) *** ### finalizedTxData[​](#finalizedtxdata-1 "Direct link to finalizedTxData") > `readonly` **finalizedTxData**: `FinalizedTxData` The finalization data of the transaction that failed. #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`finalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#finalizedtxdata) --- # ContractTypeError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractTypeError # Class: ContractTypeError The error that is thrown when there is a contract type mismatch between a given contract type, and the initial state that is deployed at a given contract address. ## Remarks[​](#remarks "Direct link to Remarks") This error is typically thrown during calls to [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md) where the supplied contract address represents a different type of contract to the contract type given. ## Extends[​](#extends "Direct link to Extends") * `TypeError` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new ContractTypeError**(`contractState`, `circuitIds`): `ContractTypeError` Initializes a new ContractTypeError. #### Parameters[​](#parameters "Direct link to Parameters") ##### contractState[​](#contractstate "Direct link to contractState") `ContractState` The initial deployed contract state. ##### circuitIds[​](#circuitids "Direct link to circuitIds") `string`\[] The circuits that are undefined, or have a verifier key mismatch with the key present in `contractState`. #### Returns[​](#returns "Direct link to Returns") `ContractTypeError` #### Overrides[​](#overrides "Direct link to Overrides") `TypeError.constructor` ## Properties[​](#properties "Direct link to Properties") ### circuitIds[​](#circuitids-1 "Direct link to circuitIds") > `readonly` **circuitIds**: `string`\[] The circuits that are undefined, or have a verifier key mismatch with the key present in `contractState`. *** ### contractState[​](#contractstate-1 "Direct link to contractState") > `readonly` **contractState**: `ContractState` The initial deployed contract state. --- # DeployTxFailedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployTxFailedError # Class: DeployTxFailedError An error indicating that a deploy transaction was not successfully applied by the consensus node. ## Extends[​](#extends "Direct link to Extends") * [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new DeployTxFailedError**(`finalizedTxData`): `DeployTxFailedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` The finalization data of the deployment transaction that failed. #### Returns[​](#returns "Direct link to Returns") `DeployTxFailedError` #### Overrides[​](#overrides "Direct link to Overrides") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`circuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#circuitid) *** ### finalizedTxData[​](#finalizedtxdata-1 "Direct link to finalizedTxData") > `readonly` **finalizedTxData**: `FinalizedTxData` The finalization data of the transaction that failed. #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`finalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#finalizedtxdata) --- # IncompleteCallTxPrivateStateConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / IncompleteCallTxPrivateStateConfig # Class: IncompleteCallTxPrivateStateConfig An error indicating that a private state ID was specified for a call transaction while a private state provider was not. We want to let the user know so that they aren't under the impression the private state of a contract was updated when it wasn't. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new IncompleteCallTxPrivateStateConfig**(): `IncompleteCallTxPrivateStateConfig` #### Returns[​](#returns "Direct link to Returns") `IncompleteCallTxPrivateStateConfig` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` --- # IncompleteFindContractPrivateStateConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / IncompleteFindContractPrivateStateConfig # Class: IncompleteFindContractPrivateStateConfig An error indicating that an initial private state was specified for a contract find while a private state ID was not. We can't store the initial private state if we don't have a private state ID, and we need to let the user know that. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new IncompleteFindContractPrivateStateConfig**(): `IncompleteFindContractPrivateStateConfig` #### Returns[​](#returns "Direct link to Returns") `IncompleteFindContractPrivateStateConfig` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` --- # InsertVerifierKeyTxFailedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / InsertVerifierKeyTxFailedError # Class: InsertVerifierKeyTxFailedError An error indicating that a verifier key insertion transaction failed. ## Extends[​](#extends "Direct link to Extends") * [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new InsertVerifierKeyTxFailedError**(`finalizedTxData`): `InsertVerifierKeyTxFailedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` #### Returns[​](#returns "Direct link to Returns") `InsertVerifierKeyTxFailedError` #### Overrides[​](#overrides "Direct link to Overrides") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`circuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#circuitid) *** ### finalizedTxData[​](#finalizedtxdata-1 "Direct link to finalizedTxData") > `readonly` **finalizedTxData**: `FinalizedTxData` The finalization data of the transaction that failed. #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`finalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#finalizedtxdata) --- # RemoveVerifierKeyTxFailedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / RemoveVerifierKeyTxFailedError # Class: RemoveVerifierKeyTxFailedError An error indicating that a verifier key removal transaction failed. ## Extends[​](#extends "Direct link to Extends") * [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new RemoveVerifierKeyTxFailedError**(`finalizedTxData`): `RemoveVerifierKeyTxFailedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` #### Returns[​](#returns "Direct link to Returns") `RemoveVerifierKeyTxFailedError` #### Overrides[​](#overrides "Direct link to Overrides") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`circuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#circuitid) *** ### finalizedTxData[​](#finalizedtxdata-1 "Direct link to finalizedTxData") > `readonly` **finalizedTxData**: `FinalizedTxData` The finalization data of the transaction that failed. #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`finalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#finalizedtxdata) --- # ReplaceMaintenanceAuthorityTxFailedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ReplaceMaintenanceAuthorityTxFailedError # Class: ReplaceMaintenanceAuthorityTxFailedError An error indicating that a contract maintenance authority replacement transaction failed. ## Extends[​](#extends "Direct link to Extends") * [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new ReplaceMaintenanceAuthorityTxFailedError**(`finalizedTxData`): `ReplaceMaintenanceAuthorityTxFailedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` #### Returns[​](#returns "Direct link to Returns") `ReplaceMaintenanceAuthorityTxFailedError` #### Overrides[​](#overrides "Direct link to Overrides") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`circuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#circuitid) *** ### finalizedTxData[​](#finalizedtxdata-1 "Direct link to finalizedTxData") > `readonly` **finalizedTxData**: `FinalizedTxData` The finalization data of the transaction that failed. #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`TxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md).[`finalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/TxFailedError.md#finalizedtxdata) --- # TxFailedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / TxFailedError # Class: TxFailedError An error indicating that a transaction submitted to a consensus node failed. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Extended by[​](#extended-by "Direct link to Extended by") * [`CallTxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/CallTxFailedError.md) * [`DeployTxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/DeployTxFailedError.md) * [`InsertVerifierKeyTxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/InsertVerifierKeyTxFailedError.md) * [`RemoveVerifierKeyTxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/RemoveVerifierKeyTxFailedError.md) * [`ReplaceMaintenanceAuthorityTxFailedError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/classes/ReplaceMaintenanceAuthorityTxFailedError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new TxFailedError**(`finalizedTxData`, `circuitId?`): `TxFailedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` The finalization data of the transaction that failed. ##### circuitId?[​](#circuitid "Direct link to circuitId?") `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. #### Returns[​](#returns "Direct link to Returns") `TxFailedError` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid-1 "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `string` | `string`\[] The name of the circuit that was called to create the call transaction that failed. Only defined if a call transaction failed. *** ### finalizedTxData[​](#finalizedtxdata-1 "Direct link to finalizedTxData") > `readonly` **finalizedTxData**: `FinalizedTxData` The finalization data of the transaction that failed. --- # createCallTxOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createCallTxOptions # Function: createCallTxOptions() > **createCallTxOptions**<`C`, `PCK`>(`compiledContract`, `circuitId`, `contractAddress`, `privateStateId`, `additionalCoinEncPublicKeyMappings`, `args`): [`CallTxOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptions.md)<`C`, `PCK`> Creates a [CallTxOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptions.md) object from various data. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> ### circuitId[​](#circuitid "Direct link to circuitId") `PCK` ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` ### privateStateId[​](#privatestateid "Direct link to privateStateId") `string` | `undefined` ### additionalCoinEncPublicKeyMappings[​](#additionalcoinencpublickeymappings "Direct link to additionalCoinEncPublicKeyMappings") `ReadonlyMap`<`string`, `string`> | `undefined` ### args[​](#args "Direct link to args") `CircuitParameters`<`C`, `PCK`> ## Returns[​](#returns "Direct link to Returns") [`CallTxOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptions.md)<`C`, `PCK`> --- # createCircuitCallTxInterface > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createCircuitCallTxInterface # Function: createCircuitCallTxInterface() > **createCircuitCallTxInterface**<`C`>(`providers`, `compiledContract`, `contractAddress`, `privateStateId`): [`CircuitCallTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitCallTxInterface.md)<`C`> Creates a circuit call transaction interface for a contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> The providers to use to build transactions. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> The contract to use to execute circuits. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The ledger address of the contract. ### privateStateId[​](#privatestateid "Direct link to privateStateId") `string` | `undefined` The identifier of the state of the witnesses of the contract. ## Returns[​](#returns "Direct link to Returns") [`CircuitCallTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitCallTxInterface.md)<`C`> --- # createCircuitMaintenanceTxInterface > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createCircuitMaintenanceTxInterface # Function: createCircuitMaintenanceTxInterface() > **createCircuitMaintenanceTxInterface**<`C`, `PCK`>(`providers`, `circuitId`, `compiledContract`, `contractAddress`): [`CircuitMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md) Creates a [CircuitMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`, `PCK`> The providers to use to create and submit transactions. ### circuitId[​](#circuitid "Direct link to circuitId") `PCK` The circuit ID the interface is for. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The address of the deployed contract for which this interface is being created. ## Returns[​](#returns "Direct link to Returns") [`CircuitMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md) --- # createCircuitMaintenanceTxInterfaces > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createCircuitMaintenanceTxInterfaces # Function: createCircuitMaintenanceTxInterfaces() > **createCircuitMaintenanceTxInterfaces**<`C`>(`providers`, `compiledContract`, `contractAddress`): [`CircuitMaintenanceTxInterfaces`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterfaces.md)<`C`> Creates a [CircuitMaintenanceTxInterfaces](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterfaces.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> The providers to use to build transactions. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> The contract to use to execute circuits. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The ledger address of the contract. ## Returns[​](#returns "Direct link to Returns") [`CircuitMaintenanceTxInterfaces`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterfaces.md)<`C`> --- # createContractMaintenanceTxInterface > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createContractMaintenanceTxInterface # Function: createContractMaintenanceTxInterface() > **createContractMaintenanceTxInterface**<`C`>(`providers`, `compiledContract`, `contractAddress`): [`ContractMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/ContractMaintenanceTxInterface.md) Creates a [ContractMaintenanceTxInterface](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/ContractMaintenanceTxInterface.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md) The providers to use to build transactions. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The ledger address of the contract. ## Returns[​](#returns "Direct link to Returns") [`ContractMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/ContractMaintenanceTxInterface.md) --- # createUnprovenCallTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createUnprovenCallTx # Function: createUnprovenCallTx() Calls a circuit using states fetched from the public data provider and private state provider, then creates an unbalanced, unproven, unsubmitted, call transaction. ## Param[​](#param "Direct link to Param") The providers to use to create the call transaction. ## Param[​](#param-1 "Direct link to Param") Configuration. ## Param[​](#param-2 "Direct link to Param") Optional scoped transaction context to participate in an existing transaction scope. ## Throws[​](#throws "Direct link to Throws") IncompleteCallTxPrivateStateConfig If a `privateStateId` was given but a `privateStateProvider` was not. We assume that when a user gives a `privateStateId`, they want to update the private state store. ## Call Signature[​](#call-signature "Direct link to Call Signature") > **createUnprovenCallTx**<`C`, `PCK`>(`providers`, `options`, `transactionContext?`): `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> #### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters "Direct link to Parameters") #### providers[​](#providers "Direct link to providers") [`UnprovenCallTxProvidersBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersBase.md) #### options[​](#options "Direct link to options") [`CallOptionsWithArguments`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithArguments.md)<`C`, `PCK`> #### transactionContext?[​](#transactioncontext "Direct link to transactionContext?") [`TransactionContext`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/TransactionContext.md)<`C`, `PCK`> ### Returns[​](#returns "Direct link to Returns") `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **createUnprovenCallTx**<`C`, `PCK`>(`providers`, `options`, `transactionContext?`): `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` #### PCK[​](#pck-1 "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### providers[​](#providers-1 "Direct link to providers") [`UnprovenCallTxProvidersWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersWithPrivateState.md)<`C`> #### options[​](#options-1 "Direct link to options") [`CallTxOptionsWithPrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsWithPrivateStateId.md)<`C`, `PCK`> #### transactionContext?[​](#transactioncontext-1 "Direct link to transactionContext?") [`TransactionContext`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/TransactionContext.md)<`C`, `PCK`> ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> --- # createUnprovenCallTxFromInitialStates > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createUnprovenCallTxFromInitialStates # Function: createUnprovenCallTxFromInitialStates() Calls a circuit using the provided initial `states` and creates an unbalanced, unproven, unsubmitted, call transaction. ## Param[​](#param "Direct link to Param") ## Param[​](#param-1 "Direct link to Param") Configuration. ## Param[​](#param-2 "Direct link to Param") ## Call Signature[​](#call-signature "Direct link to Call Signature") > **createUnprovenCallTxFromInitialStates**<`C`, `PCK`>(`zkConfigProvider`, `options`, `walletEncryptionPublicKey`): `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> #### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters "Direct link to Parameters") #### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`string`> #### options[​](#options "Direct link to options") [`CallOptionsWithProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithProviderDataDependencies.md)<`C`, `PCK`> #### walletEncryptionPublicKey[​](#walletencryptionpublickey "Direct link to walletEncryptionPublicKey") `string` ### Returns[​](#returns "Direct link to Returns") `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **createUnprovenCallTxFromInitialStates**<`C`, `PCK`>(`zkConfigProvider`, `options`, `walletEncryptionPublicKey`): `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` #### PCK[​](#pck-1 "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### zkConfigProvider[​](#zkconfigprovider-1 "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`string`> #### options[​](#options-1 "Direct link to options") [`CallOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithPrivateState.md)<`C`, `PCK`> #### walletEncryptionPublicKey[​](#walletencryptionpublickey-1 "Direct link to walletEncryptionPublicKey") `string` ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>> --- # createUnprovenDeployTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createUnprovenDeployTx # Function: createUnprovenDeployTx() Calls a contract constructor and creates an unbalanced, unproven, unsubmitted, deploy transaction from the constructor results. ## Param[​](#param "Direct link to Param") The providers to use to create the deploy transaction. ## Param[​](#param-1 "Direct link to Param") Configuration. ## Call Signature[​](#call-signature "Direct link to Call Signature") > **createUnprovenDeployTx**<`C`>(`providers`, `options`): `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> ### Parameters[​](#parameters "Direct link to Parameters") #### providers[​](#providers "Direct link to providers") [`UnprovenDeployTxProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenDeployTxProviders.md)<`C`> #### options[​](#options "Direct link to options") [`DeployTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md)<`C`> ### Returns[​](#returns "Direct link to Returns") `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **createUnprovenDeployTx**<`C`>(`providers`, `options`): `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### providers[​](#providers-1 "Direct link to providers") [`UnprovenDeployTxProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenDeployTxProviders.md)<`C`> #### options[​](#options-1 "Direct link to options") [`DeployTxOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md)<`C`> ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> --- # createUnprovenDeployTxFromVerifierKeys > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / createUnprovenDeployTxFromVerifierKeys # Function: createUnprovenDeployTxFromVerifierKeys() Calls a contract constructor and creates an unbalanced, unproven, unsubmitted, deploy transaction from the constructor results. ## Param[​](#param "Direct link to Param") The verifier keys for the contract being deployed. ## Param[​](#param-1 "Direct link to Param") The Zswap coin public key of the current user. ## Param[​](#param-2 "Direct link to Param") Configuration. ## Param[​](#param-3 "Direct link to Param") ## Call Signature[​](#call-signature "Direct link to Call Signature") > **createUnprovenDeployTxFromVerifierKeys**<`C`>(`zkConfigProvider`, `coinPublicKey`, `options`, `encryptionPublicKey`): `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> ### Parameters[​](#parameters "Direct link to Parameters") #### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`string`> #### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") `string` #### options[​](#options "Direct link to options") [`DeployTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md)<`C`> #### encryptionPublicKey[​](#encryptionpublickey "Direct link to encryptionPublicKey") `string` ### Returns[​](#returns "Direct link to Returns") `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **createUnprovenDeployTxFromVerifierKeys**<`C`>(`zkConfigProvider`, `coinPublicKey`, `options`, `encryptionPublicKey`): `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### zkConfigProvider[​](#zkconfigprovider-1 "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`string`> #### coinPublicKey[​](#coinpublickey-1 "Direct link to coinPublicKey") `string` #### options[​](#options-1 "Direct link to options") [`DeployTxOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md)<`C`> #### encryptionPublicKey[​](#encryptionpublickey-1 "Direct link to encryptionPublicKey") `string` ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`>> --- # deployContract > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / deployContract # Function: deployContract() Creates and submits a contract deployment transaction. This function is the entry point for the transaction construction workflow and is used to create a [DeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md) instance. ## Param[​](#param "Direct link to Param") The providers used to manage the transaction lifecycle. ## Param[​](#param-1 "Direct link to Param") Configuration. ## Throws[​](#throws "Direct link to Throws") DeployTxFailedError If the transaction is submitted successfully but produces an error when executed by the node. ## Call Signature[​](#call-signature "Direct link to Call Signature") > **deployContract**<`C`>(`providers`, `options`): `Promise`<[`DeployedContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md)<`C`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> ### Parameters[​](#parameters "Direct link to Parameters") #### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`, `ProvableCircuitId`<`C`>, `unknown`> #### options[​](#options "Direct link to options") [`DeployContractOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsBase.md)<`C`> ### Returns[​](#returns "Direct link to Returns") `Promise`<[`DeployedContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md)<`C`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **deployContract**<`C`>(`providers`, `options`): `Promise`<[`DeployedContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md)<`C`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### providers[​](#providers-1 "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> #### options[​](#options-1 "Direct link to options") [`DeployContractOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsWithPrivateState.md)<`C`> ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`DeployedContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md)<`C`>> --- # findDeployedContract > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / findDeployedContract # Function: findDeployedContract() Creates an instance of [FoundContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md) given the address of a deployed contract and an optional private state ID at which an existing private state is stored. When given, the current value at the private state ID is used as the `initialPrivateState` value in the `finalizedDeployTxData` property of the returned `FoundContract`. ## Param[​](#param "Direct link to Param") The providers used to manage transaction lifecycles. ## Param[​](#param-1 "Direct link to Param") Configuration. ## Throws[​](#throws "Direct link to Throws") Error Improper `privateStateId` and `initialPrivateState` configuration. ## Throws[​](#throws-1 "Direct link to Throws") Error No contract state could be found at `contractAddress`. ## Throws[​](#throws-2 "Direct link to Throws") TypeError Thrown if `contractAddress` is not correctly formatted as a contract address. ## Throws[​](#throws-3 "Direct link to Throws") ContractTypeError One or more circuits defined on `contract` are undefined on the contract state found at `contractAddress`, or have mis-matched verifier keys. ## Throws[​](#throws-4 "Direct link to Throws") IncompleteFindContractPrivateStateConfig If an `initialPrivateState` is given but no `privateStateId` is given to store it under. ## Call Signature[​](#call-signature "Direct link to Call Signature") > **findDeployedContract**<`C`>(`providers`, `options`): `Promise`<[`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> ### Parameters[​](#parameters "Direct link to Parameters") #### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`, `ProvableCircuitId`<`C`>, `unknown`> #### options[​](#options "Direct link to options") [`FindDeployedContractOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsBase.md)<`C`> ### Returns[​](#returns "Direct link to Returns") `Promise`<[`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **findDeployedContract**<`C`>(`providers`, `options`): `Promise`<[`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### providers[​](#providers-1 "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> #### options[​](#options-1 "Direct link to options") [`FindDeployedContractOptionsExistingPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsExistingPrivateState.md)<`C`> ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`>> ## Call Signature[​](#call-signature-2 "Direct link to Call Signature") > **findDeployedContract**<`C`>(`providers`, `options`): `Promise`<[`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`>> ### Type Parameters[​](#type-parameters-2 "Direct link to Type Parameters") #### C[​](#c-2 "Direct link to C") `C` *extends* `Any` ### Parameters[​](#parameters-2 "Direct link to Parameters") #### providers[​](#providers-2 "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> #### options[​](#options-2 "Direct link to options") [`FindDeployedContractOptionsStorePrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsStorePrivateState.md)<`C`> ### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`>> --- # getPublicStates > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / getPublicStates # Function: getPublicStates() > **getPublicStates**(`publicDataProvider`, `contractAddress`): `Promise`<[`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md)> Fetches only the public visible (Zswap and ledger) states of a contract. ## Parameters[​](#parameters "Direct link to Parameters") ### publicDataProvider[​](#publicdataprovider "Direct link to publicDataProvider") [`PublicDataProvider`](#) The provider to use to fetch the public states (Zswap and ledger) from the blockchain. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The ledger address of the contract. ## Returns[​](#returns "Direct link to Returns") `Promise`<[`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md)> --- # getStates > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / getStates # Function: getStates() > **getStates**<`PS`>(`publicDataProvider`, `privateStateProvider`, `contractAddress`, `privateStateId`): `Promise`<[`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PS`>> Retrieves the Zswap, ledger, and private states of the contract corresponding to the given identifier using the given providers. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` ## Parameters[​](#parameters "Direct link to Parameters") ### publicDataProvider[​](#publicdataprovider "Direct link to publicDataProvider") [`PublicDataProvider`](#) The provider to use to fetch the public states (Zswap and ledger) from the blockchain. ### privateStateProvider[​](#privatestateprovider "Direct link to privateStateProvider") [`PrivateStateProvider`](#)<`string`, `PS`> The provider to use to fetch the private state. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The ledger address of the contract. ### privateStateId[​](#privatestateid "Direct link to privateStateId") `string` The identifier for the private state of the contract. ## Returns[​](#returns "Direct link to Returns") `Promise`<[`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PS`>> --- # getUnshieldedBalances > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / getUnshieldedBalances # Function: getUnshieldedBalances() > **getUnshieldedBalances**(`publicDataProvider`, `contractAddress`): `Promise`<`UnshieldedBalances`> Fetches the unshielded balances associated with a specific contract address. ## Parameters[​](#parameters "Direct link to Parameters") ### publicDataProvider[​](#publicdataprovider "Direct link to publicDataProvider") [`PublicDataProvider`](#) The provider to use to fetch the unshielded balances from the blockchain. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The ledger address of the contract. ## Returns[​](#returns "Direct link to Returns") `Promise`<`UnshieldedBalances`> --- # submitCallTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitCallTx # Function: submitCallTx() Creates and submits a transaction for the invocation of a circuit on a given contract. ## Transaction Execution Phases[​](#transaction-execution-phases "Direct link to Transaction Execution Phases") Midnight transactions execute in two phases: 1. **Guaranteed phase**: If failure occurs, the transaction is NOT included in the blockchain 2. **Fallible phase**: If failure occurs, the transaction IS recorded on-chain as a partial success ## Failure Behavior[​](#failure-behavior "Direct link to Failure Behavior") **Guaranteed Phase Failure:** * Transaction is rejected and not included in the blockchain * `CallTxFailedError` is thrown with transaction data and circuit ID * Private state updates are NOT stored (state remains unchanged) * No on-chain record of the failed transaction **Fallible Phase Failure:** * Transaction is recorded on-chain with non-`SucceedEntirely` status * `CallTxFailedError` is thrown with transaction data and circuit ID * Private state updates are NOT stored (state remains unchanged) * Transaction appears in blockchain history as partial success ## Param[​](#param "Direct link to Param") The providers used to manage the invocation lifecycle. ## Param[​](#param-1 "Direct link to Param") Configuration. ## Param[​](#param-2 "Direct link to Param") Optional scoped transaction context to participate in an existing transaction scope. ## Throws[​](#throws "Direct link to Throws") When transaction fails in either guaranteed or fallible phase. The error contains the finalized transaction data and circuit ID for debugging. ## Call Signature[​](#call-signature "Direct link to Call Signature") > **submitCallTx**<`C`, `PCK`>(`providers`, `options`): `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> #### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters "Direct link to Parameters") #### providers[​](#providers "Direct link to providers") [`SubmitTxProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxProviders.md)<`C`, `PCK`> #### options[​](#options "Direct link to options") [`CallTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsBase.md)<`C`, `PCK`> ### Returns[​](#returns "Direct link to Returns") `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **submitCallTx**<`C`, `PCK`>(`providers`, `options`): `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` #### PCK[​](#pck-1 "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### providers[​](#providers-1 "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> #### options[​](#options-1 "Direct link to options") [`CallTxOptionsWithPrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsWithPrivateStateId.md)<`C`, `PCK`> ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> ## Call Signature[​](#call-signature-2 "Direct link to Call Signature") > **submitCallTx**<`C`, `PCK`>(`providers`, `options`, `transactionContext`): `Promise`<[`CallResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters-2 "Direct link to Type Parameters") #### C[​](#c-2 "Direct link to C") `C` *extends* `Any` #### PCK[​](#pck-2 "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters-2 "Direct link to Parameters") #### providers[​](#providers-2 "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> #### options[​](#options-2 "Direct link to options") [`CallTxOptionsWithPrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsWithPrivateStateId.md)<`C`, `PCK`> #### transactionContext[​](#transactioncontext "Direct link to transactionContext") [`TransactionContext`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/TransactionContext.md)<`C`, `PCK`> ### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`CallResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md)<`C`, `PCK`>> ## Call Signature[​](#call-signature-3 "Direct link to Call Signature") > **submitCallTx**<`C`, `PCK`>(`providers`, `options`, `transactionContext`): `Promise`<[`CallResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md)<`C`, `PCK`>> ### Type Parameters[​](#type-parameters-3 "Direct link to Type Parameters") #### C[​](#c-3 "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> #### PCK[​](#pck-3 "Direct link to PCK") `PCK` *extends* `string` ### Parameters[​](#parameters-3 "Direct link to Parameters") #### providers[​](#providers-3 "Direct link to providers") [`SubmitTxProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxProviders.md)<`C`, `PCK`> #### options[​](#options-3 "Direct link to options") [`CallTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsBase.md)<`C`, `PCK`> #### transactionContext[​](#transactioncontext-1 "Direct link to transactionContext") [`TransactionContext`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/TransactionContext.md)<`C`, `PCK`> ### Returns[​](#returns-3 "Direct link to Returns") `Promise`<[`CallResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md)<`C`, `PCK`>> --- # submitCallTxAsync > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitCallTxAsync # Function: submitCallTxAsync() > **submitCallTxAsync**<`C`, `PCK`>(`providers`, `options`): `Promise`<[`SubmittedCallTx`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmittedCallTx.md)<`C`, `PCK`>> Creates and submits a transaction for the invocation of a circuit on a given contract, returning immediately after submission without waiting for finalization. Unlike [submitCallTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitCallTx.md), this function does not wait for transaction finalization, check transaction status, or update private state. The caller must handle these steps manually. ## Transaction Execution Phases[​](#transaction-execution-phases "Direct link to Transaction Execution Phases") Midnight transactions execute in two phases: 1. **Guaranteed phase**: If failure occurs, the transaction is NOT included in the blockchain 2. **Fallible phase**: If failure occurs, the transaction IS recorded on-chain as a partial success ## Manual Post-Submission Steps[​](#manual-post-submission-steps "Direct link to Manual Post-Submission Steps") After calling this function, you must manually: 1. Watch for transaction finalization using `providers.publicDataProvider.watchForTxData(txId)` 2. Check transaction status (compare against `SucceedEntirely`) 3. Handle failures appropriately (throw errors, log, etc.) 4. Update private state if transaction succeeded and `privateStateId` was provided ## Failure Behavior (Manual Handling Required)[​](#failure-behavior-manual-handling-required "Direct link to Failure Behavior (Manual Handling Required)") **Guaranteed Phase Failure:** * Transaction is rejected and not included in the blockchain * `watchForTxData` may reject or return error status * You must NOT store private state updates **Fallible Phase Failure:** * Transaction is recorded on-chain with non-`SucceedEntirely` status * `watchForTxData` returns transaction data with failed status * You must NOT store private state updates * Transaction appears in blockchain history as partial success ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") `SubmitCallTxProviders`<`C`, `PCK`> The providers used to manage the invocation lifecycle. ### options[​](#options "Direct link to options") [`CallTxOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptions.md)<`C`, `PCK`> Configuration. ## Returns[​](#returns "Direct link to Returns") `Promise`<[`SubmittedCallTx`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmittedCallTx.md)<`C`, `PCK`>> A `Promise` that resolves with the transaction ID and call transaction data immediately after submission; or rejects with an error if the submission fails. ## Example[​](#example "Direct link to Example") ``` // 1. Submit const { txId, callTxData } = await submitCallTxAsync(providers, options); // 2. Watch (when ready) const finalizedData = await providers.publicDataProvider.watchForTxData(txId); // 3. Check status if (finalizedData.status !== SucceedEntirely) { throw new CallTxFailedError(finalizedData, options.circuitId); } // 4. Update private state manually if needed if (options.privateStateId) { await providers.privateStateProvider.set( privateStateId, callTxData.private.nextPrivateState ); } ``` --- # submitDeployTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitDeployTx # Function: submitDeployTx() Creates and submits a deploy transaction for the given contract. ## Transaction Execution Phases[​](#transaction-execution-phases "Direct link to Transaction Execution Phases") Midnight transactions execute in two phases: 1. **Guaranteed phase**: If failure occurs, the transaction is NOT included in the blockchain 2. **Fallible phase**: If failure occurs, the transaction IS recorded on-chain as a partial success ## Failure Behavior[​](#failure-behavior "Direct link to Failure Behavior") **Guaranteed Phase Failure:** * Transaction is rejected and not included in the blockchain * `DeployTxFailedError` is thrown with transaction data * Private state (if `privateStateId` provided) is NOT stored * Contract signing key is NOT stored in private state provider * Contract is NOT deployed **Fallible Phase Failure:** * Transaction is recorded on-chain with non-`SucceedEntirely` status * `DeployTxFailedError` is thrown with transaction data * Private state (if `privateStateId` provided) is NOT stored * Contract signing key is NOT stored in private state provider * Transaction appears in blockchain history as partial success * Contract may be partially deployed but not functional ## Param[​](#param "Direct link to Param") The providers used to manage the deploy lifecycle. ## Param[​](#param-1 "Direct link to Param") Configuration. ## Throws[​](#throws "Direct link to Throws") When transaction fails in either guaranteed or fallible phase. The error contains the finalized transaction data for debugging. ## Call Signature[​](#call-signature "Direct link to Call Signature") > **submitDeployTx**<`C`>(`providers`, `options`): `Promise`<[`FinalizedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md)<`C`>> ### Type Parameters[​](#type-parameters "Direct link to Type Parameters") #### C[​](#c "Direct link to C") `C` *extends* `Contract`<`undefined`, `Witnesses`<`undefined`>> ### Parameters[​](#parameters "Direct link to Parameters") #### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`, `ProvableCircuitId`<`C`>, `unknown`> #### options[​](#options "Direct link to options") [`DeployTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md)<`C`> ### Returns[​](#returns "Direct link to Returns") `Promise`<[`FinalizedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md)<`C`>> ## Call Signature[​](#call-signature-1 "Direct link to Call Signature") > **submitDeployTx**<`C`>(`providers`, `options`): `Promise`<[`FinalizedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md)<`C`>> ### Type Parameters[​](#type-parameters-1 "Direct link to Type Parameters") #### C[​](#c-1 "Direct link to C") `C` *extends* `Any` ### Parameters[​](#parameters-1 "Direct link to Parameters") #### providers[​](#providers-1 "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`> #### options[​](#options-1 "Direct link to options") [`DeployTxOptionsWithPrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateStateId.md)<`C`> ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<[`FinalizedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md)<`C`>> --- # submitInsertVerifierKeyTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitInsertVerifierKeyTx # Function: submitInsertVerifierKeyTx() > **submitInsertVerifierKeyTx**<`C`>(`providers`, `compiledContract`, `contractAddress`, `circuitId`, `newVk`): `Promise`<`FinalizedTxData`> Constructs and submits a transaction that adds a new verifier key to the blockchain for the given circuit ID at the given contract address. ## Transaction Execution Phases[​](#transaction-execution-phases "Direct link to Transaction Execution Phases") Midnight transactions execute in two phases: 1. **Guaranteed phase**: If failure occurs, the transaction is NOT included in the blockchain 2. **Fallible phase**: If failure occurs, the transaction IS recorded on-chain as a partial success ## Failure Behavior[​](#failure-behavior "Direct link to Failure Behavior") **Guaranteed Phase Failure:** * Transaction is rejected and not included in the blockchain * `InsertVerifierKeyTxFailedError` is thrown with transaction data * Verifier key is NOT added to the contract * No on-chain record of the failed transaction **Fallible Phase Failure:** * Transaction is recorded on-chain with non-`SucceedEntirely` status * `InsertVerifierKeyTxFailedError` is thrown with transaction data * Verifier key may be partially added but not usable * Transaction appears in blockchain history as partial success ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md) The providers to use to manage the transaction lifecycle. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> The compiled contract for which the maintenance authority should be updated. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The address of the contract containing the circuit for which the verifier key should be inserted. ### circuitId[​](#circuitid "Direct link to circuitId") `ProvableCircuitId`<`C`> The circuit for which the verifier key should be inserted. ### newVk[​](#newvk "Direct link to newVk") `VerifierKey` The new verifier key for the circuit. ## Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTxData`> A promise that resolves with the finalized transaction data, or rejects if an error occurs along the way. ## Throws[​](#throws "Direct link to Throws") When transaction fails in either guaranteed or fallible phase. The error contains the finalized transaction data for debugging. TODO: We'll likely want to modify ZKConfigProvider provider so that the verifier keys are automatically rotated in this function. This likely involves storing key versions along with keys in ZKConfigProvider. By default, artifacts for the latest version would be fetched to build transactions. --- # submitRemoveVerifierKeyTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitRemoveVerifierKeyTx # Function: submitRemoveVerifierKeyTx() > **submitRemoveVerifierKeyTx**<`C`>(`providers`, `compiledContract`, `contractAddress`, `circuitId`): `Promise`<`FinalizedTxData`> Constructs and submits a transaction that removes the current verifier key stored on the blockchain for the given circuit ID at the given contract address. ## Transaction Execution Phases[​](#transaction-execution-phases "Direct link to Transaction Execution Phases") Midnight transactions execute in two phases: 1. **Guaranteed phase**: If failure occurs, the transaction is NOT included in the blockchain 2. **Fallible phase**: If failure occurs, the transaction IS recorded on-chain as a partial success ## Failure Behavior[​](#failure-behavior "Direct link to Failure Behavior") **Guaranteed Phase Failure:** * Transaction is rejected and not included in the blockchain * `RemoveVerifierKeyTxFailedError` is thrown with transaction data * Verifier key remains on the contract (unchanged) * No on-chain record of the failed transaction **Fallible Phase Failure:** * Transaction is recorded on-chain with non-`SucceedEntirely` status * `RemoveVerifierKeyTxFailedError` is thrown with transaction data * Verifier key may be partially removed but contract state is inconsistent * Transaction appears in blockchain history as partial success ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md) The providers to use to manage the transaction lifecycle. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> The compiled contract for which the maintenance authority should be updated. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The address of the contract containing the circuit for which the verifier key should be removed. ### circuitId[​](#circuitid "Direct link to circuitId") `ProvableCircuitId`<`C`> The circuit for which the verifier key should be removed. ## Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTxData`> A promise that resolves with the finalized transaction data, or rejects if an error occurs along the way. ## Throws[​](#throws "Direct link to Throws") When transaction fails in either guaranteed or fallible phase. The error contains the finalized transaction data for debugging. TODO: We'll likely want to modify ZKConfigProvider provider so that the verifier keys are automatically rotated in this function. This likely involves storing key versions along with keys in ZKConfigProvider. By default, artifacts for the latest version would be fetched to build transactions. --- # submitReplaceAuthorityTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitReplaceAuthorityTx # Function: submitReplaceAuthorityTx() > **submitReplaceAuthorityTx**<`C`>(`providers`, `compiledContract`, `contractAddress`): (`newAuthority`) => `Promise`<`FinalizedTxData`> Constructs and submits a transaction that replaces the maintenance authority stored on the blockchain for this contract. After the transaction is finalized, the current signing key stored in the given private state provider is overwritten with the given new authority key. ## Transaction Execution Phases[​](#transaction-execution-phases "Direct link to Transaction Execution Phases") Midnight transactions execute in two phases: 1. **Guaranteed phase**: If failure occurs, the transaction is NOT included in the blockchain 2. **Fallible phase**: If failure occurs, the transaction IS recorded on-chain as a partial success ## Failure Behavior[​](#failure-behavior "Direct link to Failure Behavior") **Guaranteed Phase Failure:** * Transaction is rejected and not included in the blockchain * `ReplaceMaintenanceAuthorityTxFailedError` is thrown with transaction data * Signing key in private state provider is NOT updated (remains as current authority) * Contract authority on-chain remains unchanged **Fallible Phase Failure:** * Transaction is recorded on-chain with non-`SucceedEntirely` status * `ReplaceMaintenanceAuthorityTxFailedError` is thrown with transaction data * Signing key in private state provider is NOT updated (remains as current authority) * Contract authority on-chain may be partially updated but inconsistent * Transaction appears in blockchain history as partial success ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md) The providers to use to manage the transaction lifecycle. ### compiledContract[​](#compiledcontract "Direct link to compiledContract") `CompiledContract`<`C`, `any`> The compiled contract for which the maintenance authority should be updated. ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The address of the contract for which the maintenance authority should be updated. TODO: There are at least three options we should support in the future: 1. Replace authority and maintain key (current). 2. Replace authority and do not maintain key. 3. Add additional authorities and maintain original key. ## Returns[​](#returns "Direct link to Returns") > (`newAuthority`): `Promise`<`FinalizedTxData`> ### Parameters[​](#parameters-1 "Direct link to Parameters") #### newAuthority[​](#newauthority "Direct link to newAuthority") `string` The signing key of the new contract maintenance authority. ### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`FinalizedTxData`> A promise that resolves with the finalized transaction data, or rejects if an error occurs along the way. ### Throws[​](#throws "Direct link to Throws") When transaction fails in either guaranteed or fallible phase. The error contains the finalized transaction data for debugging. --- # submitTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitTx # Function: submitTx() > **submitTx**<`C`, `PCK`>(`providers`, `options`): `Promise`<`FinalizedTxData`> Proves, balances, and submits an unproven deployment or call transaction using the given providers, according to the given options. ## Blocking Behavior[​](#blocking-behavior "Direct link to Blocking Behavior") This method **waits indefinitely** for the transaction to appear on the blockchain via `providers.publicDataProvider.watchForTxData(txId)`. It will not return until: * The transaction is successfully included in the blockchain, OR * An error occurs during proving, balancing, or submission ## Conditions When Transaction May Not Appear[​](#conditions-when-transaction-may-not-appear "Direct link to Conditions When Transaction May Not Appear") A submitted transaction may fail to appear on-chain if: * Transaction is invalid in ways not detected during local validation * Network issues prevent propagation to validators * Transaction is rejected by validator consensus * Insufficient fees or resources * Contract state has changed making the transaction invalid ## Implications of Aborting This Method[​](#implications-of-aborting-this-method "Direct link to Implications of Aborting This Method") If the application terminates this method before it returns: * Transaction may still be pending/processing on-chain * **Private state updates are NOT stored** (even if transaction later succeeds on-chain) * **Signing keys are NOT updated** (for deploy/replace authority transactions) * Application state will be out of sync with blockchain state * Manual recovery may be required to reconcile state **Recommendation**: Use [submitTxAsync](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTxAsync.md) for non-blocking submission with manual finalization handling and timeout control. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`SubmitTxProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxProviders.md)<`C`, `PCK`> The providers used to manage the transaction lifecycle. ### options[​](#options "Direct link to options") [`SubmitTxOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxOptions.md)<`PCK`> Configuration. ## Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTxData`> A promise that resolves with the finalized transaction data for the invocation, or rejects if an error occurs along the way. --- # submitTxAsync > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / submitTxAsync # Function: submitTxAsync() > **submitTxAsync**<`C`, `PCK`>(`providers`, `options`): `Promise`<`string`> Proves, balances, and submits an unproven deployment or call transaction using the given providers, according to the given options. Unlike [submitTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTx.md), this function returns immediately after submission without waiting for finalization. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`SubmitTxProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxProviders.md)<`C`, `PCK`> The providers used to manage the transaction lifecycle. ### options[​](#options "Direct link to options") [`SubmitTxOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/SubmitTxOptions.md)<`PCK`> Configuration. ## Returns[​](#returns "Direct link to Returns") `Promise`<`string`> A promise that resolves with the transaction ID immediately after submission, or rejects if an error occurs during preparation or submission. To watch for finalization, use providers.publicDataProvider.watchForTxData(txId). --- # verifierKeysEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / verifierKeysEqual # Function: verifierKeysEqual() > **verifierKeysEqual**(`a`, `b`): `boolean` Checks that two verifier keys are equal. Does initial length check match for efficiency. ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") `Uint8Array` First verifier key. ### b[​](#b "Direct link to b") `Uint8Array` Second verifier key. ## Returns[​](#returns "Direct link to Returns") `boolean` --- # verifyContractState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / verifyContractState # Function: verifyContractState() > **verifyContractState**(`verifierKeys`, `contractState`): `void` Checks that the given `contractState` contains the given `verifierKeys`. ## Parameters[​](#parameters "Direct link to Parameters") ### verifierKeys[​](#verifierkeys "Direct link to verifierKeys") \[`string`, `VerifierKey`]\[] The verifier keys the client has for the deployed contract we're checking. ### contractState[​](#contractstate "Direct link to contractState") `ContractState` The (typically already deployed) contract state containing verifier keys. ## Returns[​](#returns "Direct link to Returns") `void` ## Throws[​](#throws "Direct link to Throws") ContractTypeError When one or more of the local and deployed verifier keys do not match. --- # ContractMaintenanceTxInterface > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractMaintenanceTxInterface # Interface: ContractMaintenanceTxInterface Interface for creating maintenance transactions for a contract that was deployed. ## Methods[​](#methods "Direct link to Methods") ### replaceAuthority()[​](#replaceauthority "Direct link to replaceAuthority()") > **replaceAuthority**(`newAuthority`): `Promise`<`FinalizedTxData`> Constructs and submits a transaction that replaces the maintenance authority stored on the blockchain for this contract. #### Parameters[​](#parameters "Direct link to Parameters") ##### newAuthority[​](#newauthority "Direct link to newAuthority") `string` The new contract maintenance authority for this contract. #### Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTxData`> --- # TransactionContext > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / TransactionContext # Interface: TransactionContext\ Encapsulates the context for managing a scoped contract transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> = `Contract.ProvableCircuitId`<`C`> ## Properties[​](#properties "Direct link to Properties") ### \[CacheStates][​](#cachestates "Direct link to \[CacheStates]") > `readonly` **\[CacheStates]**: (`states`, `identity`) => `void` #### Parameters[​](#parameters "Direct link to Parameters") ##### states[​](#states "Direct link to states") [`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) | [`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PrivateState`<`C`>> ##### identity[​](#identity "Direct link to identity") `CachedStateIdentity` #### Returns[​](#returns "Direct link to Returns") `void` *** ### \[GetCurrentStatesForIdentity][​](#getcurrentstatesforidentity "Direct link to \[GetCurrentStatesForIdentity]") > `readonly` **\[GetCurrentStatesForIdentity]**: (`identity`) => [`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) | [`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PrivateState`<`C`>> | `undefined` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### identity[​](#identity-1 "Direct link to identity") `CachedStateIdentity` #### Returns[​](#returns-1 "Direct link to Returns") [`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) | [`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PrivateState`<`C`>> | `undefined` *** ### \[MergeUnsubmittedCallTxData][​](#mergeunsubmittedcalltxdata "Direct link to \[MergeUnsubmittedCallTxData]") > `readonly` **\[MergeUnsubmittedCallTxData]**: (`circuitId`, `callData`, `privateStateId?`) => `void` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### circuitId[​](#circuitid "Direct link to circuitId") `PCK` ##### callData[​](#calldata "Direct link to callData") [`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`> ##### privateStateId?[​](#privatestateid "Direct link to privateStateId?") `string` #### Returns[​](#returns-2 "Direct link to Returns") `void` *** ### \[Submit][​](#submit "Direct link to \[Submit]") > `readonly` **\[Submit]**: () => `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> *** ### \[TypeId][​](#typeid "Direct link to \[TypeId]") > `readonly` **\[TypeId]**: *typeof* `TypeId` ## Methods[​](#methods "Direct link to Methods") ### getAdditionalMappings()[​](#getadditionalmappings "Direct link to getAdditionalMappings()") > **getAdditionalMappings**(): `ReadonlyMap`<`string`, `string`> | `undefined` Gets the additional scoped CoinPublicKey to EncPublicKey mappings. #### Returns[​](#returns-4 "Direct link to Returns") `ReadonlyMap`<`string`, `string`> | `undefined` A `ReadonlyMap ` instance, or `undefined` if no additional mappings were specified for the current transaction context. *** ### getCurrentStates()[​](#getcurrentstates "Direct link to getCurrentStates()") > **getCurrentStates**(): [`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) | [`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PrivateState`<`C`>> | `undefined` Gets the current cached contract states within the transaction context. #### Returns[​](#returns-5 "Direct link to Returns") [`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) | [`ContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md)<`PrivateState`<`C`>> | `undefined` A cached [ContractStates](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractStates.md) instance, or `undefined` if circuit calls are yet to be made. #### Remarks[​](#remarks "Direct link to Remarks") The returned states represent the unsubmitted *running* state of the contract within the transaction context, reflecting any unsubmitted circuit calls made to the contract during the scope of the transaction. *** ### getLastUnsubmittedCallTxDataToTransact()[​](#getlastunsubmittedcalltxdatatotransact "Direct link to getLastUnsubmittedCallTxDataToTransact()") > **getLastUnsubmittedCallTxDataToTransact**(): \[[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>, `string`?] | `undefined` Gets the last unsubmitted call transaction data. #### Returns[​](#returns-6 "Direct link to Returns") \[[`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`>, `string`?] | `undefined` A tuple containing an [UnsubmittedCallTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md) instance, and an optional private state ID, or `undefined` if circuit calls are yet to be made. --- # CallOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallOptions # Type Alias: CallOptions\ > **CallOptions**<`C`, `PCK`> = [`CallOptionsWithProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithProviderDataDependencies.md)<`C`, `PCK`> | [`CallOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithPrivateState.md)<`C`, `PCK`> Call options for a given contract and circuit. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CallOptionsBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallOptionsBase # Type Alias: CallOptionsBase\ > **CallOptionsBase**<`C`, `PCK`> = `object` Describes the target of a circuit invocation. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> ## Properties[​](#properties "Direct link to Properties") ### additionalCoinEncPublicKeyMappings?[​](#additionalcoinencpublickeymappings "Direct link to additionalCoinEncPublicKeyMappings?") > `readonly` `optional` **additionalCoinEncPublicKeyMappings?**: `ReadonlyMap`<`CoinPublicKey`, `EncPublicKey`> An optional mapping of CoinPublicKey to EncPublicKey that can be used to resolve encryption keys for coins created during circuit execution. *** ### circuitId[​](#circuitid "Direct link to circuitId") > `readonly` **circuitId**: `PCK` The identifier of the circuit to call. *** ### compiledContract[​](#compiledcontract "Direct link to compiledContract") > `readonly` **compiledContract**: `CompiledContract.CompiledContract`<`C`, `any`> The contract defining the circuit to call. *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") > `readonly` **contractAddress**: [`ContractAddress`](#) The address of the contract being executed. --- # CallOptionsProviderDataDependencies > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallOptionsProviderDataDependencies # Type Alias: CallOptionsProviderDataDependencies > **CallOptionsProviderDataDependencies** = `object` Data retrieved via providers that should be included in the call options. ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") > `readonly` **coinPublicKey**: `CoinPublicKey` The Zswap public key of the current user. *** ### initialContractState[​](#initialcontractstate "Direct link to initialContractState") > `readonly` **initialContractState**: `ContractState` The initial public state of the contract to run the circuit against. *** ### initialZswapChainState[​](#initialzswapchainstate "Direct link to initialZswapChainState") > `readonly` **initialZswapChainState**: `ZswapChainState` The initial public Zswap state of the contract to run the circuit against. *** ### ledgerParameters[​](#ledgerparameters "Direct link to ledgerParameters") > `readonly` **ledgerParameters**: `LedgerParameters` The ledger parameters to use when executing the circuit. --- # CallOptionsWithArguments > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallOptionsWithArguments # Type Alias: CallOptionsWithArguments\ > **CallOptionsWithArguments**<`C`, `PCK`> = `Contract.CircuitParameters`<`C`, `PCK`> *extends* \[] ? [`CallOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsBase.md)<`C`, `PCK`> : [`CallOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsBase.md)<`C`, `PCK`> & `object` Conditional type that optionally adds the inferred circuit argument types to the options for a circuit call. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CallOptionsWithPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallOptionsWithPrivateState # Type Alias: CallOptionsWithPrivateState\ > **CallOptionsWithPrivateState**<`C`, `PCK`> = [`CallOptionsWithProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithProviderDataDependencies.md)<`C`, `PCK`> & `object` Call options for contracts with private state. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") > `readonly` **initialPrivateState**: `Contract.PrivateState`<`C`> The private state to run the circuit against. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CallOptionsWithProviderDataDependencies > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallOptionsWithProviderDataDependencies # Type Alias: CallOptionsWithProviderDataDependencies\ > **CallOptionsWithProviderDataDependencies**<`C`, `PCK`> = [`CallOptionsWithArguments`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithArguments.md)<`C`, `PCK`> & [`CallOptionsProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsProviderDataDependencies.md) Call options with circuit arguments and data ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CallResult > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallResult # Type Alias: CallResult\ > **CallResult**<`C`, `PCK`> = `object` Contains all information resulting from circuit execution. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> ## Properties[​](#properties "Direct link to Properties") ### private[​](#private "Direct link to private") > `readonly` **private**: [`CallResultPrivate`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResultPrivate.md)<`C`, `PCK`> The private/sensitive data produced by the circuit execution. *** ### public[​](#public "Direct link to public") > `readonly` **public**: [`CallResultPublic`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResultPublic.md) The public/non-sensitive data produced by the circuit execution. --- # CallResultPrivate > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallResultPrivate # Type Alias: CallResultPrivate\ > **CallResultPrivate**<`C`, `PCK`> = `object` The private (sensitive) portions of the call result. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> ## Properties[​](#properties "Direct link to Properties") ### input[​](#input "Direct link to input") > `readonly` **input**: `AlignedValue` ZK representation of the circuit arguments. *** ### nextPrivateState[​](#nextprivatestate "Direct link to nextPrivateState") > `readonly` **nextPrivateState**: `Contract.PrivateState`<`C`> The private state resulting from executing the circuit. *** ### nextZswapLocalState[​](#nextzswaplocalstate "Direct link to nextZswapLocalState") > `readonly` **nextZswapLocalState**: `ZswapLocalState` The Zswap local state resulting from executing the circuit. *** ### output[​](#output "Direct link to output") > `readonly` **output**: `AlignedValue` ZK representation of the circuit result. *** ### privateTranscriptOutputs[​](#privatetranscriptoutputs "Direct link to privateTranscriptOutputs") > `readonly` **privateTranscriptOutputs**: `AlignedValue`\[] ZK representation of the circuit witness call results. *** ### result[​](#result "Direct link to result") > `readonly` **result**: `Contract.CircuitReturnType`<`C`, `PCK`> The JS representation of the input to the circuit. --- # CallResultPublic > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallResultPublic # Type Alias: CallResultPublic > **CallResultPublic** = `object` The public portions of the call result. ## Properties[​](#properties "Direct link to Properties") ### nextContractState[​](#nextcontractstate "Direct link to nextContractState") > `readonly` **nextContractState**: `StateValue` The public state resulting from executing the circuit. *** ### partitionedTranscript[​](#partitionedtranscript "Direct link to partitionedTranscript") > `readonly` **partitionedTranscript**: `PartitionedTranscript` A [publicTranscript](#publictranscript) partitioned into guaranteed and fallible sections. The guaranteed section of a public transcript must succeed for the corresponding transaction to be considered valid. The fallible section of a public transcript can fail without invalidating the transaction, as long as the guaranteed section succeeds. *** ### publicTranscript[​](#publictranscript "Direct link to publicTranscript") > `readonly` **publicTranscript**: `Op`<`AlignedValue`>\[] The public transcript resulting from executing the circuit. --- # CallTxOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallTxOptions # Type Alias: CallTxOptions\ > **CallTxOptions**<`C`, `PCK`> = [`CallTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsBase.md)<`C`, `PCK`> | [`CallTxOptionsWithPrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsWithPrivateStateId.md)<`C`, `PCK`> Call transaction configuration. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CallTxOptionsBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallTxOptionsBase # Type Alias: CallTxOptionsBase\ > **CallTxOptionsBase**<`C`, `PCK`> = [`CallOptionsWithArguments`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithArguments.md)<`C`, `PCK`> Base type for configuration for a call transaction; identical to [CallOptionsWithArguments](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallOptionsWithArguments.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CallTxOptionsWithPrivateStateId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CallTxOptionsWithPrivateStateId # Type Alias: CallTxOptionsWithPrivateStateId\ > **CallTxOptionsWithPrivateStateId**<`C`, `PCK`> = [`CallTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallTxOptionsBase.md)<`C`, `PCK`> & `object` Call transaction options with the private state ID to use to store the new private state resulting from the circuit call. Since a private state should already be stored at the given private state ID, we don't need an 'initialPrivateState' like in [DeployTxOptionsWithPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md). ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### privateStateId[​](#privatestateid "Direct link to privateStateId") > `readonly` **privateStateId**: `PrivateStateId` The identifier for the private state of the contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # CircuitCallTxInterface > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CircuitCallTxInterface # Type Alias: CircuitCallTxInterface\ > **CircuitCallTxInterface**<`C`> = `{ [PCK in Contract.ProvableCircuitId]: { (args: CircuitParameters): Promise>; (txCtx: TransactionContext, args: CircuitParameters): Promise> } }` A type that lifts each circuit defined in a contract to a function that builds and submits a call transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # CircuitMaintenanceTxInterface > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CircuitMaintenanceTxInterface # Type Alias: CircuitMaintenanceTxInterface > **CircuitMaintenanceTxInterface** = `object` An interface for creating maintenance transactions for a specific circuit defined in a given contract. ## Methods[​](#methods "Direct link to Methods") ### insertVerifierKey()[​](#insertverifierkey "Direct link to insertVerifierKey()") > **insertVerifierKey**(`newVk`): `Promise`<`FinalizedTxData`> Constructs and submits a transaction that adds a new verifier key to the blockchain for this circuit at this contract's address. #### Parameters[​](#parameters "Direct link to Parameters") ##### newVk[​](#newvk "Direct link to newVk") `VerifierKey` The new verifier key to add for this circuit. #### Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTxData`> *** ### removeVerifierKey()[​](#removeverifierkey "Direct link to removeVerifierKey()") > **removeVerifierKey**(): `Promise`<`FinalizedTxData`> Constructs and submits a transaction that removes the current verifier key stored on the blockchain for this circuit at this contract's address. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`FinalizedTxData`> --- # CircuitMaintenanceTxInterfaces > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / CircuitMaintenanceTxInterfaces # Type Alias: CircuitMaintenanceTxInterfaces\ > **CircuitMaintenanceTxInterfaces**<`C`> = `Record`<`Contract.ProvableCircuitId`<`C`>, [`CircuitMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md)> A set of maintenance transaction creation interfaces, one for each circuit defined in a given contract, keyed by the circuit name. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # ContractConstructorOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorOptions # Type Alias: ContractConstructorOptions\ > **ContractConstructorOptions**<`C`> = [`ContractConstructorOptionsWithProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithProviderDataDependencies.md)<`C`> | [`ContractConstructorOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithPrivateState.md)<`C`> Conditional type that optionally adds the inferred circuit argument types to the target of a circuit invocation. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # ContractConstructorOptionsBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorOptionsBase # Type Alias: ContractConstructorOptionsBase\ > **ContractConstructorOptionsBase**<`C`> = `object` Describes the target of a circuit invocation. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ## Properties[​](#properties "Direct link to Properties") ### compiledContract[​](#compiledcontract "Direct link to compiledContract") > `readonly` **compiledContract**: `CompiledContract.CompiledContract`<`C`, `any`> The compiled contract defining the circuit to call. --- # ContractConstructorOptionsProviderDataDependencies > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorOptionsProviderDataDependencies # Type Alias: ContractConstructorOptionsProviderDataDependencies > **ContractConstructorOptionsProviderDataDependencies** = `object` Data retrieved via providers that should be included in the constructor call options. ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") > `readonly` **coinPublicKey**: `CoinPublicKey` The current user's ZSwap public key. --- # ContractConstructorOptionsWithArguments > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorOptionsWithArguments # Type Alias: ContractConstructorOptionsWithArguments\ > **ContractConstructorOptionsWithArguments**<`C`> = `Contract.InitializeParameters`<`C`> *extends* \[] ? [`ContractConstructorOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsBase.md)<`C`> : [`ContractConstructorOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsBase.md)<`C`> & `object` Conditional type that optionally adds the inferred contract constructor argument types to the constructor options. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # ContractConstructorOptionsWithPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorOptionsWithPrivateState # Type Alias: ContractConstructorOptionsWithPrivateState\ > **ContractConstructorOptionsWithPrivateState**<`C`> = [`ContractConstructorOptionsWithProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithProviderDataDependencies.md)<`C`> & `object` Conditional type that optionally adds the inferred circuit argument types to the target of a circuit invocation. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") > `readonly` **initialPrivateState**: `Contract.PrivateState`<`C`> The private state to run the circuit against. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # ContractConstructorOptionsWithProviderDataDependencies > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorOptionsWithProviderDataDependencies # Type Alias: ContractConstructorOptionsWithProviderDataDependencies\ > **ContractConstructorOptionsWithProviderDataDependencies**<`C`> = [`ContractConstructorOptionsWithArguments`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithArguments.md)<`C`> & [`ContractConstructorOptionsProviderDataDependencies`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsProviderDataDependencies.md) Contract constructor options including arguments and provider data. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # ContractConstructorResult > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractConstructorResult # Type Alias: ContractConstructorResult\ > **ContractConstructorResult**<`C`> = `object` The updated states resulting from executing a contract constructor. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ## Properties[​](#properties "Direct link to Properties") ### nextContractState[​](#nextcontractstate "Direct link to nextContractState") > `readonly` **nextContractState**: `ContractState` The public state resulting from executing the contract constructor. *** ### nextPrivateState[​](#nextprivatestate "Direct link to nextPrivateState") > `readonly` **nextPrivateState**: `Contract.PrivateState`<`C`> The private state resulting from executing the contract constructor. *** ### nextZswapLocalState[​](#nextzswaplocalstate "Direct link to nextZswapLocalState") > `readonly` **nextZswapLocalState**: `ZswapLocalState` The Zswap local state resulting from executing the contract constructor. --- # ContractProviders > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractProviders # Type Alias: ContractProviders\ > **ContractProviders**<`C`, `PCK`, `PS`> = `MidnightProviders`<`PCK`, `PrivateStateId`, `PS`> Convenience type for representing the set of providers necessary to use a given contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` = `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> = `Contract.ProvableCircuitId`<`C`> ### PS[​](#ps "Direct link to PS") `PS` = `Contract.PrivateState`<`C`> --- # ContractStates > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ContractStates # Type Alias: ContractStates\ > **ContractStates**<`PS`> = [`PublicContractStates`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/PublicContractStates.md) & `object` Object containing the publicly visible states of a contract and the private state of a contract. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### privateState[​](#privatestate "Direct link to privateState") > `readonly` **privateState**: `PS` The private state of a contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PS[​](#ps "Direct link to PS") `PS` --- # DeployContractOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployContractOptions # Type Alias: DeployContractOptions\ > **DeployContractOptions**<`C`> = [`DeployContractOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsBase.md)<`C`> | [`DeployContractOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsWithPrivateState.md)<`C`> Configuration for [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployContractOptionsBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployContractOptionsBase # Type Alias: DeployContractOptionsBase\ > **DeployContractOptionsBase**<`C`> = [`ContractConstructorOptionsWithArguments`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithArguments.md)<`C`> & `object` Base type for configuration for [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md); identical to [ContractConstructorOptionsWithArguments](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithArguments.md) except the `signingKey` is now optional, since [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md) will generate a fresh signing key in the event that `signingKey` is undefined. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### additionalCoinEncPublicKeyMappings?[​](#additionalcoinencpublickeymappings "Direct link to additionalCoinEncPublicKeyMappings?") > `readonly` `optional` **additionalCoinEncPublicKeyMappings?**: `ReadonlyMap`<`CoinPublicKey`, `EncPublicKey`> An optional mapping of CoinPublicKey to EncPublicKey that can be used to resolve encryption keys for coins created in the contract constructor. This is useful in cases where the constructor creates outputs to addresses that don't belong to the current user. ### signingKey?[​](#signingkey "Direct link to signingKey?") > `readonly` `optional` **signingKey?**: `SigningKey` The signing key to add as the to-be-deployed contract's maintenance authority. If undefined, a new signing key is sampled and used as the CMA then stored in the private state provider under the newly deployed contract's address. Otherwise, the passed signing key is added as the CMA. The second case is useful when you want to use the same CMA for two different contracts. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployContractOptionsWithPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployContractOptionsWithPrivateState # Type Alias: DeployContractOptionsWithPrivateState\ > **DeployContractOptionsWithPrivateState**<`C`> = [`DeployContractOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptionsBase.md)<`C`> & `object` [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md) base options with information needed to store private states; only used if the contract being deployed has a private state. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") > `readonly` **initialPrivateState**: `Contract.PrivateState`<`C`> The private state to run the circuit against. ### privateStateId[​](#privatestateid "Direct link to privateStateId") > `readonly` **privateStateId**: `PrivateStateId` An identifier for the private state of the contract being found. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployedContract > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployedContract # Type Alias: DeployedContract\ > **DeployedContract**<`C`> = [`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md)<`C`> & `object` Interface for a contract that has been deployed to the blockchain. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### deployTxData[​](#deploytxdata "Direct link to deployTxData") > `readonly` **deployTxData**: [`FinalizedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxData.md)<`C`> Data resulting from the deployment transaction that created this contract. The information in a deployTxData contains additional private information that does not exist in [FoundContract.deployTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md#deploytxdata) because certain private data is only available to the deployer of a contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployTxOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployTxOptions # Type Alias: DeployTxOptions\ > **DeployTxOptions**<`C`> = [`DeployTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md)<`C`> | [`DeployTxOptionsWithPrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateStateId.md)<`C`> Configuration for creating deploy transactions. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployTxOptionsBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployTxOptionsBase # Type Alias: DeployTxOptionsBase\ > **DeployTxOptionsBase**<`C`> = [`ContractConstructorOptionsWithArguments`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractConstructorOptionsWithArguments.md)<`C`> & `object` Base type for deploy transaction configuration. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### additionalCoinEncPublicKeyMappings?[​](#additionalcoinencpublickeymappings "Direct link to additionalCoinEncPublicKeyMappings?") > `readonly` `optional` **additionalCoinEncPublicKeyMappings?**: `ReadonlyMap`<`CoinPublicKey`, `EncPublicKey`> An optional mapping of CoinPublicKey to EncPublicKey that can be used to resolve encryption keys for coins created in the contract constructor. This is useful in cases where the constructor creates outputs to addresses that don't belong to the current user. ### signingKey[​](#signingkey "Direct link to signingKey") > `readonly` **signingKey**: `SigningKey` The signing key to add as the to-be-deployed contract's maintenance authority. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployTxOptionsWithPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployTxOptionsWithPrivateState # Type Alias: DeployTxOptionsWithPrivateState\ > **DeployTxOptionsWithPrivateState**<`C`> = [`DeployTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md)<`C`> & `object` Configuration for creating deploy transactions for contracts with private state. This configuration used as a base type for the [DeployTxOptionsWithPrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateStateId.md) configuration. It is also used directly as parameter to [createUnprovenDeployTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/createUnprovenDeployTx.md) which doesn't need to save private state (and therefore doesn't need a private state ID) but does need to supply an initial private state to run the contract constructor against. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") > `readonly` **initialPrivateState**: `Contract.PrivateState`<`C`> The private state to run the contract constructor against. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # DeployTxOptionsWithPrivateStateId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / DeployTxOptionsWithPrivateStateId # Type Alias: DeployTxOptionsWithPrivateStateId\ > **DeployTxOptionsWithPrivateStateId**<`C`> = [`DeployTxOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md)<`C`> & `object` Configuration for creating deploy transactions for contracts with private state. This configuration is used when a deployment transaction is created and an initial private state needs to be stored, as is the case in [submitDeployTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitDeployTx.md). ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### privateStateId[​](#privatestateid "Direct link to privateStateId") > `readonly` **privateStateId**: `PrivateStateId` The identifier for the private state of the contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # FinalizedCallTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FinalizedCallTxData # Type Alias: FinalizedCallTxData\ > **FinalizedCallTxData**<`C`, `PCK`> = [`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`> & `object` Data for a submitted, finalized call transaction. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### public[​](#public "Direct link to public") > `readonly` **public**: `FinalizedTxData` Public data relevant to this call transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # FinalizedDeployTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FinalizedDeployTxData # Type Alias: FinalizedDeployTxData\ > **FinalizedDeployTxData**<`C`> = [`UnsubmittedDeployTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxData.md)<`C`> & `object` Data for a finalized deploy transaction submitted in this process. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### public[​](#public "Direct link to public") > `readonly` **public**: `FinalizedTxData` The data of this transaction that is visible on the blockchain. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # FinalizedDeployTxDataBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FinalizedDeployTxDataBase # Type Alias: FinalizedDeployTxDataBase\ > **FinalizedDeployTxDataBase**<`C`> = [`UnsubmittedDeployTxDataBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxDataBase.md)<`C`> & `object` Data for a finalized deploy transaction submitted in this process. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### public[​](#public "Direct link to public") > `readonly` **public**: `FinalizedTxData` The data of this transaction that is visible on the blockchain. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # FindDeployedContractOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FindDeployedContractOptions # Type Alias: FindDeployedContractOptions\ > **FindDeployedContractOptions**<`C`> = [`FindDeployedContractOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsBase.md)<`C`> | [`FindDeployedContractOptionsExistingPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsExistingPrivateState.md)<`C`> | [`FindDeployedContractOptionsStorePrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsStorePrivateState.md)<`C`> Configuration for [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # FindDeployedContractOptionsBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FindDeployedContractOptionsBase # Type Alias: FindDeployedContractOptionsBase\ > **FindDeployedContractOptionsBase**<`C`> = `object` Base type for the configuration options for [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ## Properties[​](#properties "Direct link to Properties") ### compiledContract[​](#compiledcontract "Direct link to compiledContract") > `readonly` **compiledContract**: `CompiledContract.CompiledContract`<`C`, `any`> The compiled contract to use to execute circuits. *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") > `readonly` **contractAddress**: [`ContractAddress`](#) The address of a previously deployed contract. *** ### signingKey?[​](#signingkey "Direct link to signingKey?") > `readonly` `optional` **signingKey?**: `SigningKey` The signing key to use to perform contract maintenance updates. If defined, the given signing key is stored for this contract address. This is useful when someone has already added the given signing key to the contract maintenance authority. If undefined, and there is an existing signing key for the contract address locally, the existing signing key is kept. This is useful when the contract was deployed locally. If undefined, and there is not an existing signing key for the contract address locally, a fresh signing key is generated and stored for the contract address locally. This is useful when you want to give a signing key to someone else to add you as a maintenance authority. --- # FindDeployedContractOptionsExistingPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FindDeployedContractOptionsExistingPrivateState # Type Alias: FindDeployedContractOptionsExistingPrivateState\ > **FindDeployedContractOptionsExistingPrivateState**<`C`> = [`FindDeployedContractOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsBase.md)<`C`> & `object` [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md) base configuration that includes an initial private state to store and the private state ID at which to store it. Only used if the intention is to overwrite the private state currently stored at the given private state ID. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### privateStateId[​](#privatestateid "Direct link to privateStateId") > `readonly` **privateStateId**: `PrivateStateId` An identifier for the private state of the contract being found. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # FindDeployedContractOptionsStorePrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FindDeployedContractOptionsStorePrivateState # Type Alias: FindDeployedContractOptionsStorePrivateState\ > **FindDeployedContractOptionsStorePrivateState**<`C`> = [`FindDeployedContractOptionsExistingPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FindDeployedContractOptionsExistingPrivateState.md)<`C`> & `object` [findDeployedContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/findDeployedContract.md) configuration that includes an initial private state to store and the private state ID at which to store it. Only used if the intention is to overwrite the private state currently stored at the given private state ID. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") > `readonly` **initialPrivateState**: `Contract.PrivateState`<`C`> For types of contract that make no use of private state and or witnesses that operate upon it, this property may be `undefined`. Otherwise, the value provided via this property should be same initial state that was used when calling [deployContract](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/deployContract.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # FoundContract > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / FoundContract # Type Alias: FoundContract\ > **FoundContract**<`C`> = `object` Base type for a deployed contract that has been found on the blockchain. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ## Properties[​](#properties "Direct link to Properties") ### callTx[​](#calltx "Direct link to callTx") > `readonly` **callTx**: [`CircuitCallTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitCallTxInterface.md)<`C`> Interface for creating call transactions for a contract. *** ### circuitMaintenanceTx[​](#circuitmaintenancetx "Direct link to circuitMaintenanceTx") > `readonly` **circuitMaintenanceTx**: [`CircuitMaintenanceTxInterfaces`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterfaces.md)<`C`> An interface for creating maintenance transactions for circuits defined in the contract that was deployed. *** ### contractMaintenanceTx[​](#contractmaintenancetx "Direct link to contractMaintenanceTx") > `readonly` **contractMaintenanceTx**: [`ContractMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/interfaces/ContractMaintenanceTxInterface.md) Interface for creating maintenance transactions for the contract that was deployed. *** ### deployTxData[​](#deploytxdata "Direct link to deployTxData") > `readonly` **deployTxData**: [`FinalizedDeployTxDataBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedDeployTxDataBase.md)<`C`> Data for the finalized deploy transaction corresponding to this contract. --- # PublicContractStates > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / PublicContractStates # Type Alias: PublicContractStates > **PublicContractStates** = `object` Object containing the publicly visible states of a contract. ## Properties[​](#properties "Direct link to Properties") ### contractState[​](#contractstate "Direct link to contractState") > `readonly` **contractState**: `ContractState` The (public) ledger state of a contract. *** ### ledgerParameters[​](#ledgerparameters "Direct link to ledgerParameters") > `readonly` **ledgerParameters**: `LedgerParameters` The ledger parameters in effect on the block associated with the contract state. *** ### zswapChainState[​](#zswapchainstate "Direct link to zswapChainState") > `readonly` **zswapChainState**: `ZswapChainState` The (public) Zswap chain state of a contract. --- # ScopedTransactionOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / ScopedTransactionOptions # Type Alias: ScopedTransactionOptions > **ScopedTransactionOptions** = `object` Options for use when creating scoped transactions. ## Properties[​](#properties "Direct link to Properties") ### additionalCoinEncPublicKeyMappings?[​](#additionalcoinencpublickeymappings "Direct link to additionalCoinEncPublicKeyMappings?") > `readonly` `optional` **additionalCoinEncPublicKeyMappings?**: `ReadonlyMap`<`CoinPublicKey`, `EncPublicKey`> An optional mapping of CoinPublicKey to EncPublicKey that can be used to resolve encryption keys for coins created during circuit execution. *** ### scopeName?[​](#scopename "Direct link to scopeName?") > `readonly` `optional` **scopeName?**: `string` An optional name for the transaction scope. --- # SubmittedCallTx > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / SubmittedCallTx # Type Alias: SubmittedCallTx\ > **SubmittedCallTx**<`C`, `PCK`> = `object` Data returned from an asynchronous call transaction submission. Contains the transaction ID and call transaction data without waiting for finalization. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> ## Properties[​](#properties "Direct link to Properties") ### callTxData[​](#calltxdata "Direct link to callTxData") > `readonly` **callTxData**: [`UnsubmittedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedCallTxData.md)<`C`, `PCK`> The unproven call transaction data including private state. *** ### txId[​](#txid "Direct link to txId") > `readonly` **txId**: `string` The transaction ID returned from submission. --- # SubmitTxOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / SubmitTxOptions # Type Alias: SubmitTxOptions\ > **SubmitTxOptions**<`PCK`> = `object` Configuration for [submitTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTx.md). ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `AnyProvableCircuitId` ## Properties[​](#properties "Direct link to Properties") ### circuitId?[​](#circuitid "Direct link to circuitId?") > `readonly` `optional` **circuitId?**: `PCK` | `PCK`\[] A circuit identifier to use to fetch the ZK artifacts needed to prove the transaction. Only defined if a call transaction is being submitted. #### Remarks[​](#remarks "Direct link to Remarks") Where a transaction involves multiple circuits (e.g., when circuit calls are scoped to a transaction context), this may be an array of circuit IDs. *** ### unprovenTx[​](#unproventx "Direct link to unprovenTx") > `readonly` **unprovenTx**: `UnprovenTransaction` The transaction to prove, balance, and submit. --- # SubmitTxProviders > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / SubmitTxProviders # Type Alias: SubmitTxProviders\ > **SubmitTxProviders**<`C`, `PCK`> = `Omit`<[`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`, `PCK`>, `"privateStateProvider"`> Providers required to submit an unproven deployment transaction. Since [submitTx](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/functions/submitTx.md) doesn't manipulate private state, the private state provider can be omitted. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # UnprovenCallTxProvidersBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnprovenCallTxProvidersBase # Type Alias: UnprovenCallTxProvidersBase > **UnprovenCallTxProvidersBase** = `Pick`<[`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md), `"zkConfigProvider"` | `"publicDataProvider"` | `"walletProvider"`> The minimum set of providers needed to create a call transaction, the ZK artifact provider and a wallet. By defining this type, users can choose to omit a private state provider if they're creating a call transaction for a contract with no private state. --- # UnprovenCallTxProvidersWithPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnprovenCallTxProvidersWithPrivateState # Type Alias: UnprovenCallTxProvidersWithPrivateState\ > **UnprovenCallTxProvidersWithPrivateState**<`C`> = [`UnprovenCallTxProvidersBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersBase.md) & `Pick`<[`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`>, `"privateStateProvider"`> Same providers as [UnprovenCallTxProvidersBase](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnprovenCallTxProvidersBase.md) with an additional private state provider to store the new private state resulting from the circuit call - only used when creating a call transaction for a contract with a private state. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # UnprovenDeployTxOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnprovenDeployTxOptions # Type Alias: UnprovenDeployTxOptions\ > **UnprovenDeployTxOptions**<`C`> = [`DeployTxOptionsBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsBase.md)<`C`> | [`DeployTxOptionsWithPrivateState`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployTxOptionsWithPrivateState.md)<`C`> Configuration for creating unproven deploy transactions. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # UnprovenDeployTxProviders > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnprovenDeployTxProviders # Type Alias: UnprovenDeployTxProviders\ > **UnprovenDeployTxProviders**<`C`> = `Pick`<[`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`>, `"zkConfigProvider"` | `"walletProvider"`> Providers needed to create an unproven deployment transactions, just the ZK artifact provider and a wallet. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # UnsubmittedCallTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnsubmittedCallTxData # Type Alias: UnsubmittedCallTxData\ > **UnsubmittedCallTxData**<`C`, `PCK`> = [`CallResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CallResult.md)<`C`, `PCK`> & `object` Data for an unsubmitted call transaction. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### private[​](#private "Direct link to private") > `readonly` **private**: [`UnsubmittedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedTxData.md) Private data relevant to this call transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> --- # UnsubmittedDeployTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnsubmittedDeployTxData # Type Alias: UnsubmittedDeployTxData\ > **UnsubmittedDeployTxData**<`C`> = [`UnsubmittedDeployTxDataBase`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxDataBase.md)<`C`> & `object` Data for an unsubmitted deployment transaction. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### private[​](#private "Direct link to private") > `readonly` **private**: [`UnsubmittedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedTxData.md) & `object` The data of this transaction that is only visible on the user device. #### Type Declaration[​](#type-declaration-1 "Direct link to Type Declaration") ##### initialZswapState[​](#initialzswapstate "Direct link to initialZswapState") > `readonly` **initialZswapState**: `ZswapLocalState` The Zswap state produced as a result of running the contract constructor. Useful for when inputs or outputs are created in the contract constructor. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` --- # UnsubmittedDeployTxDataBase > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnsubmittedDeployTxDataBase # Type Alias: UnsubmittedDeployTxDataBase\ > **UnsubmittedDeployTxDataBase**<`C`> = `object` Base type for data relevant to an unsubmitted deployment transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ## Properties[​](#properties "Direct link to Properties") ### private[​](#private "Direct link to private") > `readonly` **private**: [`UnsubmittedDeployTxPrivateData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxPrivateData.md)<`C`> The private data (data that will not be revealed upon tx submission) relevant to the deployment transaction. *** ### public[​](#public "Direct link to public") > `readonly` **public**: [`UnsubmittedDeployTxPublicData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/UnsubmittedDeployTxPublicData.md) The public data (data that will be revealed upon tx submission) relevant to the deployment transaction. --- # UnsubmittedDeployTxPrivateData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnsubmittedDeployTxPrivateData # Type Alias: UnsubmittedDeployTxPrivateData\ > **UnsubmittedDeployTxPrivateData**<`C`> = `object` Base type for private data relevant to an unsubmitted deployment transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ## Properties[​](#properties "Direct link to Properties") ### initialPrivateState[​](#initialprivatestate "Direct link to initialPrivateState") > `readonly` **initialPrivateState**: `Contract.PrivateState`<`C`> The initial private state of the contract deployed to the blockchain. This value is persisted if the transaction succeeds. *** ### signingKey[​](#signingkey "Direct link to signingKey") > `readonly` **signingKey**: `SigningKey` The signing key that was added as the deployed contract's maintenance authority. --- # UnsubmittedDeployTxPublicData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnsubmittedDeployTxPublicData # Type Alias: UnsubmittedDeployTxPublicData > **UnsubmittedDeployTxPublicData** = `object` Base type for public data relevant to an unsubmitted deployment transaction. ## Properties[​](#properties "Direct link to Properties") ### contractAddress[​](#contractaddress "Direct link to contractAddress") > `readonly` **contractAddress**: [`ContractAddress`](#) The ledger address of the contract that was deployed. *** ### initialContractState[​](#initialcontractstate "Direct link to initialContractState") > `readonly` **initialContractState**: `ContractState` The initial public state of the contract deployed to the blockchain. --- # UnsubmittedTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / UnsubmittedTxData # Type Alias: UnsubmittedTxData > **UnsubmittedTxData** = `object` Data relevant to any unsubmitted transaction. ## Properties[​](#properties "Direct link to Properties") ### newCoins[​](#newcoins "Direct link to newCoins") > `readonly` **newCoins**: `ShieldedCoinInfo`\[] New coins created during the construction of the transaction. *** ### unprovenTx[​](#unproventx "Direct link to unprovenTx") > `readonly` **unprovenTx**: `UnprovenTransaction` The unproven ledger transaction produced. --- # withContractScopedTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-contracts](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) / withContractScopedTransaction # Variable: withContractScopedTransaction > `const` **withContractScopedTransaction**: <`C`, `PCK`>(`providers`, `fn`, `options?`) => `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> Executes a function within the context of a contract-scoped transaction. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Contract.Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `Contract.ProvableCircuitId`<`C`> = `Contract.ProvableCircuitId`<`C`> ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") [`ContractProviders`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ContractProviders.md)<`C`, `PCK`> The contract providers to use within the transaction. ### fn[​](#fn "Direct link to fn") (`txCtx`) => `Promise`<`void`> The function to execute within the transaction context. ### options?[​](#options "Direct link to options?") [`ScopedTransactionOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/ScopedTransactionOptions.md) Optional transaction scope options. ## Returns[​](#returns "Direct link to Returns") `Promise`<[`FinalizedCallTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FinalizedCallTxData.md)<`C`, `PCK`>> A `Promise` that resolves with the finalized transaction data of the single transaction created for all circuit calls made within `fn`. ## Remarks[​](#remarks "Direct link to Remarks") Where `fn` make circuit calls, these are batched together and submitted as a single transaction when the function completes successfully. If `fn` throws an error, any unsubmitted circuit calls are discarded. --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-dapp-connector-proof-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-dapp-connector-proof-provider # @midnight-ntwrk/midnight-js-dapp-connector-proof-provider ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [DAppConnectorProvingAPI](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/type-aliases/DAppConnectorProvingAPI.md) ## Functions[​](#functions "Direct link to Functions") * [dappConnectorProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/functions/dappConnectorProofProvider.md) * [dappConnectorProvingProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/functions/dappConnectorProvingProvider.md) --- # dappConnectorProofProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-dapp-connector-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider.md) / dappConnectorProofProvider # Function: dappConnectorProofProvider() > **dappConnectorProofProvider**<`K`>(`api`, `zkConfigProvider`, `costModel`): `Promise`<[`ProofProvider`](#)> Creates a [ProofProvider](#) that delegates proving to a DApp Connector wallet. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` Union of circuit identifier strings defined by the contract. ## Parameters[​](#parameters "Direct link to Parameters") ### api[​](#api "Direct link to api") [`DAppConnectorProvingAPI`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/type-aliases/DAppConnectorProvingAPI.md) DApp Connector wallet API exposing `getProvingProvider`. ### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`K`> Provider that supplies ZK configuration artifacts and key material. ### costModel[​](#costmodel "Direct link to costModel") `CostModel` Cost model applied during transaction proving. ## Returns[​](#returns "Direct link to Returns") `Promise`<[`ProofProvider`](#)> A [ProofProvider](#) whose `proveTx` method delegates to the wallet. ## Remarks[​](#remarks "Direct link to Remarks") Combines a wallet-backed [dappConnectorProvingProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/functions/dappConnectorProvingProvider.md) with the given `costModel` to produce a transaction-level proof provider. The wallet's proving provider is obtained once during initialization and reused for all subsequent `proveTx` calls. --- # dappConnectorProvingProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-dapp-connector-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider.md) / dappConnectorProvingProvider # Function: dappConnectorProvingProvider() > **dappConnectorProvingProvider**<`K`>(`api`, `zkConfigProvider`): `Promise`<`ProvingProvider`> Obtains a ProvingProvider from the DApp Connector wallet. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` Union of circuit identifier strings defined by the contract. ## Parameters[​](#parameters "Direct link to Parameters") ### api[​](#api "Direct link to api") [`DAppConnectorProvingAPI`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider/type-aliases/DAppConnectorProvingAPI.md) DApp Connector wallet API exposing `getProvingProvider`. ### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`K`> Provider that supplies ZK configuration artifacts and key material. ## Returns[​](#returns "Direct link to Returns") `Promise`<`ProvingProvider`> A ProvingProvider backed by the wallet. ## Remarks[​](#remarks "Direct link to Remarks") Extracts key material from the given `zkConfigProvider` and passes it to the wallet's `getProvingProvider` method. Use this when you need direct, circuit-level access to the wallet's proving capabilities without cost model integration. --- # DAppConnectorProvingAPI > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-dapp-connector-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider.md) / DAppConnectorProvingAPI # Type Alias: DAppConnectorProvingAPI > **DAppConnectorProvingAPI** = `Pick`<`WalletConnectedAPI`, `"getProvingProvider"`> Minimal interface required from the DApp Connector wallet. ## Remarks[​](#remarks "Direct link to Remarks") Picks only WalletConnectedAPI.getProvingProvider | getProvingProvider from the full wallet API, allowing loose coupling between the framework and the wallet implementation. --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-fetch-zk-config-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-fetch-zk-config-provider # @midnight-ntwrk/midnight-js-fetch-zk-config-provider ## Classes[​](#classes "Direct link to Classes") * [FetchZkConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-fetch-zk-config-provider/classes/FetchZkConfigProvider.md) --- # FetchZkConfigProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-fetch-zk-config-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-fetch-zk-config-provider.md) / FetchZkConfigProvider # Class: FetchZkConfigProvider\ Retrieves ZK artifacts from a remote source. ## Extends[​](#extends "Direct link to Extends") * [`ZKConfigProvider`](#)<`K`> ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new FetchZkConfigProvider**<`K`>(`baseURL`, `fetchFunc?`): `FetchZkConfigProvider`<`K`> #### Parameters[​](#parameters "Direct link to Parameters") ##### baseURL[​](#baseurl "Direct link to baseURL") `string` The endpoint to query for ZK artifacts. ##### fetchFunc?[​](#fetchfunc "Direct link to fetchFunc?") {(`input`, `init?`): `Promise`<`Response`>; (`input`, `init?`): `Promise`<`Response`>; } The function to use to execute queries. #### Returns[​](#returns "Direct link to Returns") `FetchZkConfigProvider`<`K`> #### Overrides[​](#overrides "Direct link to Overrides") `ZKConfigProvider.constructor` ## Properties[​](#properties "Direct link to Properties") ### baseURL[​](#baseurl-1 "Direct link to baseURL") > `readonly` **baseURL**: `string` The endpoint to query for ZK artifacts. ## Methods[​](#methods "Direct link to Methods") ### asKeyMaterialProvider()[​](#askeymaterialprovider "Direct link to asKeyMaterialProvider()") > **asKeyMaterialProvider**(): `KeyMaterialProvider` #### Returns[​](#returns-1 "Direct link to Returns") `KeyMaterialProvider` #### Inherited from[​](#inherited-from "Direct link to Inherited from") `ZKConfigProvider.asKeyMaterialProvider` *** ### get()[​](#get "Direct link to get()") > **get**(`circuitId`): `Promise`<`ZKConfig`<`K`>> Retrieves all zero-knowledge artifacts produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### circuitId[​](#circuitid "Direct link to circuitId") `K` The circuit ID of the artifacts to retrieve. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`ZKConfig`<`K`>> #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") `ZKConfigProvider.get` *** ### getProverKey()[​](#getproverkey "Direct link to getProverKey()") > **getProverKey**(`circuitId`): `Promise`<`ProverKey`> Retrieves the prover key produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### circuitId[​](#circuitid-1 "Direct link to circuitId") `K` The circuit ID of the prover key to retrieve. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`ProverKey`> #### Overrides[​](#overrides-1 "Direct link to Overrides") `ZKConfigProvider.getProverKey` *** ### getVerifierKey()[​](#getverifierkey "Direct link to getVerifierKey()") > **getVerifierKey**(`circuitId`): `Promise`<`VerifierKey`> Retrieves the verifier key produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### circuitId[​](#circuitid-2 "Direct link to circuitId") `K` The circuit ID of the verifier key to retrieve. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`VerifierKey`> #### Overrides[​](#overrides-2 "Direct link to Overrides") `ZKConfigProvider.getVerifierKey` *** ### getVerifierKeys()[​](#getverifierkeys "Direct link to getVerifierKeys()") > **getVerifierKeys**(`circuitIds`): `Promise`<\[`K`, `VerifierKey`]\[]> Retrieves the verifier keys produced by `compactc` compiler for the given circuits. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### circuitIds[​](#circuitids "Direct link to circuitIds") `K`\[] The circuit IDs of the verifier keys to retrieve. #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<\[`K`, `VerifierKey`]\[]> #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") `ZKConfigProvider.getVerifierKeys` *** ### getZKIR()[​](#getzkir "Direct link to getZKIR()") > **getZKIR**(`circuitId`): `Promise`<`ZKIR`> Retrieves the zero-knowledge intermediate representation produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### circuitId[​](#circuitid-3 "Direct link to circuitId") `K` The circuit ID of the ZKIR to retrieve. #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<`ZKIR`> #### Overrides[​](#overrides-3 "Direct link to Overrides") `ZKConfigProvider.getZKIR` --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-http-client-proof-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-http-client-proof-provider # @midnight-ntwrk/midnight-js-http-client-proof-provider ## Interfaces[​](#interfaces "Direct link to Interfaces") * [ProvingProviderConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/interfaces/ProvingProviderConfig.md) ## Variables[​](#variables "Direct link to Variables") * [DEFAULT\_CONFIG](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/variables/DEFAULT_CONFIG.md) * [DEFAULT\_TIMEOUT](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/variables/DEFAULT_TIMEOUT.md) ## Functions[​](#functions "Direct link to Functions") * [httpClientProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/functions/httpClientProofProvider.md) * [httpClientProvingProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/functions/httpClientProvingProvider.md) --- # httpClientProofProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-http-client-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md) / httpClientProofProvider # Function: httpClientProofProvider() > **httpClientProofProvider**<`K`>(`url`, `zkConfigProvider`, `config?`): [`ProofProvider`](#) Creates a high-level [ProofProvider](#) that implements transaction-level proving using the low-level circuit-by-circuit [ProvingProvider](#) as its foundation. This adapter bridges the gap between: * High-level ProofProvider interface (works with complete transactions) * Low-level ProvingProvider interface (works with individual circuits) ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### url[​](#url "Direct link to url") `string` The URL of the proof server ### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`K`> Provider for zero-knowledge configuration artifacts ### config?[​](#config "Direct link to config?") [`ProvingProviderConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/interfaces/ProvingProviderConfig.md) Optional configuration for the underlying ProvingProvider ## Returns[​](#returns "Direct link to Returns") [`ProofProvider`](#) A ProofProvider instance that uses ProvingProvider internally ## Remarks[​](#remarks "Direct link to Remarks") **Architecture:** ``` ProofProvider (Transaction-level) ↓ (adapter) ProvingProvider (Circuit-level) ↓ (HTTP client) Proof Server (/check, /prove endpoints) ``` **Note:** The /prove-tx endpoint is NOT used. All proving is done through individual circuit operations using /check and /prove endpoints. --- # httpClientProvingProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-http-client-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md) / httpClientProvingProvider # Function: httpClientProvingProvider() > **httpClientProvingProvider**<`K`>(`url`, `zkConfigProvider`, `config?`): [`ProvingProvider`](#) ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### url[​](#url "Direct link to url") `string` ### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](#)<`K`> ### config?[​](#config "Direct link to config?") [`ProvingProviderConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider/interfaces/ProvingProviderConfig.md) ## Returns[​](#returns "Direct link to Returns") [`ProvingProvider`](#) --- # ProvingProviderConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-http-client-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md) / ProvingProviderConfig # Interface: ProvingProviderConfig ## Properties[​](#properties "Direct link to Properties") ### headers?[​](#headers "Direct link to headers?") > `readonly` `optional` **headers?**: `Record`<`string`, `string`> *** ### timeout?[​](#timeout "Direct link to timeout?") > `readonly` `optional` **timeout?**: `number` --- # DEFAULT\_CONFIG > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-http-client-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md) / DEFAULT\_CONFIG # Variable: DEFAULT\_CONFIG > `const` **DEFAULT\_CONFIG**: `object` HTTP Client Proof Provider This package provides two levels of abstraction for interacting with a Midnight proof server: ## High-Level: Transaction Proving (ProofProvider)[​](#high-level-transaction-proving-proofprovider "Direct link to High-Level: Transaction Proving (ProofProvider)") Use `httpClientProofProvider` for most use cases. It handles complete transactions by using the low-level ProvingProvider internally. ``` import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; const proofProvider = httpClientProofProvider( 'http://localhost:6300', zkConfigProvider ); const provenTx = await proofProvider.proveTx(unprovenTx, { zkConfig }); ``` ## Low-Level: Circuit Proving (ProvingProvider)[​](#low-level-circuit-proving-provingprovider "Direct link to Low-Level: Circuit Proving (ProvingProvider)") Use `httpClientProvingProvider` for advanced scenarios where you need fine-grained control over individual circuit proving operations. ``` import { httpClientProvingProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; const provingProvider = httpClientProvingProvider( 'http://localhost:6300', zkConfigProvider ); const checkResult = await provingProvider.check(serializedPreimage, circuitId); const proof = await provingProvider.prove(serializedPreimage, circuitId); ``` ## Architecture[​](#architecture "Direct link to Architecture") ``` ProofProvider (httpClientProofProvider) ↓ uses ProvingProvider (httpClientProvingProvider) ↓ calls Proof Server (/check, /prove) ``` ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### timeout[​](#timeout "Direct link to timeout") > **timeout**: `number` = `300000` ### zkConfig[​](#zkconfig "Direct link to zkConfig") > **zkConfig**: `undefined` = `undefined` --- # DEFAULT\_TIMEOUT > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-http-client-proof-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md) / DEFAULT\_TIMEOUT # Variable: DEFAULT\_TIMEOUT > `const` **DEFAULT\_TIMEOUT**: `300000` = `300000` --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-indexer-public-data-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-indexer-public-data-provider # @midnight-ntwrk/midnight-js-indexer-public-data-provider ## Classes[​](#classes "Direct link to Classes") * [IndexerFormattedError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/classes/IndexerFormattedError.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [IndexerUtxo](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/type-aliases/IndexerUtxo.md) ## Functions[​](#functions "Direct link to Functions") * [indexerPublicDataProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/indexerPublicDataProvider.md) * [isRegularTransaction](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/isRegularTransaction.md) * [toSegmentStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toSegmentStatus.md) * [toSegmentStatusMap](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toSegmentStatusMap.md) * [toTxStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toTxStatus.md) * [toUnshieldedBalances](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toUnshieldedBalances.md) * [toUnshieldedUtxos](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/functions/toUnshieldedUtxos.md) --- # IndexerFormattedError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / IndexerFormattedError # Class: IndexerFormattedError An error describing the causes of error that occurred during server-side execution of a query against the Indexer. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new IndexerFormattedError**(`cause`): `IndexerFormattedError` #### Parameters[​](#parameters "Direct link to Parameters") ##### cause[​](#cause "Direct link to cause") readonly `GraphQLFormattedError`\[] An array of GraphQL errors that occurred during the server-side execution. #### Returns[​](#returns "Direct link to Returns") `IndexerFormattedError` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` ## Properties[​](#properties "Direct link to Properties") ### cause[​](#cause-1 "Direct link to cause") > `readonly` **cause**: readonly `GraphQLFormattedError`\[] An array of GraphQL errors that occurred during the server-side execution. #### Inherited from[​](#inherited-from "Direct link to Inherited from") `Error.cause` --- # indexerPublicDataProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / indexerPublicDataProvider # Function: indexerPublicDataProvider() > **indexerPublicDataProvider**(`queryURL`, `subscriptionURL`, `webSocketImpl?`): [`PublicDataProvider`](#) Constructs a [PublicDataProvider](#) based on an [ApolloClient](#). ## Parameters[​](#parameters "Direct link to Parameters") ### queryURL[​](#queryurl "Direct link to queryURL") `string` The URL of a GraphQL server query endpoint. ### subscriptionURL[​](#subscriptionurl "Direct link to subscriptionURL") `string` The URL of a GraphQL server subscription (websocket) endpoint. ### webSocketImpl?[​](#websocketimpl "Direct link to webSocketImpl?") *typeof* `WebSocket` = `ws.WebSocket` An optional websocket implementation for the Apollo client to use. TODO: Re-examine caching when 'ContractCall' and 'ContractDeploy' have transaction identifiers included. ## Returns[​](#returns "Direct link to Returns") [`PublicDataProvider`](#) --- # isRegularTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / isRegularTransaction # Function: isRegularTransaction() > **isRegularTransaction**(`tx`): `tx is Transaction & { block: Block; contractActions: readonly ContractAction[]; dustLedgerEvents: readonly DustLedgerEvent[]; endIndex: number; fees: TransactionFees; hash: string; id: number; identifiers: readonly string[]; merkleTreeRoot: string; protocolVersion: number; raw: string; startIndex: number; transactionResult: TransactionResult; unshieldedCreatedOutputs: readonly UnshieldedUtxo[]; unshieldedSpentOutputs: readonly UnshieldedUtxo[]; zswapLedgerEvents: readonly ZswapLedgerEvent[] } & { hash: string; identifiers: string[] }` ## Parameters[​](#parameters "Direct link to Parameters") ### tx[​](#tx "Direct link to tx") `any` ## Returns[​](#returns "Direct link to Returns") `tx is Transaction & { block: Block; contractActions: readonly ContractAction[]; dustLedgerEvents: readonly DustLedgerEvent[]; endIndex: number; fees: TransactionFees; hash: string; id: number; identifiers: readonly string[]; merkleTreeRoot: string; protocolVersion: number; raw: string; startIndex: number; transactionResult: TransactionResult; unshieldedCreatedOutputs: readonly UnshieldedUtxo[]; unshieldedSpentOutputs: readonly UnshieldedUtxo[]; zswapLedgerEvents: readonly ZswapLedgerEvent[] } & { hash: string; identifiers: string[] }` --- # toSegmentStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / toSegmentStatus # Function: toSegmentStatus() > **toSegmentStatus**(`success`): `SegmentStatus` ## Parameters[​](#parameters "Direct link to Parameters") ### success[​](#success "Direct link to success") `boolean` ## Returns[​](#returns "Direct link to Returns") `SegmentStatus` --- # toSegmentStatusMap > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / toSegmentStatusMap # Function: toSegmentStatusMap() > **toSegmentStatusMap**(`transactionResult`): `Map`<`number`, `SegmentStatus`> | `undefined` ## Parameters[​](#parameters "Direct link to Parameters") ### transactionResult[​](#transactionresult "Direct link to transactionResult") `TransactionResult` ## Returns[​](#returns "Direct link to Returns") `Map`<`number`, `SegmentStatus`> | `undefined` --- # toTxStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / toTxStatus # Function: toTxStatus() > **toTxStatus**(`transactionResult`): `TxStatus` ## Parameters[​](#parameters "Direct link to Parameters") ### transactionResult[​](#transactionresult "Direct link to transactionResult") `TransactionResult` ## Returns[​](#returns "Direct link to Returns") `TxStatus` --- # toUnshieldedBalances > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / toUnshieldedBalances # Function: toUnshieldedBalances() > **toUnshieldedBalances**(`contractBalances`): `UnshieldedBalances` ## Parameters[​](#parameters "Direct link to Parameters") ### contractBalances[​](#contractbalances "Direct link to contractBalances") readonly `ContractBalance`\[] ## Returns[​](#returns "Direct link to Returns") `UnshieldedBalances` --- # toUnshieldedUtxos > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / toUnshieldedUtxos # Function: toUnshieldedUtxos() > **toUnshieldedUtxos**(`createdUtxo`, `spentUtxo`): `UnshieldedUtxos` ## Parameters[​](#parameters "Direct link to Parameters") ### createdUtxo[​](#createdutxo "Direct link to createdUtxo") readonly [`IndexerUtxo`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/type-aliases/IndexerUtxo.md)\[] ### spentUtxo[​](#spentutxo "Direct link to spentUtxo") readonly [`IndexerUtxo`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider/type-aliases/IndexerUtxo.md)\[] ## Returns[​](#returns "Direct link to Returns") `UnshieldedUtxos` --- # IndexerUtxo > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-indexer-public-data-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) / IndexerUtxo # Type Alias: IndexerUtxo > **IndexerUtxo** = `object` ## Properties[​](#properties "Direct link to Properties") ### intentHash[​](#intenthash "Direct link to intentHash") > **intentHash**: `string` *** ### owner[​](#owner "Direct link to owner") > **owner**: `string` *** ### tokenType[​](#tokentype "Direct link to tokenType") > **tokenType**: `string` *** ### value[​](#value "Direct link to value") > **value**: `string` --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-level-private-state-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-level-private-state-provider # @midnight-ntwrk/midnight-js-level-private-state-provider ## Classes[​](#classes "Direct link to Classes") * [StorageEncryption](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/classes/StorageEncryption.md) ## Interfaces[​](#interfaces "Direct link to Interfaces") * [CryptoBackend](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/CryptoBackend.md) * [LevelPrivateStateProviderConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/LevelPrivateStateProviderConfig.md) * [MigrationResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/MigrationResult.md) * [PasswordRotationOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/PasswordRotationOptions.md) * [PasswordRotationResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/PasswordRotationResult.md) * [StorageEncryptionOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/StorageEncryptionOptions.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [CryptoBackendType](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/CryptoBackendType.md) * [DatabaseLevel](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/DatabaseLevel.md) * [LevelFactory](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/LevelFactory.md) * [PrivateStoragePasswordProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/PrivateStoragePasswordProvider.md) ## Variables[​](#variables "Direct link to Variables") * [DEFAULT\_CONFIG](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/variables/DEFAULT_CONFIG.md) ## Functions[​](#functions "Direct link to Functions") * [decryptValue](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/functions/decryptValue.md) * [levelPrivateStateProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/functions/levelPrivateStateProvider.md) * [migrateToAccountScoped](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/functions/migrateToAccountScoped.md) --- # StorageEncryption > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / StorageEncryption # Class: StorageEncryption ## Methods[​](#methods "Direct link to Methods") ### decrypt()[​](#decrypt "Direct link to decrypt()") > **decrypt**(`encryptedData`): `Promise`<`string`> #### Parameters[​](#parameters "Direct link to Parameters") ##### encryptedData[​](#encrypteddata "Direct link to encryptedData") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<`string`> *** ### decryptWithPassword()[​](#decryptwithpassword "Direct link to decryptWithPassword()") > **decryptWithPassword**(`encryptedData`, `password`): `Promise`<`string`> #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### encryptedData[​](#encrypteddata-1 "Direct link to encryptedData") `string` ##### password[​](#password "Direct link to password") `string` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`string`> *** ### encrypt()[​](#encrypt "Direct link to encrypt()") > **encrypt**(`data`): `Promise`<`string`> #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### data[​](#data "Direct link to data") `string` #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`string`> *** ### getSalt()[​](#getsalt "Direct link to getSalt()") > **getSalt**(): `Buffer` #### Returns[​](#returns-3 "Direct link to Returns") `Buffer` *** ### verifyPassword()[​](#verifypassword "Direct link to verifyPassword()") > **verifyPassword**(`password`): `Promise`<`boolean`> #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### password[​](#password-1 "Direct link to password") `string` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`boolean`> *** ### create()[​](#create "Direct link to create()") > `static` **create**(`password`, `options?`): `Promise`<`StorageEncryption`> #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### password[​](#password-2 "Direct link to password") `string` ##### options?[​](#options "Direct link to options?") [`StorageEncryptionOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/StorageEncryptionOptions.md) #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<`StorageEncryption`> *** ### getVersion()[​](#getversion "Direct link to getVersion()") > `static` **getVersion**(`encryptedData`): `number` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### encryptedData[​](#encrypteddata-2 "Direct link to encryptedData") `string` #### Returns[​](#returns-6 "Direct link to Returns") `number` *** ### isEncrypted()[​](#isencrypted "Direct link to isEncrypted()") > `static` **isEncrypted**(`data`): `boolean` #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### data[​](#data-1 "Direct link to data") `string` #### Returns[​](#returns-7 "Direct link to Returns") `boolean` --- # decryptValue > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / decryptValue # Function: decryptValue() > **decryptValue**(`encryptedValue`, `encryption`, `password`): `Promise`<`string`> ## Parameters[​](#parameters "Direct link to Parameters") ### encryptedValue[​](#encryptedvalue "Direct link to encryptedValue") `string` ### encryption[​](#encryption "Direct link to encryption") [`StorageEncryption`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/classes/StorageEncryption.md) ### password[​](#password "Direct link to password") `string` ## Returns[​](#returns "Direct link to Returns") `Promise`<`string`> --- # levelPrivateStateProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / levelPrivateStateProvider # Function: levelPrivateStateProvider() > **levelPrivateStateProvider**<`PSI`, `PS`>(`config`): [`PrivateStateProvider`](#)<`PSI`, `PS`> & `object` Constructs an instance of [PrivateStateProvider](#) based on [Level](#) database. ⚠️ WARNING RISK: This provider lacks a recovery mechanism. Clearing browser cache or deleting local files permanently destroys the private state (contract state/keys). For assets with real-world value, this may result in irreversible financial loss. DO NOT use for production applications requiring data persistence. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PSI[​](#psi "Direct link to PSI") `PSI` *extends* `string` ### PS[​](#ps "Direct link to PS") `PS` = `any` ## Parameters[​](#parameters "Direct link to Parameters") ### config[​](#config "Direct link to config") `Partial`<[`LevelPrivateStateProviderConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/LevelPrivateStateProviderConfig.md)> & `Pick`<[`LevelPrivateStateProviderConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/LevelPrivateStateProviderConfig.md), `"privateStoragePasswordProvider"` | `"accountId"`> Database configuration options. ## Returns[​](#returns "Direct link to Returns") [`PrivateStateProvider`](#)<`PSI`, `PS`> & `object` --- # migrateToAccountScoped > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / migrateToAccountScoped # Function: migrateToAccountScoped() > **migrateToAccountScoped**(`config`): `Promise`<[`MigrationResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/MigrationResult.md)> Migrates existing unscoped private state and signing key data to account-scoped sublevels. This function copies data from the legacy unscoped locations to the new account-scoped locations. The original data is preserved (not deleted) to allow for safe rollback if needed. To remove old data after successful migration, manually clear the unscoped sublevels. Note: Running this function multiple times is safe but will re-copy all data, overwriting any changes made in the scoped location since the last migration. ## Parameters[​](#parameters "Direct link to Parameters") ### config[​](#config "Direct link to config") `Partial`<[`LevelPrivateStateProviderConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/LevelPrivateStateProviderConfig.md)> & `Pick`<[`LevelPrivateStateProviderConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/LevelPrivateStateProviderConfig.md), `"accountId"`> ## Returns[​](#returns "Direct link to Returns") `Promise`<[`MigrationResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/interfaces/MigrationResult.md)> --- # CryptoBackend > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / CryptoBackend # Interface: CryptoBackend ## Methods[​](#methods "Direct link to Methods") ### aesGcmDecrypt()[​](#aesgcmdecrypt "Direct link to aesGcmDecrypt()") > **aesGcmDecrypt**(`key`, `iv`, `ciphertext`, `authTag`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters "Direct link to Parameters") ##### key[​](#key "Direct link to key") `Uint8Array` ##### iv[​](#iv "Direct link to iv") `Uint8Array` ##### ciphertext[​](#ciphertext "Direct link to ciphertext") `Uint8Array` ##### authTag[​](#authtag "Direct link to authTag") `Uint8Array` #### Returns[​](#returns "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> *** ### aesGcmEncrypt()[​](#aesgcmencrypt "Direct link to aesGcmEncrypt()") > **aesGcmEncrypt**(`key`, `iv`, `plaintext`): `Promise`<{ `authTag`: `Uint8Array`; `ciphertext`: `Uint8Array`; }> #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### key[​](#key-1 "Direct link to key") `Uint8Array` ##### iv[​](#iv-1 "Direct link to iv") `Uint8Array` ##### plaintext[​](#plaintext "Direct link to plaintext") `Uint8Array` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<{ `authTag`: `Uint8Array`; `ciphertext`: `Uint8Array`; }> *** ### pbkdf2()[​](#pbkdf2 "Direct link to pbkdf2()") > **pbkdf2**(`password`, `salt`, `iterations`, `keyLength`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### password[​](#password "Direct link to password") `Uint8Array` ##### salt[​](#salt "Direct link to salt") `Uint8Array` ##### iterations[​](#iterations "Direct link to iterations") `number` ##### keyLength[​](#keylength "Direct link to keyLength") `number` #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> *** ### randomBytes()[​](#randombytes "Direct link to randomBytes()") > **randomBytes**(`length`): `Uint8Array` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### length[​](#length "Direct link to length") `number` #### Returns[​](#returns-3 "Direct link to Returns") `Uint8Array` *** ### sha256()[​](#sha256 "Direct link to sha256()") > **sha256**(`data`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### data[​](#data "Direct link to data") `Uint8Array` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> --- # LevelPrivateStateProviderConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / LevelPrivateStateProviderConfig # Interface: LevelPrivateStateProviderConfig Configuration properties for the LevelDB based private state provider. ## Properties[​](#properties "Direct link to Properties") ### accountId[​](#accountid "Direct link to accountId") > `readonly` **accountId**: `string` Account identifier used to scope storage. This ensures data isolation between different accounts/wallets using the same database. The accountId is hashed (SHA-256, first 32 chars) before being used in storage paths, so any unique identifier can be used (e.g., wallet address). #### Example[​](#example "Direct link to Example") ``` { accountId: walletAddress } ``` *** ### cryptoBackend?[​](#cryptobackend "Direct link to cryptoBackend?") > `readonly` `optional` **cryptoBackend?**: [`CryptoBackendType`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/CryptoBackendType.md) *** ### levelFactory?[​](#levelfactory "Direct link to levelFactory?") > `readonly` `optional` **levelFactory?**: [`LevelFactory`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/LevelFactory.md) *** ### midnightDbName[​](#midnightdbname "Direct link to midnightDbName") > `readonly` **midnightDbName**: `string` The name of the LevelDB database used to store all Midnight related data. *** ### privateStateStoreName[​](#privatestatestorename "Direct link to privateStateStoreName") > `readonly` **privateStateStoreName**: `string` The name of the object store containing private states. *** ### privateStoragePasswordProvider[​](#privatestoragepasswordprovider "Direct link to privateStoragePasswordProvider") > `readonly` **privateStoragePasswordProvider**: [`PrivateStoragePasswordProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/PrivateStoragePasswordProvider.md) Provider function that returns the password used for encrypting private state. The password must be at least 16 characters long. SECURITY: Use a strong, secret password. Never use public key material or other non-secret values as the password source. #### Example[​](#example-1 "Direct link to Example") ``` { privateStoragePasswordProvider: async () => await getSecretPassword() } ``` *** ### signingKeyStoreName[​](#signingkeystorename "Direct link to signingKeyStoreName") > `readonly` **signingKeyStoreName**: `string` The name of the object store containing signing keys. --- # MigrationResult > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / MigrationResult # Interface: MigrationResult ## Properties[​](#properties "Direct link to Properties") ### privateStatesMigrated[​](#privatestatesmigrated "Direct link to privateStatesMigrated") > `readonly` **privateStatesMigrated**: `number` *** ### signingKeysMigrated[​](#signingkeysmigrated "Direct link to signingKeysMigrated") > `readonly` **signingKeysMigrated**: `number` --- # PasswordRotationOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / PasswordRotationOptions # Interface: PasswordRotationOptions ## Properties[​](#properties "Direct link to Properties") ### maxEntries?[​](#maxentries "Direct link to maxEntries?") > `readonly` `optional` **maxEntries?**: `number` --- # PasswordRotationResult > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / PasswordRotationResult # Interface: PasswordRotationResult ## Properties[​](#properties "Direct link to Properties") ### entriesMigrated[​](#entriesmigrated "Direct link to entriesMigrated") > `readonly` **entriesMigrated**: `number` --- # StorageEncryptionOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / StorageEncryptionOptions # Interface: StorageEncryptionOptions ## Properties[​](#properties "Direct link to Properties") ### cryptoBackend?[​](#cryptobackend "Direct link to cryptoBackend?") > `optional` **cryptoBackend?**: [`CryptoBackendType`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/CryptoBackendType.md) *** ### existingSalt?[​](#existingsalt "Direct link to existingSalt?") > `optional` **existingSalt?**: `Uint8Array`<`ArrayBufferLike`> | `Buffer`<`ArrayBufferLike`> --- # CryptoBackendType > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / CryptoBackendType # Type Alias: CryptoBackendType > **CryptoBackendType** = `"webcrypto"` | `"noble"` --- # DatabaseLevel > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / DatabaseLevel # Type Alias: DatabaseLevel > **DatabaseLevel** = `AbstractLevel`<`string` | `Buffer` | `Uint8Array`, `string`, `string`> --- # LevelFactory > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / LevelFactory # Type Alias: LevelFactory > **LevelFactory** = (`dbName`) => [`DatabaseLevel`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/DatabaseLevel.md) ## Parameters[​](#parameters "Direct link to Parameters") ### dbName[​](#dbname "Direct link to dbName") `string` ## Returns[​](#returns "Direct link to Returns") [`DatabaseLevel`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider/type-aliases/DatabaseLevel.md) --- # PrivateStoragePasswordProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / PrivateStoragePasswordProvider # Type Alias: PrivateStoragePasswordProvider > **PrivateStoragePasswordProvider** = () => `string` | `Promise`<`string`> ## Returns[​](#returns "Direct link to Returns") `string` | `Promise`<`string`> --- # DEFAULT\_CONFIG > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-level-private-state-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) / DEFAULT\_CONFIG # Variable: DEFAULT\_CONFIG > `const` **DEFAULT\_CONFIG**: `object` The default configuration for the level database. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### midnightDbName[​](#midnightdbname "Direct link to midnightDbName") > **midnightDbName**: `string` = `MN_LDB_DEFAULT_DB_NAME` The name of the database. ### privateStateStoreName[​](#privatestatestorename "Direct link to privateStateStoreName") > **privateStateStoreName**: `string` = `MN_LDB_DEFAULT_PRIS_STORE_NAME` The name of the "level" on which to store private state. ### signingKeyStoreName[​](#signingkeystorename "Direct link to signingKeyStoreName") > **signingKeyStoreName**: `string` = `MN_LDB_DEFAULT_KEY_STORE_NAME` The name of the "level" on which to store signing keys. --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-logger-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-logger-provider # @midnight-ntwrk/midnight-js-logger-provider ## Classes[​](#classes "Direct link to Classes") * [LoggerProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-logger-provider/classes/LoggerProvider.md) --- # LoggerProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-logger-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-logger-provider.md) / LoggerProvider # Class: LoggerProvider Implementation of LoggerProvider that returns a [Logger](#) instance. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new LoggerProvider**(`logger`): `LoggerProvider` #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") [`Logger`](#) #### Returns[​](#returns "Direct link to Returns") `LoggerProvider` ## Properties[​](#properties "Direct link to Properties") ### debug[​](#debug "Direct link to debug") > **debug**: `LogFn` *** ### error[​](#error "Direct link to error") > **error**: `LogFn` *** ### fatal[​](#fatal "Direct link to fatal") > **fatal**: `LogFn` *** ### info[​](#info "Direct link to info") > **info**: `LogFn` *** ### trace[​](#trace "Direct link to trace") > **trace**: `LogFn` *** ### warn[​](#warn "Direct link to warn") > **warn**: `LogFn` ## Methods[​](#methods "Direct link to Methods") ### isLevelEnabled()[​](#islevelenabled "Direct link to isLevelEnabled()") > **isLevelEnabled**(`level`): `boolean` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### level[​](#level "Direct link to level") `LogLevel` #### Returns[​](#returns-1 "Direct link to Returns") `boolean` --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-network-id [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-network-id # @midnight-ntwrk/midnight-js-network-id ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [NetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/type-aliases/NetworkId.md) ## Functions[​](#functions "Direct link to Functions") * [getNetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/functions/getNetworkId.md) * [setNetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/functions/setNetworkId.md) --- # getNetworkId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-network-id](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id.md) / getNetworkId # Function: getNetworkId() > **getNetworkId**(): `string` Retrieves the currently set global network identifier. ## Returns[​](#returns "Direct link to Returns") `string` The currently set [NetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/type-aliases/NetworkId.md). ## Throws[​](#throws "Direct link to Throws") If [setNetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/functions/setNetworkId.md) has not been called. --- # setNetworkId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-network-id](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id.md) / setNetworkId # Function: setNetworkId() > **setNetworkId**(`id`): `void` Sets the global network identifier. ## Parameters[​](#parameters "Direct link to Parameters") ### id[​](#id "Direct link to id") `string` A valid [NetworkId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id/type-aliases/NetworkId.md) value. ## Returns[​](#returns "Direct link to Returns") `void` --- # NetworkId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-network-id](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id.md) / NetworkId # Type Alias: NetworkId > **NetworkId** = `string` A valid named Midnight network identifier. --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-node-zk-config-provider [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-node-zk-config-provider # @midnight-ntwrk/midnight-js-node-zk-config-provider ## Classes[​](#classes "Direct link to Classes") * [NodeZkConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-node-zk-config-provider/classes/NodeZkConfigProvider.md) --- # NodeZkConfigProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-node-zk-config-provider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-node-zk-config-provider.md) / NodeZkConfigProvider # Class: NodeZkConfigProvider\ Implementation of [ZKConfigProvider](#) that reads the keys and zkIR from the local filesystem. ## Extends[​](#extends "Direct link to Extends") * [`ZKConfigProvider`](#)<`K`> ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` The type of the circuit ID used by the provider. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new NodeZkConfigProvider**<`K`>(`directory`): `NodeZkConfigProvider`<`K`> #### Parameters[​](#parameters "Direct link to Parameters") ##### directory[​](#directory "Direct link to directory") `string` The path to the base directory containing the key and ZKIR subdirectories. #### Returns[​](#returns "Direct link to Returns") `NodeZkConfigProvider`<`K`> #### Overrides[​](#overrides "Direct link to Overrides") `ZKConfigProvider.constructor` ## Properties[​](#properties "Direct link to Properties") ### directory[​](#directory-1 "Direct link to directory") > `readonly` **directory**: `string` The path to the base directory containing the key and ZKIR subdirectories. ## Methods[​](#methods "Direct link to Methods") ### asKeyMaterialProvider()[​](#askeymaterialprovider "Direct link to asKeyMaterialProvider()") > **asKeyMaterialProvider**(): `KeyMaterialProvider` #### Returns[​](#returns-1 "Direct link to Returns") `KeyMaterialProvider` #### Inherited from[​](#inherited-from "Direct link to Inherited from") `ZKConfigProvider.asKeyMaterialProvider` *** ### get()[​](#get "Direct link to get()") > **get**(`circuitId`): `Promise`<`ZKConfig`<`K`>> Retrieves all zero-knowledge artifacts produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### circuitId[​](#circuitid "Direct link to circuitId") `K` The circuit ID of the artifacts to retrieve. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`ZKConfig`<`K`>> #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") `ZKConfigProvider.get` *** ### getProverKey()[​](#getproverkey "Direct link to getProverKey()") > **getProverKey**(`circuitId`): `Promise`<`ProverKey`> [ZKConfigProvider.getProverKey](#) #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### circuitId[​](#circuitid-1 "Direct link to circuitId") `K` #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`ProverKey`> #### Overrides[​](#overrides-1 "Direct link to Overrides") `ZKConfigProvider.getProverKey` *** ### getVerifierKey()[​](#getverifierkey "Direct link to getVerifierKey()") > **getVerifierKey**(`circuitId`): `Promise`<`VerifierKey`> [ZKConfigProvider.getVerifierKey](#) #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### circuitId[​](#circuitid-2 "Direct link to circuitId") `K` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`VerifierKey`> #### Overrides[​](#overrides-2 "Direct link to Overrides") `ZKConfigProvider.getVerifierKey` *** ### getVerifierKeys()[​](#getverifierkeys "Direct link to getVerifierKeys()") > **getVerifierKeys**(`circuitIds`): `Promise`<\[`K`, `VerifierKey`]\[]> Retrieves the verifier keys produced by `compactc` compiler for the given circuits. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### circuitIds[​](#circuitids "Direct link to circuitIds") `K`\[] The circuit IDs of the verifier keys to retrieve. #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<\[`K`, `VerifierKey`]\[]> #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") `ZKConfigProvider.getVerifierKeys` *** ### getZKIR()[​](#getzkir "Direct link to getZKIR()") > **getZKIR**(`circuitId`): `Promise`<`ZKIR`> [ZKConfigProvider.getZKIR](#) #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### circuitId[​](#circuitid-3 "Direct link to circuitId") `K` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<`ZKIR`> #### Overrides[​](#overrides-3 "Direct link to Overrides") `ZKConfigProvider.getZKIR` --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-protocol [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-protocol # Protocol Version-agnostic re-exports of Midnight protocol packages. Decouples framework consumers from specific protocol version numbers, so that protocol upgrades require changes only in this package. ## Versioning Contract[​](#versioning-contract "Direct link to Versioning Contract") **This package must never include a protocol version number in its name.** The package name `@midnight-ntwrk/midnight-js-protocol` is permanent. If the package were renamed to `midnight-js-protocol-v2` or similar, every consumer import would need updating, defeating the purpose of this abstraction. Protocol version changes are handled through: * **semver** (npm package version): major bump when underlying protocol packages change in a breaking way * **internal re-exports**: this package updates which concrete protocol packages it re-exports ## Installation[​](#installation "Direct link to Installation") ``` yarn add @midnight-ntwrk/midnight-js-protocol ``` ## Usage[​](#usage "Direct link to Usage") Import protocol types through version-agnostic subpaths: ``` import { type ContractAddress } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { type CompactRuntime } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { Contract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import { type OnChainRuntime } from '@midnight-ntwrk/midnight-js-protocol/onchain-runtime'; import { createPlatform } from '@midnight-ntwrk/midnight-js-protocol/platform-js'; ``` ## Sub-path Exports[​](#sub-path-exports "Direct link to Sub-path Exports") | Sub-path | Re-exports | Description | | -------------------------------------- | ---------------------------------------------------- | ---------------------------------------- | | `./ledger` | `@midnight-ntwrk/ledger-v8` | Ledger types and transaction primitives | | `./compact-runtime` | `@midnight-ntwrk/compact-runtime` | Compact contract runtime utilities | | `./compact-js` | `@midnight-ntwrk/compact-js` | Compact JS bindings | | `./compact-js/effect` | `@midnight-ntwrk/compact-js/effect` | Effect-based Compact bindings | | `./compact-js/effect/Contract` | `@midnight-ntwrk/compact-js/effect/Contract` | Effect-based Contract module | | `./onchain-runtime` | `@midnight-ntwrk/onchain-runtime-v3` | On-chain runtime (Impact VM) | | `./platform-js` | `@midnight-ntwrk/platform-js` | Platform services | | `./platform-js/effect/Configuration` | `@midnight-ntwrk/platform-js/effect/Configuration` | Effect-based configuration | | `./platform-js/effect/ContractAddress` | `@midnight-ntwrk/platform-js/effect/ContractAddress` | Effect-based contract address resolution | ## ESLint Enforcement[​](#eslint-enforcement "Direct link to ESLint Enforcement") An ESLint `no-restricted-imports` rule prevents direct imports of the underlying protocol packages outside of this package. If you see an error like: > Import from `@midnight-ntwrk/midnight-js-protocol/ledger` instead. Replace the direct protocol import with the corresponding subpath from this package. ## Resources[​](#resources "Direct link to Resources") * [Midnight Network](https://midnight.network) * [Developer Hub](https://midnight.network/developer-hub) ## Terms & License[​](#terms--license "Direct link to Terms & License") By using this package, you agree to [Midnight's Terms and Conditions](https://midnight.network/static/terms.pdf) and [Privacy Policy](https://midnight.network/static/privacy-policy.pdf). Licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-types [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-types # @midnight-ntwrk/midnight-js-types ## Enumerations[​](#enumerations "Direct link to Enumerations") * [LogLevel](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/enumerations/LogLevel.md) ## Classes[​](#classes "Direct link to Classes") * [ExportDecryptionError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ExportDecryptionError.md) * [ImportConflictError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ImportConflictError.md) * [InvalidExportFormatError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/InvalidExportFormatError.md) * [InvalidProtocolSchemeError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/InvalidProtocolSchemeError.md) * [PrivateStateExportError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateExportError.md) * [PrivateStateImportError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md) * [SigningKeyExportError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/SigningKeyExportError.md) * [ZKConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ZKConfigProvider.md) ## Interfaces[​](#interfaces "Direct link to Interfaces") * [ExportPrivateStatesOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ExportPrivateStatesOptions.md) * [ExportSigningKeysOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ExportSigningKeysOptions.md) * [FinalizedTxData](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/FinalizedTxData.md) * [ImportPrivateStatesOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesOptions.md) * [ImportPrivateStatesResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesResult.md) * [ImportSigningKeysOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysOptions.md) * [ImportSigningKeysResult](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysResult.md) * [LoggerProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/LoggerProvider.md) * [MidnightProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/MidnightProvider.md) * [MidnightProviders](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/MidnightProviders.md) * [PrivateStateExport](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateExport.md) * [PrivateStateProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateProvider.md) * [ProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) * [ProveTxConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProveTxConfig.md) * [PublicDataProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PublicDataProvider.md) * [SigningKeyExport](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/SigningKeyExport.md) * [WalletProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/WalletProvider.md) * [ZKConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ZKConfig.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [All](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/All.md) * [AnyPrivateState](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/AnyPrivateState.md) * [AnyProvableCircuitId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/AnyProvableCircuitId.md) * [BlockHash](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHash.md) * [BlockHashConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHashConfig.md) * [BlockHeightConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHeightConfig.md) * [ContractExecutableRuntimeOptions](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractExecutableRuntimeOptions.md) * [ContractStateObservableConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractStateObservableConfig.md) * [Fees](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/Fees.md) * [KeyMaterialProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/KeyMaterialProvider.md) * [Latest](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/Latest.md) * [PrivateStateId](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateId.md) * [PrivateStateImportErrorCause](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md) * [ProverKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md) * [SegmentStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/SegmentStatus.md) * [TxIdConfig](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/TxIdConfig.md) * [TxStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/TxStatus.md) * [UnboundTransaction](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnboundTransaction.md) * [UnshieldedBalance](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalance.md) * [UnshieldedBalances](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md) * [UnshieldedUtxo](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxo.md) * [UnshieldedUtxos](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxos.md) * [VerifierKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md) * [ZKIR](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md) ## Variables[​](#variables "Direct link to Variables") * [exitResultOrError](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/exitResultOrError.md) * [FailEntirely](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/FailEntirely.md) * [FailFallible](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/FailFallible.md) * [makeContractExecutableRuntime](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/makeContractExecutableRuntime.md) * [MAX\_EXPORT\_SIGNING\_KEYS](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/MAX_EXPORT_SIGNING_KEYS.md) * [MAX\_EXPORT\_STATES](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/MAX_EXPORT_STATES.md) * [SegmentFail](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SegmentFail.md) * [SegmentSuccess](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SegmentSuccess.md) * [SucceedEntirely](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SucceedEntirely.md) ## Functions[​](#functions "Direct link to Functions") * [asContractAddress](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/asContractAddress.md) * [asEffectOption](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/asEffectOption.md) * [createProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createProofProvider.md) * [createProverKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createProverKey.md) * [createVerifierKey](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createVerifierKey.md) * [createZKIR](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/createZKIR.md) * [zkConfigToProvingKeyMaterial](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/functions/zkConfigToProvingKeyMaterial.md) --- # ExportDecryptionError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ExportDecryptionError # Class: ExportDecryptionError Error thrown when decryption of export data fails. This could be due to wrong password, corrupted data, or tampered content. The specific cause is intentionally not disclosed to prevent oracle attacks. ## Extends[​](#extends "Direct link to Extends") * [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new ExportDecryptionError**(): `ExportDecryptionError` #### Returns[​](#returns "Direct link to Returns") `ExportDecryptionError` #### Overrides[​](#overrides "Direct link to Overrides") [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### cause?[​](#cause "Direct link to cause?") > `readonly` `optional` **cause?**: [`PrivateStateImportErrorCause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md) #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md).[`cause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md#cause) --- # ImportConflictError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ImportConflictError # Class: ImportConflictError Error thrown when import conflicts with existing data and conflictStrategy is 'error'. ## Extends[​](#extends "Direct link to Extends") * [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new ImportConflictError**(`conflictCount`, `entityName?`): `ImportConflictError` #### Parameters[​](#parameters "Direct link to Parameters") ##### conflictCount[​](#conflictcount "Direct link to conflictCount") `number` ##### entityName?[​](#entityname "Direct link to entityName?") `string` = `'private state'` #### Returns[​](#returns "Direct link to Returns") `ImportConflictError` #### Overrides[​](#overrides "Direct link to Overrides") [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### cause?[​](#cause "Direct link to cause?") > `readonly` `optional` **cause?**: [`PrivateStateImportErrorCause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md) #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md).[`cause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md#cause) *** ### conflictCount[​](#conflictcount-1 "Direct link to conflictCount") > `readonly` **conflictCount**: `number` --- # InvalidExportFormatError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / InvalidExportFormatError # Class: InvalidExportFormatError Error thrown when the export data format is invalid. ## Extends[​](#extends "Direct link to Extends") * [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new InvalidExportFormatError**(`message?`): `InvalidExportFormatError` #### Parameters[​](#parameters "Direct link to Parameters") ##### message?[​](#message "Direct link to message?") `string` = `'Invalid export format'` #### Returns[​](#returns "Direct link to Returns") `InvalidExportFormatError` #### Overrides[​](#overrides "Direct link to Overrides") [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md).[`constructor`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### cause?[​](#cause "Direct link to cause?") > `readonly` `optional` **cause?**: [`PrivateStateImportErrorCause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md) #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`PrivateStateImportError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md).[`cause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/PrivateStateImportError.md#cause) --- # InvalidProtocolSchemeError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / InvalidProtocolSchemeError # Class: InvalidProtocolSchemeError An error describing an invalid protocol scheme. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new InvalidProtocolSchemeError**(`invalidScheme`, `allowableSchemes`): `InvalidProtocolSchemeError` #### Parameters[​](#parameters "Direct link to Parameters") ##### invalidScheme[​](#invalidscheme "Direct link to invalidScheme") `string` The invalid scheme. ##### allowableSchemes[​](#allowableschemes "Direct link to allowableSchemes") `string`\[] The valid schemes that are allowed. #### Returns[​](#returns "Direct link to Returns") `InvalidProtocolSchemeError` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` ## Properties[​](#properties "Direct link to Properties") ### allowableSchemes[​](#allowableschemes-1 "Direct link to allowableSchemes") > `readonly` **allowableSchemes**: `string`\[] The valid schemes that are allowed. *** ### invalidScheme[​](#invalidscheme-1 "Direct link to invalidScheme") > `readonly` **invalidScheme**: `string` The invalid scheme. --- # PrivateStateExportError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PrivateStateExportError # Class: PrivateStateExportError An error thrown when exporting private states fails. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new PrivateStateExportError**(`message`): `PrivateStateExportError` #### Parameters[​](#parameters "Direct link to Parameters") ##### message[​](#message "Direct link to message") `string` #### Returns[​](#returns "Direct link to Returns") `PrivateStateExportError` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` --- # PrivateStateImportError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PrivateStateImportError # Class: PrivateStateImportError Base error thrown when importing private states fails. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Extended by[​](#extended-by "Direct link to Extended by") * [`ExportDecryptionError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ExportDecryptionError.md) * [`InvalidExportFormatError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/InvalidExportFormatError.md) * [`ImportConflictError`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ImportConflictError.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new PrivateStateImportError**(`message`, `cause?`): `PrivateStateImportError` #### Parameters[​](#parameters "Direct link to Parameters") ##### message[​](#message "Direct link to message") `string` ##### cause?[​](#cause "Direct link to cause?") [`PrivateStateImportErrorCause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md) #### Returns[​](#returns "Direct link to Returns") `PrivateStateImportError` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` ## Properties[​](#properties "Direct link to Properties") ### cause?[​](#cause-1 "Direct link to cause?") > `readonly` `optional` **cause?**: [`PrivateStateImportErrorCause`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateImportErrorCause.md) #### Inherited from[​](#inherited-from "Direct link to Inherited from") `Error.cause` --- # SigningKeyExportError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / SigningKeyExportError # Class: SigningKeyExportError An error thrown when exporting signing keys fails. ## Extends[​](#extends "Direct link to Extends") * `Error` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new SigningKeyExportError**(`message`): `SigningKeyExportError` #### Parameters[​](#parameters "Direct link to Parameters") ##### message[​](#message "Direct link to message") `string` #### Returns[​](#returns "Direct link to Returns") `SigningKeyExportError` #### Overrides[​](#overrides "Direct link to Overrides") `Error.constructor` --- # ZKConfigProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ZKConfigProvider # Abstract Class: ZKConfigProvider\ A provider for zero-knowledge intermediate representations, prover keys, and verifier keys. All three are used by the [ProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) to create a proof for a call transaction. The implementation of this provider depends on the runtime environment, since each environment has different conventions for accessing static artifacts. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` The type of the circuit ID used by the provider. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new ZKConfigProvider**<`K`>(): `ZKConfigProvider`<`K`> #### Returns[​](#returns "Direct link to Returns") `ZKConfigProvider`<`K`> ## Methods[​](#methods "Direct link to Methods") ### asKeyMaterialProvider()[​](#askeymaterialprovider "Direct link to asKeyMaterialProvider()") > **asKeyMaterialProvider**(): [`KeyMaterialProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/KeyMaterialProvider.md) #### Returns[​](#returns-1 "Direct link to Returns") [`KeyMaterialProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/KeyMaterialProvider.md) *** ### get()[​](#get "Direct link to get()") > **get**(`circuitId`): `Promise`<[`ZKConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ZKConfig.md)<`K`>> Retrieves all zero-knowledge artifacts produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters "Direct link to Parameters") ##### circuitId[​](#circuitid "Direct link to circuitId") `K` The circuit ID of the artifacts to retrieve. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`ZKConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ZKConfig.md)<`K`>> *** ### getProverKey()[​](#getproverkey "Direct link to getProverKey()") > `abstract` **getProverKey**(`circuitId`): `Promise`<[`ProverKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md)> Retrieves the prover key produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### circuitId[​](#circuitid-1 "Direct link to circuitId") `K` The circuit ID of the prover key to retrieve. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<[`ProverKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md)> *** ### getVerifierKey()[​](#getverifierkey "Direct link to getVerifierKey()") > `abstract` **getVerifierKey**(`circuitId`): `Promise`<[`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md)> Retrieves the verifier key produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### circuitId[​](#circuitid-2 "Direct link to circuitId") `K` The circuit ID of the verifier key to retrieve. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<[`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md)> *** ### getVerifierKeys()[​](#getverifierkeys "Direct link to getVerifierKeys()") > **getVerifierKeys**(`circuitIds`): `Promise`<\[`K`, [`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md)]\[]> Retrieves the verifier keys produced by `compactc` compiler for the given circuits. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### circuitIds[​](#circuitids "Direct link to circuitIds") `K`\[] The circuit IDs of the verifier keys to retrieve. #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<\[`K`, [`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md)]\[]> *** ### getZKIR()[​](#getzkir "Direct link to getZKIR()") > `abstract` **getZKIR**(`circuitId`): `Promise`<[`ZKIR`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md)> Retrieves the zero-knowledge intermediate representation produced by `compactc` compiler for the given circuit. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### circuitId[​](#circuitid-3 "Direct link to circuitId") `K` The circuit ID of the ZKIR to retrieve. #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`ZKIR`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md)> --- # LogLevel > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / LogLevel # Enumeration: LogLevel A valid named log level. ## Enumeration Members[​](#enumeration-members "Direct link to Enumeration Members") ### DEBUG[​](#debug "Direct link to DEBUG") > **DEBUG**: `"debug"` Log levels used by Midnight.JS to report internal state. *** ### ERROR[​](#error "Direct link to ERROR") > **ERROR**: `"error"` *** ### FATAL[​](#fatal "Direct link to FATAL") > **FATAL**: `"fatal"` *** ### INFO[​](#info "Direct link to INFO") > **INFO**: `"info"` Log levels typically used by DAapp developers. *** ### TRACE[​](#trace "Direct link to TRACE") > **TRACE**: `"trace"` *** ### WARN[​](#warn "Direct link to WARN") > **WARN**: `"warn"` --- # asContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / asContractAddress # Function: asContractAddress() > **asContractAddress**(`address`): [`ContractAddress`](#) Constructs a branded contract address from a given string value. ## Parameters[​](#parameters "Direct link to Parameters") ### address[​](#address "Direct link to address") `string` A string value representing a contract address. ## Returns[​](#returns "Direct link to Returns") [`ContractAddress`](#) A [ContractAddress](#) constructed from `address`. --- # asEffectOption > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / asEffectOption # Function: asEffectOption() > **asEffectOption**<`T`>(`obj`): `Option`<`T`> Wraps an object into an `Option.some`. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### T[​](#t "Direct link to T") `T` ## Parameters[​](#parameters "Direct link to Parameters") ### obj[​](#obj "Direct link to obj") `unknown` The value that should be wrapped into an `Option`. ## Returns[​](#returns "Direct link to Returns") `Option`<`T`> An `Option.some` for `obj`. --- # createProofProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / createProofProvider # Function: createProofProvider() > **createProofProvider**(`provingProvider`, `costModel?`): [`ProofProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) Creates a [ProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) from a [ProvingProvider](#). The returned provider proves transactions using the initial cost model. ## Parameters[​](#parameters "Direct link to Parameters") ### provingProvider[​](#provingprovider "Direct link to provingProvider") [`ProvingProvider`](#) The underlying proving provider used to generate proofs. ### costModel?[​](#costmodel "Direct link to costModel?") `CostModel` = `...` Optional cost model to use for proof generation. Defaults to the initial cost model if not provided. ## Returns[​](#returns "Direct link to Returns") [`ProofProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) A [ProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) that delegates proof generation to the given proving provider. --- # createProverKey > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / createProverKey # Function: createProverKey() > **createProverKey**(`uint8Array`): [`ProverKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md) Creates a branded prover key representation from a prover key binary. ## Parameters[​](#parameters "Direct link to Parameters") ### uint8Array[​](#uint8array "Direct link to uint8Array") `Uint8Array` The prover key binary. ## Returns[​](#returns "Direct link to Returns") [`ProverKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md) --- # createVerifierKey > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / createVerifierKey # Function: createVerifierKey() > **createVerifierKey**(`uint8Array`): [`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md) Creates a branded verifier key representation from a verifier key binary. ## Parameters[​](#parameters "Direct link to Parameters") ### uint8Array[​](#uint8array "Direct link to uint8Array") `Uint8Array` The verifier key binary. ## Returns[​](#returns "Direct link to Returns") [`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md) --- # createZKIR > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / createZKIR # Function: createZKIR() > **createZKIR**(`uint8Array`): [`ZKIR`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md) Creates a branded ZKIR representation from a ZKIR binary. ## Parameters[​](#parameters "Direct link to Parameters") ### uint8Array[​](#uint8array "Direct link to uint8Array") `Uint8Array` The ZKIR binary. ## Returns[​](#returns "Direct link to Returns") [`ZKIR`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md) --- # zkConfigToProvingKeyMaterial > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / zkConfigToProvingKeyMaterial # Function: zkConfigToProvingKeyMaterial() > **zkConfigToProvingKeyMaterial**<`K`>(`zkConfig`): `object` Converts a ZKConfig object to ProvingKeyMaterial format. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### zkConfig[​](#zkconfig "Direct link to zkConfig") [`ZKConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ZKConfig.md)<`K`> ## Returns[​](#returns "Direct link to Returns") `object` ### ir[​](#ir "Direct link to ir") > **ir**: [`ZKIR`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md) = `zkConfig.zkir` ### proverKey[​](#proverkey "Direct link to proverKey") > **proverKey**: [`ProverKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md) = `zkConfig.proverKey` ### verifierKey[​](#verifierkey "Direct link to verifierKey") > **verifierKey**: [`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md) = `zkConfig.verifierKey` --- # ExportPrivateStatesOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ExportPrivateStatesOptions # Interface: ExportPrivateStatesOptions Options for exporting private states. ## Properties[​](#properties "Direct link to Properties") ### maxStates?[​](#maxstates "Direct link to maxStates?") > `readonly` `optional` **maxStates?**: `number` Maximum number of states to export. Defaults to MAX\_EXPORT\_STATES (10000). Set to a lower value to limit memory usage. *** ### password?[​](#password "Direct link to password?") > `readonly` `optional` **password?**: `string` Password used to encrypt the export. Must be at least 16 characters. If not provided, uses the storage password. --- # ExportSigningKeysOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ExportSigningKeysOptions # Interface: ExportSigningKeysOptions Options for exporting signing keys. ## Properties[​](#properties "Direct link to Properties") ### maxKeys?[​](#maxkeys "Direct link to maxKeys?") > `readonly` `optional` **maxKeys?**: `number` Maximum number of keys to export. Defaults to MAX\_EXPORT\_SIGNING\_KEYS (10000). Set to a lower value to limit memory usage. *** ### password?[​](#password "Direct link to password?") > `readonly` `optional` **password?**: `string` Password used to encrypt the export. Must be at least 16 characters. If not provided, uses the storage password. --- # FinalizedTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / FinalizedTxData # Interface: FinalizedTxData Data for any finalized transaction. ## Properties[​](#properties "Direct link to Properties") ### blockAuthor[​](#blockauthor "Direct link to blockAuthor") > `readonly` **blockAuthor**: `string` | `null` The author of the block in which the transaction was included. *** ### blockHash[​](#blockhash "Direct link to blockHash") > `readonly` **blockHash**: `string` The block hash of the block in which the transaction was included. *** ### blockHeight[​](#blockheight "Direct link to blockHeight") > `readonly` **blockHeight**: `number` The block height of the block in which the transaction was included. *** ### blockTimestamp[​](#blocktimestamp "Direct link to blockTimestamp") > `readonly` **blockTimestamp**: `number` The timestamp of the block in which the transaction was included. *** ### fees[​](#fees "Direct link to fees") > `readonly` **fees**: [`Fees`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/Fees.md) The fees associated with the transaction, including both paid and estimated fees. *** ### identifiers[​](#identifiers "Direct link to identifiers") > `readonly` **identifiers**: readonly `string`\[] All transaction IDs of the submitted transaction. *** ### indexerId[​](#indexerid "Direct link to indexerId") > `readonly` **indexerId**: `number` The indexer internal db ID. *** ### protocolVersion[​](#protocolversion "Direct link to protocolVersion") > `readonly` **protocolVersion**: `number` The protocol version of the transaction. *** ### segmentStatusMap[​](#segmentstatusmap "Direct link to segmentStatusMap") > `readonly` **segmentStatusMap**: `Map`<`number`, [`SegmentStatus`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/SegmentStatus.md)> | `undefined` The map that associates segment identifiers (numbers) with their corresponding status [SegmentStatus](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/SegmentStatus.md). The segment identifier is represented as a number (key in the map), and the status indicates the success or failure of the transaction update. *** ### status[​](#status "Direct link to status") > `readonly` **status**: [`TxStatus`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/TxStatus.md) The status of a submitted transaction. *** ### tx[​](#tx "Direct link to tx") > `readonly` **tx**: `Transaction`<`SignatureEnabled`, `Proof`, `Binding`> The transaction that was finalized. *** ### txHash[​](#txhash "Direct link to txHash") > `readonly` **txHash**: `string` The transaction hash of the transaction in which the original transaction was included. *** ### txId[​](#txid "Direct link to txId") > `readonly` **txId**: `string` One of the transaction ID of the submitted transaction. *** ### unshielded[​](#unshielded "Direct link to unshielded") > `readonly` **unshielded**: [`UnshieldedUtxos`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxos.md) Represents the unshielded outputs, typically used for transactions or operations involving data or values that are not encrypted or concealed. --- # ImportPrivateStatesOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ImportPrivateStatesOptions # Interface: ImportPrivateStatesOptions Options for importing private states. ## Properties[​](#properties "Direct link to Properties") ### conflictStrategy?[​](#conflictstrategy "Direct link to conflictStrategy?") > `readonly` `optional` **conflictStrategy?**: `"error"` | `"skip"` | `"overwrite"` How to handle conflicts when a private state ID already exists. * 'skip': Keep existing state, ignore imported state * 'overwrite': Replace existing state with imported state * 'error': Throw an error if any conflict is detected Default: 'error' *** ### maxStates?[​](#maxstates "Direct link to maxStates?") > `readonly` `optional` **maxStates?**: `number` Maximum number of states to import. Defaults to MAX\_EXPORT\_STATES (10000). Set to a lower value to limit memory usage. *** ### password?[​](#password "Direct link to password?") > `readonly` `optional` **password?**: `string` Password used to decrypt the import. Must match the password used during export. If not provided, uses the storage password. --- # ImportPrivateStatesResult > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ImportPrivateStatesResult # Interface: ImportPrivateStatesResult Result of an import operation. ## Properties[​](#properties "Direct link to Properties") ### imported[​](#imported "Direct link to imported") > `readonly` **imported**: `number` Number of states successfully imported. *** ### overwritten[​](#overwritten "Direct link to overwritten") > `readonly` **overwritten**: `number` Number of states that overwrote existing states (when conflictStrategy is 'overwrite'). *** ### skipped[​](#skipped "Direct link to skipped") > `readonly` **skipped**: `number` Number of states skipped due to conflicts (when conflictStrategy is 'skip'). --- # ImportSigningKeysOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ImportSigningKeysOptions # Interface: ImportSigningKeysOptions Options for importing signing keys. ## Properties[​](#properties "Direct link to Properties") ### conflictStrategy?[​](#conflictstrategy "Direct link to conflictStrategy?") > `readonly` `optional` **conflictStrategy?**: `"error"` | `"skip"` | `"overwrite"` How to handle conflicts when a signing key already exists for an address. * 'skip': Keep existing key, ignore imported key * 'overwrite': Replace existing key with imported key * 'error': Throw an error if any conflict is detected Default: 'error' *** ### maxKeys?[​](#maxkeys "Direct link to maxKeys?") > `readonly` `optional` **maxKeys?**: `number` Maximum number of keys to import. Defaults to MAX\_EXPORT\_SIGNING\_KEYS (10000). Set to a lower value to limit memory usage. *** ### password?[​](#password "Direct link to password?") > `readonly` `optional` **password?**: `string` Password used to decrypt the import. Must match the password used during export. If not provided, uses the storage password. --- # ImportSigningKeysResult > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ImportSigningKeysResult # Interface: ImportSigningKeysResult Result of a signing key import operation. ## Properties[​](#properties "Direct link to Properties") ### imported[​](#imported "Direct link to imported") > `readonly` **imported**: `number` Number of keys successfully imported. *** ### overwritten[​](#overwritten "Direct link to overwritten") > `readonly` **overwritten**: `number` Number of keys that overwrote existing keys (when conflictStrategy is 'overwrite'). *** ### skipped[​](#skipped "Direct link to skipped") > `readonly` **skipped**: `number` Number of keys skipped due to conflicts (when conflictStrategy is 'skip'). --- # LoggerProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / LoggerProvider # Interface: LoggerProvider A provider for logging functions. ## Properties[​](#properties "Direct link to Properties") ### debug?[​](#debug "Direct link to debug?") > `optional` **debug?**: `LogFn` *** ### error?[​](#error "Direct link to error?") > `optional` **error?**: `LogFn` *** ### fatal?[​](#fatal "Direct link to fatal?") > `optional` **fatal?**: `LogFn` *** ### info?[​](#info "Direct link to info?") > `optional` **info?**: `LogFn` *** ### warn?[​](#warn "Direct link to warn?") > `optional` **warn?**: `LogFn` ## Methods[​](#methods "Direct link to Methods") ### isLevelEnabled()[​](#islevelenabled "Direct link to isLevelEnabled()") > **isLevelEnabled**(`level`): `boolean` #### Parameters[​](#parameters "Direct link to Parameters") ##### level[​](#level "Direct link to level") [`LogLevel`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/enumerations/LogLevel.md) #### Returns[​](#returns "Direct link to Returns") `boolean` --- # MidnightProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / MidnightProvider # Interface: MidnightProvider Interface for Midnight transaction submission logic. It could be implemented, e.g., by a wallet, a third-party service, or a node itself. ## Methods[​](#methods "Direct link to Methods") ### submitTx()[​](#submittx "Direct link to submitTx()") > **submitTx**(`tx`): `Promise`<`string`> Submit a transaction to the network to be consensed upon. #### Parameters[​](#parameters "Direct link to Parameters") ##### tx[​](#tx "Direct link to tx") `FinalizedTransaction` The finalized transaction to submit. #### Returns[​](#returns "Direct link to Returns") `Promise`<`string`> The transaction identifier of the submitted transaction. --- # MidnightProviders > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / MidnightProviders # Interface: MidnightProviders\ Set of providers needed for transaction construction and submission. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* [`AnyProvableCircuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/AnyProvableCircuitId.md) = [`AnyProvableCircuitId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/AnyProvableCircuitId.md) A union of string literal types representing the callable circuits. ### PSI[​](#psi "Direct link to PSI") `PSI` *extends* [`PrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateId.md) = [`PrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateId.md) Parameter indicating the private state ID, sometimes a union of string literals. ### PS[​](#ps "Direct link to PS") `PS` = `any` Parameter indicating the private state type stored, sometimes a union of private state types. ## Properties[​](#properties "Direct link to Properties") ### loggerProvider?[​](#loggerprovider "Direct link to loggerProvider?") > `readonly` `optional` **loggerProvider?**: [`LoggerProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/LoggerProvider.md) An optional logger that provides utilities for logging at given levels. *** ### midnightProvider[​](#midnightprovider "Direct link to midnightProvider") > `readonly` **midnightProvider**: [`MidnightProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/MidnightProvider.md) Submits proven, balanced transactions to the network. *** ### privateStateProvider[​](#privatestateprovider "Direct link to privateStateProvider") > `readonly` **privateStateProvider**: [`PrivateStateProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateProvider.md)<`PSI`, `PS`> Manages the private state of a contract. *** ### proofProvider[​](#proofprovider "Direct link to proofProvider") > `readonly` **proofProvider**: [`ProofProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) Creates proven, unbalanced transactions. *** ### publicDataProvider[​](#publicdataprovider "Direct link to publicDataProvider") > `readonly` **publicDataProvider**: [`PublicDataProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PublicDataProvider.md) Retrieves public data from the blockchain. *** ### walletProvider[​](#walletprovider "Direct link to walletProvider") > `readonly` **walletProvider**: [`WalletProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/WalletProvider.md) Creates proven, balanced transactions. *** ### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") > `readonly` **zkConfigProvider**: [`ZKConfigProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ZKConfigProvider.md)<`PCK`> Retrieves the ZK artifacts of a contract needed to create proofs. --- # PrivateStateExport > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PrivateStateExport # Interface: PrivateStateExport Represents the exported private state data structure. All metadata is included in the encrypted payload to prevent tampering. ## Properties[​](#properties "Direct link to Properties") ### encryptedPayload[​](#encryptedpayload "Direct link to encryptedPayload") > `readonly` **encryptedPayload**: `string` Encrypted payload containing version, metadata, and serialized private states. Format: base64-encoded AES-256-GCM encrypted JSON. *** ### format[​](#format "Direct link to format") > `readonly` **format**: `"midnight-private-state-export"` Format identifier. Must be 'midnight-private-state-export'. *** ### salt[​](#salt "Direct link to salt") > `readonly` **salt**: `string` Salt used for key derivation (hex-encoded, 32 bytes / 64 characters). Required for decryption with the export password. --- # PrivateStateProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PrivateStateProvider # Interface: PrivateStateProvider\ Interface for a typed key-valued store containing contract private states. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PSI[​](#psi "Direct link to PSI") `PSI` *extends* [`PrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateId.md) = [`PrivateStateId`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/PrivateStateId.md) Parameter indicating the private state ID, sometimes a union of string literals. ### PS[​](#ps "Direct link to PS") `PS` = `any` Parameter indicating the private state type stored, sometimes a union of private state types. ## Methods[​](#methods "Direct link to Methods") ### clear()[​](#clear "Direct link to clear()") > **clear**(): `Promise`<`void`> Remove all contract private states. #### Returns[​](#returns "Direct link to Returns") `Promise`<`void`> *** ### clearSigningKeys()[​](#clearsigningkeys "Direct link to clearSigningKeys()") > **clearSigningKeys**(): `Promise`<`void`> Remove all contract signing keys. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`void`> *** ### exportPrivateStates()[​](#exportprivatestates "Direct link to exportPrivateStates()") > **exportPrivateStates**(`options?`): `Promise`<[`PrivateStateExport`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateExport.md)> Export all private states as an encrypted JSON-serializable structure. NOTE: This does NOT export signing keys for security reasons. #### Parameters[​](#parameters "Direct link to Parameters") ##### options?[​](#options "Direct link to options?") [`ExportPrivateStatesOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ExportPrivateStatesOptions.md) Export options including optional custom password and state limit. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`PrivateStateExport`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateExport.md)> A JSON-serializable export structure that can be saved or transmitted. #### Throws[​](#throws "Direct link to Throws") If no states exist to export or limit exceeded. *** ### exportSigningKeys()[​](#exportsigningkeys "Direct link to exportSigningKeys()") > **exportSigningKeys**(`options?`): `Promise`<[`SigningKeyExport`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/SigningKeyExport.md)> Export all signing keys as an encrypted JSON-serializable structure. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### options?[​](#options-1 "Direct link to options?") [`ExportSigningKeysOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ExportSigningKeysOptions.md) Export options including optional custom password and key limit. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<[`SigningKeyExport`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/SigningKeyExport.md)> A JSON-serializable export structure that can be saved or transmitted. #### Throws[​](#throws-1 "Direct link to Throws") If no keys exist to export or limit exceeded. *** ### get()[​](#get "Direct link to get()") > **get**(`privateStateId`): `Promise`<`PS` | `null`> Retrieve the private state at the given private state ID. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### privateStateId[​](#privatestateid "Direct link to privateStateId") `PSI` The private state identifier. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`PS` | `null`> *** ### getSigningKey()[​](#getsigningkey "Direct link to getSigningKey()") > **getSigningKey**(`address`): `Promise`<`string` | `null`> Retrieve the signing key for a contract. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### address[​](#address "Direct link to address") `string` The address of the contract for which to get the signing key. #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<`string` | `null`> *** ### importPrivateStates()[​](#importprivatestates "Direct link to importPrivateStates()") > **importPrivateStates**(`exportData`, `options?`): `Promise`<[`ImportPrivateStatesResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesResult.md)> Import private states from a previously exported structure. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### exportData[​](#exportdata "Direct link to exportData") [`PrivateStateExport`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/PrivateStateExport.md) The export data structure to import. ##### options?[​](#options-2 "Direct link to options?") [`ImportPrivateStatesOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesOptions.md) Import options including password, conflict strategy, and state limit. #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`ImportPrivateStatesResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportPrivateStatesResult.md)> Result indicating how many states were imported/skipped/overwritten. #### Throws[​](#throws-2 "Direct link to Throws") If decryption fails (wrong password or corrupted data). #### Throws[​](#throws-3 "Direct link to Throws") If the export format is invalid or unsupported. #### Throws[​](#throws-4 "Direct link to Throws") If conflictStrategy is 'error' and conflicts exist. *** ### importSigningKeys()[​](#importsigningkeys "Direct link to importSigningKeys()") > **importSigningKeys**(`exportData`, `options?`): `Promise`<[`ImportSigningKeysResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysResult.md)> Import signing keys from a previously exported structure. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### exportData[​](#exportdata-1 "Direct link to exportData") [`SigningKeyExport`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/SigningKeyExport.md) The export data structure to import. ##### options?[​](#options-3 "Direct link to options?") [`ImportSigningKeysOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysOptions.md) Import options including password, conflict strategy, and key limit. #### Returns[​](#returns-7 "Direct link to Returns") `Promise`<[`ImportSigningKeysResult`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ImportSigningKeysResult.md)> Result indicating how many keys were imported/skipped/overwritten. #### Throws[​](#throws-5 "Direct link to Throws") If decryption fails (wrong password or corrupted data). #### Throws[​](#throws-6 "Direct link to Throws") If the export format is invalid or unsupported. #### Throws[​](#throws-7 "Direct link to Throws") If conflictStrategy is 'error' and conflicts exist. *** ### remove()[​](#remove "Direct link to remove()") > **remove**(`privateStateId`): `Promise`<`void`> Remove the value at the given private state ID. #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### privateStateId[​](#privatestateid-1 "Direct link to privateStateId") `PSI` The private state identifier. #### Returns[​](#returns-8 "Direct link to Returns") `Promise`<`void`> *** ### removeSigningKey()[​](#removesigningkey "Direct link to removeSigningKey()") > **removeSigningKey**(`address`): `Promise`<`void`> Remove the signing key for a contract. #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### address[​](#address-1 "Direct link to address") `string` The address of the contract for which to delete the signing key. #### Returns[​](#returns-9 "Direct link to Returns") `Promise`<`void`> *** ### set()[​](#set "Direct link to set()") > **set**(`privateStateId`, `state`): `Promise`<`void`> Store the given private state at the given private state ID. #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### privateStateId[​](#privatestateid-2 "Direct link to privateStateId") `PSI` The private state identifier. ##### state[​](#state "Direct link to state") `PS` The private state to store. #### Returns[​](#returns-10 "Direct link to Returns") `Promise`<`void`> *** ### setContractAddress()[​](#setcontractaddress "Direct link to setContractAddress()") > **setContractAddress**(`address`): `void` Set the contract address for scoping private state operations. Must be called before any get/set/remove operations on private states. This provides namespace isolation between different contracts. #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### address[​](#address-2 "Direct link to address") `string` The contract address to scope operations to. #### Returns[​](#returns-11 "Direct link to Returns") `void` *** ### setSigningKey()[​](#setsigningkey "Direct link to setSigningKey()") > **setSigningKey**(`address`, `signingKey`): `Promise`<`void`> Store the given signing key at the given address. #### Parameters[​](#parameters-10 "Direct link to Parameters") ##### address[​](#address-3 "Direct link to address") `string` The address of the contract having the given signing key. ##### signingKey[​](#signingkey "Direct link to signingKey") `string` The signing key to store. #### Returns[​](#returns-12 "Direct link to Returns") `Promise`<`void`> --- # ProofProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ProofProvider # Interface: ProofProvider Interface for a proof server running in a trusted environment. ## Type Param[​](#type-param "Direct link to Type Param") The type of the circuit ID used by the provider. ## Methods[​](#methods "Direct link to Methods") ### proveTx()[​](#provetx "Direct link to proveTx()") > **proveTx**(`unprovenTx`, `proveTxConfig?`): `Promise`<[`UnboundTransaction`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnboundTransaction.md)> Creates call proofs for an unproven transaction. The resulting transaction is unbalanced and must be balanced using the [WalletProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/WalletProvider.md) interface. contain a single contract call. #### Parameters[​](#parameters "Direct link to Parameters") ##### unprovenTx[​](#unproventx "Direct link to unprovenTx") `UnprovenTransaction` ##### proveTxConfig?[​](#provetxconfig "Direct link to proveTxConfig?") [`ProveTxConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProveTxConfig.md) The configuration for the proof request to the proof provider. Empty in case a deploy transaction is being proved with no user-defined timeout. #### Returns[​](#returns "Direct link to Returns") `Promise`<[`UnboundTransaction`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnboundTransaction.md)> --- # ProveTxConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ProveTxConfig # Interface: ProveTxConfig The configuration for the proof request to the proof provider. ## Properties[​](#properties "Direct link to Properties") ### timeout?[​](#timeout "Direct link to timeout?") > `readonly` `optional` **timeout?**: `number` The timeout for the request. --- # PublicDataProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PublicDataProvider # Interface: PublicDataProvider Interface for a public data service. This service retrieves public data from the blockchain. TODO: Add timeouts or retry limits to 'watchFor' queries. ## Methods[​](#methods "Direct link to Methods") ### contractStateObservable()[​](#contractstateobservable "Direct link to contractStateObservable()") > **contractStateObservable**(`address`, `config`): `Observable`<`ContractState`> Creates a stream of contract states. The observable emits a value every time a state is either created or updated at the given address. Waits indefinitely for matching data to appear. #### Parameters[​](#parameters "Direct link to Parameters") ##### address[​](#address "Direct link to address") `string` The address of the contract of interest. ##### config[​](#config "Direct link to config") [`ContractStateObservableConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractStateObservableConfig.md) The configuration for the observable. #### Returns[​](#returns "Direct link to Returns") `Observable`<`ContractState`> *** ### queryContractState()[​](#querycontractstate "Direct link to queryContractState()") > **queryContractState**(`contractAddress`, `config?`): `Promise`<`ContractState` | `null`> Retrieves the on-chain state of a contract. If no block hash or block height are provided, the contract state at the address in the latest block is returned. Immediately returns null if no matching data is found. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The address of the contract of interest. ##### config?[​](#config-1 "Direct link to config?") [`BlockHeightConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHeightConfig.md) | [`BlockHashConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHashConfig.md) The configuration of the query. If `undefined` returns the latest states. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`ContractState` | `null`> *** ### queryDeployContractState()[​](#querydeploycontractstate "Direct link to queryDeployContractState()") > **queryDeployContractState**(`contractAddress`): `Promise`<`ContractState` | `null`> Retrieves the contract state included in the deployment of the contract at the given contract address. Immediately returns null if no matching data is found. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### contractAddress[​](#contractaddress-1 "Direct link to contractAddress") `string` The address of the contract of interest. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`ContractState` | `null`> *** ### queryUnshieldedBalances()[​](#queryunshieldedbalances "Direct link to queryUnshieldedBalances()") > **queryUnshieldedBalances**(`contractAddress`, `config?`): `Promise`<[`UnshieldedBalances`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md) | `null`> Retrieves the unshielded balances associated with a specific contract address. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### contractAddress[​](#contractaddress-2 "Direct link to contractAddress") `string` The address of the contract of interest. ##### config?[​](#config-2 "Direct link to config?") [`BlockHeightConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHeightConfig.md) | [`BlockHashConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHashConfig.md) The configuration of the query. If `undefined` returns the latest states. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<[`UnshieldedBalances`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md) | `null`> *** ### queryZSwapAndContractState()[​](#queryzswapandcontractstate "Direct link to queryZSwapAndContractState()") > **queryZSwapAndContractState**(`contractAddress`, `config?`): `Promise`<\[`ZswapChainState`, `ContractState`, `LedgerParameters`] | `null`> Retrieves the zswap chain state (token balances), the contract state of the contract at the given address, and the ledger parameters in effect on the associated block. Both states are retrieved in a single query to ensure consistency between the two. Immediately returns null if no matching data is found. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### contractAddress[​](#contractaddress-3 "Direct link to contractAddress") `string` The address of the contract of interest. ##### config?[​](#config-3 "Direct link to config?") [`BlockHeightConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHeightConfig.md) | [`BlockHashConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHashConfig.md) The configuration of the query. If `undefined` returns the latest states. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<\[`ZswapChainState`, `ContractState`, `LedgerParameters`] | `null`> *** ### unshieldedBalancesObservable()[​](#unshieldedbalancesobservable "Direct link to unshieldedBalancesObservable()") > **unshieldedBalancesObservable**(`address`, `config`): `Observable`<[`UnshieldedBalances`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md)> Retrieves an observable that tracks the unshielded balances for a specific contract address. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### address[​](#address-1 "Direct link to address") `string` The contract address for which unshielded balances are being observed. ##### config[​](#config-4 "Direct link to config") [`ContractStateObservableConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractStateObservableConfig.md) The configuration object for observing contract state changes. #### Returns[​](#returns-5 "Direct link to Returns") `Observable`<[`UnshieldedBalances`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md)> An observable that emits the unshielded balances for the provided address. *** ### watchForContractState()[​](#watchforcontractstate "Direct link to watchForContractState()") > **watchForContractState**(`contractAddress`): `Promise`<`ContractState`> Retrieves the contract state of the contract with the given address. Waits indefinitely for matching data to appear. #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### contractAddress[​](#contractaddress-4 "Direct link to contractAddress") `string` The address of the contract of interest. #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<`ContractState`> *** ### watchForDeployTxData()[​](#watchfordeploytxdata "Direct link to watchForDeployTxData()") > **watchForDeployTxData**(`contractAddress`): `Promise`<[`FinalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/FinalizedTxData.md)> Retrieves data of the deployment transaction for the contract at the given contract address. **IMPORTANT: This method waits indefinitely** until the deployment transaction appears on the blockchain. It will never timeout or reject unless an error occurs. Custom implementations MUST maintain this indefinite waiting behavior to ensure consistency across all PublicDataProvider implementations. Do not implement timeouts in this method. #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### contractAddress[​](#contractaddress-5 "Direct link to contractAddress") `string` The address of the contract of interest. #### Returns[​](#returns-7 "Direct link to Returns") `Promise`<[`FinalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/FinalizedTxData.md)> A promise that resolves with finalized transaction data when the deployment appears on-chain. The promise never rejects due to timeout. *** ### watchForTxData()[​](#watchfortxdata "Direct link to watchForTxData()") > **watchForTxData**(`txId`): `Promise`<[`FinalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/FinalizedTxData.md)> Retrieves data of the transaction containing the call or deployment with the given identifier. **IMPORTANT: This method waits indefinitely** until the transaction appears on the blockchain. It will never timeout or reject unless an error occurs. Custom implementations MUST maintain this indefinite waiting behavior to ensure consistency across all PublicDataProvider implementations. Do not implement timeouts in this method. Applications using this method should be aware that: * The promise will not resolve until the transaction appears on-chain * If a transaction is invalid and never appears, this will never return * Consider using application-level timeouts or cancellation mechanisms if needed #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### txId[​](#txid "Direct link to txId") `string` The identifier of the call or deployment of interest. #### Returns[​](#returns-8 "Direct link to Returns") `Promise`<[`FinalizedTxData`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/FinalizedTxData.md)> A promise that resolves with finalized transaction data when the transaction appears on-chain. The promise never rejects due to timeout. *** ### watchForUnshieldedBalances()[​](#watchforunshieldedbalances "Direct link to watchForUnshieldedBalances()") > **watchForUnshieldedBalances**(`contractAddress`): `Promise`<[`UnshieldedBalances`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md)> Monitors for any unshielded balances associated with a specific contract address. #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### contractAddress[​](#contractaddress-6 "Direct link to contractAddress") `string` The address of the contract to monitor for unshielded balances. #### Returns[​](#returns-9 "Direct link to Returns") `Promise`<[`UnshieldedBalances`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalances.md)> A promise that resolves to the detected unshielded balances. --- # SigningKeyExport > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / SigningKeyExport # Interface: SigningKeyExport Represents the exported signing key data structure. All metadata is included in the encrypted payload to prevent tampering. ## Properties[​](#properties "Direct link to Properties") ### encryptedPayload[​](#encryptedpayload "Direct link to encryptedPayload") > `readonly` **encryptedPayload**: `string` Encrypted payload containing version, metadata, and signing keys. Format: base64-encoded AES-256-GCM encrypted JSON. *** ### format[​](#format "Direct link to format") > `readonly` **format**: `"midnight-signing-key-export"` Format identifier. Must be 'midnight-signing-key-export'. *** ### salt[​](#salt "Direct link to salt") > `readonly` **salt**: `string` Salt used for key derivation (hex-encoded, 32 bytes / 64 characters). Required for decryption with the export password. --- # WalletProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / WalletProvider # Interface: WalletProvider Interface representing a WalletProvider that handles operations such as transaction balancing and finalization, and provides access to cryptographic secret keys. ## Methods[​](#methods "Direct link to Methods") ### balanceTx()[​](#balancetx "Direct link to balanceTx()") > **balanceTx**(`tx`, `ttl?`): `Promise`<`FinalizedTransaction`> Balances a transaction #### Parameters[​](#parameters "Direct link to Parameters") ##### tx[​](#tx "Direct link to tx") [`UnboundTransaction`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnboundTransaction.md) The transaction to balance. ##### ttl?[​](#ttl "Direct link to ttl?") `Date` #### Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTransaction`> *** ### getCoinPublicKey()[​](#getcoinpublickey "Direct link to getCoinPublicKey()") > **getCoinPublicKey**(): `string` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### getEncryptionPublicKey()[​](#getencryptionpublickey "Direct link to getEncryptionPublicKey()") > **getEncryptionPublicKey**(): `string` #### Returns[​](#returns-2 "Direct link to Returns") `string` --- # ZKConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ZKConfig # Interface: ZKConfig\ Contains all information required by the [ProofProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/interfaces/ProofProvider.md) ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### K[​](#k "Direct link to K") `K` *extends* `string` The type of the circuit ID. ## Properties[​](#properties "Direct link to Properties") ### circuitId[​](#circuitid "Direct link to circuitId") > `readonly` **circuitId**: `K` A circuit identifier. *** ### proverKey[​](#proverkey "Direct link to proverKey") > `readonly` **proverKey**: [`ProverKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ProverKey.md) The prover key corresponding to [ZKConfig.circuitId](#circuitid). *** ### verifierKey[​](#verifierkey "Direct link to verifierKey") > `readonly` **verifierKey**: [`VerifierKey`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/VerifierKey.md) The verifier key corresponding to [ZKConfig.circuitId](#circuitid). *** ### zkir[​](#zkir "Direct link to zkir") > `readonly` **zkir**: [`ZKIR`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ZKIR.md) The zero-knowledge intermediate representation corresponding to [ZKConfig.circuitId](#circuitid). --- # All > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / All # Type Alias: All > **All** = `object` Streams all previous states of a contract. ## Properties[​](#properties "Direct link to Properties") ### type[​](#type "Direct link to type") > `readonly` **type**: `"all"` --- # AnyPrivateState > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / AnyPrivateState # Type Alias: AnyPrivateState > **AnyPrivateState** = `Contract.PrivateState`<`Contract.Any`> --- # AnyProvableCircuitId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / AnyProvableCircuitId # Type Alias: AnyProvableCircuitId > **AnyProvableCircuitId** = `Contract.ProvableCircuitId`<`Contract.Any`> --- # BlockHash > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / BlockHash # Type Alias: BlockHash > **BlockHash** = `string` Block identifier --- # BlockHashConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / BlockHashConfig # Type Alias: BlockHashConfig > **BlockHashConfig** = `object` Starts a contract state stream at the given block hash. ## Properties[​](#properties "Direct link to Properties") ### blockHash[​](#blockhash "Direct link to blockHash") > `readonly` **blockHash**: `string` The block height indicating where to begin the state stream. *** ### type[​](#type "Direct link to type") > `readonly` **type**: `"blockHash"` --- # BlockHeightConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / BlockHeightConfig # Type Alias: BlockHeightConfig > **BlockHeightConfig** = `object` Starts a contract state stream at the given block height. ## Properties[​](#properties "Direct link to Properties") ### blockHeight[​](#blockheight "Direct link to blockHeight") > `readonly` **blockHeight**: `number` The block height indicating where to begin the state stream. *** ### type[​](#type "Direct link to type") > `readonly` **type**: `"blockHeight"` --- # ContractExecutableRuntimeOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ContractExecutableRuntimeOptions # Type Alias: ContractExecutableRuntimeOptions > **ContractExecutableRuntimeOptions** = `object` Options for use when constructing a Compact.js contract executable runtime. ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") > `readonly` **coinPublicKey**: `string` The current user's ZSwap public key. *** ### signingKey?[​](#signingkey "Direct link to signingKey?") > `readonly` `optional` **signingKey?**: `string` The signing key to add as the to-be-deployed contract's maintenance authority. --- # ContractStateObservableConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ContractStateObservableConfig # Type Alias: ContractStateObservableConfig > **ContractStateObservableConfig** = [`TxIdConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/TxIdConfig.md) | [`BlockHashConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHashConfig.md) | [`BlockHeightConfig`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/BlockHeightConfig.md) & `object` | [`Latest`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/Latest.md) | [`All`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/All.md) The configuration for a contract state observable. The corresponding observables may begin at different places (e.g. after a specific transaction identifier / block height) depending on the configuration, but all state updates after the beginning are always included. --- # Fees > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / Fees # Type Alias: Fees > **Fees** = `object` Represents the fees associated with a particular entity or operation. This type includes both the paid fees and the estimated fees. The paid fees represent the amount that has already been settled, while the estimated fees provide a calculation or projection of expected fees. ## Properties[​](#properties "Direct link to Properties") ### estimatedFees[​](#estimatedfees "Direct link to estimatedFees") > `readonly` **estimatedFees**: `string` The estimated fees that are expected to be incurred. *** ### paidFees[​](#paidfees "Direct link to paidFees") > `readonly` **paidFees**: `string` The fees that have already been paid. --- # KeyMaterialProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / KeyMaterialProvider # Type Alias: KeyMaterialProvider > **KeyMaterialProvider** = `object` DApp connector API type for key material retrieval ## Methods[​](#methods "Direct link to Methods") ### getProverKey()[​](#getproverkey "Direct link to getProverKey()") > **getProverKey**(`circuitKeyLocation`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters "Direct link to Parameters") ##### circuitKeyLocation[​](#circuitkeylocation "Direct link to circuitKeyLocation") `string` #### Returns[​](#returns "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> *** ### getVerifierKey()[​](#getverifierkey "Direct link to getVerifierKey()") > **getVerifierKey**(`circuitKeyLocation`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### circuitKeyLocation[​](#circuitkeylocation-1 "Direct link to circuitKeyLocation") `string` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> *** ### getZKIR()[​](#getzkir "Direct link to getZKIR()") > **getZKIR**(`circuitKeyLocation`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### circuitKeyLocation[​](#circuitkeylocation-2 "Direct link to circuitKeyLocation") `string` #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> --- # Latest > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / Latest # Type Alias: Latest > **Latest** = `object` Streams all states of a contract starting with the most recent. ## Properties[​](#properties "Direct link to Properties") ### type[​](#type "Direct link to type") > `readonly` **type**: `"latest"` --- # PrivateStateId > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PrivateStateId # Type Alias: PrivateStateId > **PrivateStateId** = `string` A type representing an ID used to store a contract's private state. --- # PrivateStateImportErrorCause > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / PrivateStateImportErrorCause # Type Alias: PrivateStateImportErrorCause > **PrivateStateImportErrorCause** = `"decryption_failed"` | `"invalid_format"` | `"conflict"` | `"unknown"` Cause types for private state import errors. --- # ProverKey > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ProverKey # Type Alias: ProverKey > **ProverKey** = `Uint8Array` & `object` A type representing a prover key derived from a contract circuit. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### ProverKey[​](#proverkey "Direct link to ProverKey") > `readonly` **ProverKey**: unique `symbol` Unique symbol brand. --- # SegmentStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / SegmentStatus # Type Alias: SegmentStatus > **SegmentStatus** = *typeof* [`SegmentSuccess`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SegmentSuccess.md) | *typeof* [`SegmentFail`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SegmentFail.md) Represents the result of a segment operation, which can either be a successful operation (`SegmentSuccess`) or a failed operation (`SegmentFail`). --- # TxIdConfig > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / TxIdConfig # Type Alias: TxIdConfig > **TxIdConfig** = `object` Starts a contract state stream at the given transaction identifier. ## Properties[​](#properties "Direct link to Properties") ### txId[​](#txid "Direct link to txId") > `readonly` **txId**: `TransactionId` The transaction identifier indicating where to begin the state stream. *** ### type[​](#type "Direct link to type") > `readonly` **type**: `"txId"` --- # TxStatus > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / TxStatus # Type Alias: TxStatus > **TxStatus** = *typeof* [`FailEntirely`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/FailEntirely.md) | *typeof* [`FailFallible`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/FailFallible.md) | *typeof* [`SucceedEntirely`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/variables/SucceedEntirely.md) The status of a transaction. --- # UnboundTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / UnboundTransaction # Type Alias: UnboundTransaction > **UnboundTransaction** = `Transaction`<`SignatureEnabled`, `Proof`, `PreBinding`> --- # UnshieldedBalance > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / UnshieldedBalance # Type Alias: UnshieldedBalance > **UnshieldedBalance** = `object` Represents an unshielded balance, which is a balance that is not shielded or encrypted. This type is used to track the available funds in an account that are visible on the public ledger. ## Properties[​](#properties "Direct link to Properties") ### balance[​](#balance "Direct link to balance") > `readonly` **balance**: `bigint` Represents the current number of funds available or held in an account. *** ### tokenType[​](#tokentype "Direct link to tokenType") > `readonly` **tokenType**: `RawTokenType` Represents the type of token in the system. --- # UnshieldedBalances > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / UnshieldedBalances # Type Alias: UnshieldedBalances > **UnshieldedBalances** = [`UnshieldedBalance`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedBalance.md)\[] Represents a collection of unshielded balances, which are balances that are not shielded or encrypted. --- # UnshieldedUtxo > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / UnshieldedUtxo # Type Alias: UnshieldedUtxo > **UnshieldedUtxo** = `object` Represents an unshielded UTXO (Unspent Transaction Output). Unshielded UTXOs are outputs that have not been shielded or encrypted, making them visible on the public ledger. ## Properties[​](#properties "Direct link to Properties") ### intentHash[​](#intenthash "Direct link to intentHash") > `readonly` **intentHash**: `IntentHash` The identifier of the intent associated with the unshielded UTXO. This is used to track the intent behind the creation or use of the UTXO. *** ### owner[​](#owner "Direct link to owner") > `readonly` **owner**: `ContractAddress` The unique identifier of the unshielded UTXO. *** ### tokenType[​](#tokentype "Direct link to tokenType") > `readonly` **tokenType**: `RawTokenType` The type of token associated with the unshielded UTXO. This indicates the kind of asset or currency represented by the UTXO. *** ### value[​](#value "Direct link to value") > `readonly` **value**: `bigint` The value of the unshielded UTXO, represented as a bigint. --- # UnshieldedUtxos > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / UnshieldedUtxos # Type Alias: UnshieldedUtxos > **UnshieldedUtxos** = `object` Represents a collection of unshielded UTXOs, which are unspent transaction outputs that are not shielded. This type is used to manage and track the state of unshielded UTXOs. ## Properties[​](#properties "Direct link to Properties") ### created[​](#created "Direct link to created") > `readonly` **created**: readonly [`UnshieldedUtxo`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxo.md)\[] Represents the unshielded UTXOs that have been created but not yet spent. *** ### spent[​](#spent "Direct link to spent") > `readonly` **spent**: readonly [`UnshieldedUtxo`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/UnshieldedUtxo.md)\[] Represents the unshielded UTXOs that have been spent. --- # VerifierKey > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / VerifierKey # Type Alias: VerifierKey > **VerifierKey** = `Uint8Array` & `object` A type representing a verifier key derived from a contract circuit. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### VerifierKey[​](#verifierkey "Direct link to VerifierKey") > `readonly` **VerifierKey**: unique `symbol` Unique symbol brand. --- # ZKIR > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / ZKIR # Type Alias: ZKIR > **ZKIR** = `Uint8Array` & `object` A type representing a zero-knowledge circuit intermediate representation derived from a contract circuit. ## Type Declaration[​](#type-declaration "Direct link to Type Declaration") ### ZKIR[​](#zkir "Direct link to ZKIR") > `readonly` **ZKIR**: unique `symbol` Unique symbol brand. --- # exitResultOrError > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / exitResultOrError # Variable: exitResultOrError > `const` **exitResultOrError**: <`A`, `E`>(`exit`) => `A` Unwraps an Effect `Exit` instance, returning its value if it is successful, or throwing the error contained within it. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ### E[​](#e "Direct link to E") `E` ## Parameters[​](#parameters "Direct link to Parameters") ### exit[​](#exit "Direct link to exit") `Exit.Exit`<`A`, `E`> The source Effect `Exit` instance. ## Returns[​](#returns "Direct link to Returns") `A` The value from `exit` if it is successful, otherwise throws the error contained within it. --- # FailEntirely > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / FailEntirely # Variable: FailEntirely > `const` **FailEntirely**: `"FailEntirely"` Indicates that the transaction is invalid. --- # FailFallible > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / FailFallible # Variable: FailFallible > `const` **FailFallible**: `"FailFallible"` Indicates that the transaction is valid but the portion of the transcript that is allowed to fail (the portion after a checkpoint) did fail. All effects from the guaranteed part of the transaction are kept but the effects from the fallible part of the transaction are discarded. --- # makeContractExecutableRuntime > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / makeContractExecutableRuntime # Variable: makeContractExecutableRuntime > `const` **makeContractExecutableRuntime**: (`zkConfigProvider`, `options`) => [`ManagedRuntime`](#)<`ContractExecutable.ContractExecutable.Context`, `ConfigError.ConfigError`> Constructs an Effect managed runtime configured to execute contract executables. ## Parameters[​](#parameters "Direct link to Parameters") ### zkConfigProvider[​](#zkconfigprovider "Direct link to zkConfigProvider") [`ZKConfigProvider`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ZKConfigProvider.md)<`string`> The [ZKConfigProvider](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/classes/ZKConfigProvider.md) that is to be adapted. ### options[​](#options "Direct link to options") [`ContractExecutableRuntimeOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types/type-aliases/ContractExecutableRuntimeOptions.md) Values that will be mapped into and made available within the constructed runtime. ## Returns[​](#returns "Direct link to Returns") [`ManagedRuntime`](#)<`ContractExecutable.ContractExecutable.Context`, `ConfigError.ConfigError`> An Effect [ManagedRuntime](#) that can be used to execute [ContractExecutable](#) instances. --- # MAX\_EXPORT\_SIGNING\_KEYS > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / MAX\_EXPORT\_SIGNING\_KEYS # Variable: MAX\_EXPORT\_SIGNING\_KEYS > `const` **MAX\_EXPORT\_SIGNING\_KEYS**: `10000` = `10000` Maximum number of signing keys that can be exported/imported. This limit prevents memory exhaustion attacks. --- # MAX\_EXPORT\_STATES > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / MAX\_EXPORT\_STATES # Variable: MAX\_EXPORT\_STATES > `const` **MAX\_EXPORT\_STATES**: `10000` = `10000` Maximum number of states that can be exported/imported. This limit prevents memory exhaustion attacks. --- # SegmentFail > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / SegmentFail # Variable: SegmentFail > `const` **SegmentFail**: `"SegmentFail"` Indicates that the segment update is invalid. --- # SegmentSuccess > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / SegmentSuccess # Variable: SegmentSuccess > `const` **SegmentSuccess**: `"SegmentSuccess"` Indicates that the segment is valid. --- # SucceedEntirely > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-types](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) / SucceedEntirely # Variable: SucceedEntirely > `const` **SucceedEntirely**: `"SucceedEntirely"` Indicates that the guaranteed and fallible portions of the transaction were successful. --- > For the complete documentation index, see [llms.txt](/llms.txt) # midnight-js-utils [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / @midnight-ntwrk/midnight-js-utils # @midnight-ntwrk/midnight-js-utils ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [ParsedHexString](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/type-aliases/ParsedHexString.md) ## Variables[​](#variables "Direct link to Variables") * [MAX\_SAFE\_NAME\_LENGTH](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/variables/MAX_SAFE_NAME_LENGTH.md) ## Functions[​](#functions "Direct link to Functions") * [assertDefined](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertDefined.md) * [assertIsContractAddress](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertIsContractAddress.md) * [assertIsHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertIsHex.md) * [assertSafeName](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertSafeName.md) * [assertSemVer](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertSemVer.md) * [assertUndefined](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/assertUndefined.md) * [fromHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/fromHex.md) * [isHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/isHex.md) * [parseCoinPublicKeyToHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/parseCoinPublicKeyToHex.md) * [parseEncPublicKeyToHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/parseEncPublicKeyToHex.md) * [parseHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/parseHex.md) * [toHex](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/toHex.md) * [ttlOneHour](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/functions/ttlOneHour.md) --- # assertDefined > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / assertDefined # Function: assertDefined() > **assertDefined**<`A`>(`value`, `message?`): `asserts value is NonNullable` Asserts that the given value is non-nullable. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### value[​](#value "Direct link to value") `A` | `null` | `undefined` The value to test for nullability. ### message?[​](#message "Direct link to message?") `string` The error message to use if an error is thrown. ## Returns[​](#returns "Direct link to Returns") `asserts value is NonNullable` ## Throws[​](#throws "Direct link to Throws") Error If the value is nullable. --- # assertIsContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / assertIsContractAddress # Function: assertIsContractAddress() > **assertIsContractAddress**(`contractAddress`): `asserts contractAddress is string` **`Internal`** Asserts that a string represents a hex-encoded contract address. ## Parameters[​](#parameters "Direct link to Parameters") ### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` The source string. ## Returns[​](#returns "Direct link to Returns") `asserts contractAddress is string` ## Throws[​](#throws "Direct link to Throws") `TypeError` `contractAddress` is not a correctly formatted [ContractAddress](#). --- # assertIsHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / assertIsHex # Function: assertIsHex() > **assertIsHex**(`source`, `byteLen?`): `asserts source is string` Asserts that a string represents a hex-encoded sequence of bytes. ## Parameters[​](#parameters "Direct link to Parameters") ### source[​](#source "Direct link to source") `string` The source string. ### byteLen?[​](#bytelen "Direct link to byteLen?") `number` An optional number of bytes that `source` should represent. If not specified then any number of bytes can be represented by `source`. ## Returns[​](#returns "Direct link to Returns") `asserts source is string` ## Throws[​](#throws "Direct link to Throws") `Error` `byteLen` is <= zero. Valid hex-strings will be required to have at least one byte. ## Throws[​](#throws-1 "Direct link to Throws") `TypeError` `source` is not a hex-encoded string because it: * is empty, * contains invalid or incomplete characters, or * does not represent `byteLen` bytes. --- # assertSafeName > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / assertSafeName # Function: assertSafeName() > **assertSafeName**(`name`, `label`): `void` Asserts that `name` is safe to use as a single path segment or URL path component. Rejects traversal payloads (`.`, `..`, separators), URL-encoded characters, null bytes, whitespace, empty strings, and names longer than [MAX\_SAFE\_NAME\_LENGTH](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/variables/MAX_SAFE_NAME_LENGTH.md). ## Parameters[​](#parameters "Direct link to Parameters") ### name[​](#name "Direct link to name") `string` The value to validate. ### label[​](#label "Direct link to label") `string` Human-readable name of the parameter (for error messages). ## Returns[​](#returns "Direct link to Returns") `void` ## Throws[​](#throws "Direct link to Throws") Error if `name` fails validation. --- # assertSemVer > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / assertSemVer # Function: assertSemVer() > **assertSemVer**(`version`, `label`): `void` Asserts that `version` is a valid SemVer-style version string of the shape `MAJOR.MINOR.PATCH` with an optional pre-release suffix (`-[A-Za-z0-9._-]+`). Build metadata (`+...`) is intentionally not supported because compactc releases do not use it. ## Parameters[​](#parameters "Direct link to Parameters") ### version[​](#version "Direct link to version") `string` The version string to validate. ### label[​](#label "Direct link to label") `string` Human-readable name of the parameter (for error messages). ## Returns[​](#returns "Direct link to Returns") `void` ## Throws[​](#throws "Direct link to Throws") Error if `version` is not SemVer-shaped. --- # assertUndefined > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / assertUndefined # Function: assertUndefined() > **assertUndefined**<`A`>(`value`, `message?`): asserts value is null | undefined Asserts that the given value is null or undefined. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### A[​](#a "Direct link to A") `A` ## Parameters[​](#parameters "Direct link to Parameters") ### value[​](#value "Direct link to value") `A` | `null` | `undefined` The value to test for nullability. ### message?[​](#message "Direct link to message?") `string` The error message to use if an error is thrown. ## Returns[​](#returns "Direct link to Returns") asserts value is null | undefined ## Throws[​](#throws "Direct link to Throws") Error If the value is not undefined or null --- # fromHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / fromHex # Function: fromHex() > **fromHex**(`str`): `Buffer` Converts a hex string into a byte string. ## Parameters[​](#parameters "Direct link to Parameters") ### str[​](#str "Direct link to str") `string` The hex string to decode. ## Returns[​](#returns "Direct link to Returns") `Buffer` --- # isHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / isHex # Function: isHex() > **isHex**(`source`, `byteLen?`): `boolean` Determines if a string represents a hex-encoded sequence of bytes. ## Parameters[​](#parameters "Direct link to Parameters") ### source[​](#source "Direct link to source") `string` The source string. ### byteLen?[​](#bytelen "Direct link to byteLen?") `number` An optional number of bytes that `source` should represent. If not specified then any number of bytes can be represented by `source`. ## Returns[​](#returns "Direct link to Returns") `boolean` `true` if the `source` string is parsable as a hex-string, of non-zero length, and of the optional byte length of `byteLen`; otherwise `false`. --- # parseCoinPublicKeyToHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / parseCoinPublicKeyToHex # Function: parseCoinPublicKeyToHex() > **parseCoinPublicKeyToHex**(`possibleBech32`, `zswapNetworkId`): `string` Parses a coin public key (in Bech32m format or hex) into a hex formatted string. ## Parameters[​](#parameters "Direct link to Parameters") ### possibleBech32[​](#possiblebech32 "Direct link to possibleBech32") `string` The input string, which can be a Bech32m-encoded coin public key or a hex string. ### zswapNetworkId[​](#zswapnetworkid "Direct link to zswapNetworkId") `string` The network ID used for decoding the Bech32m formatted string. ## Returns[​](#returns "Direct link to Returns") `string` The hex string representation of the coin public key. ## Throws[​](#throws "Direct link to Throws") `Error` If the input string is not a valid hex string or a valid Bech32m-encoded coin public key. --- # parseEncPublicKeyToHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / parseEncPublicKeyToHex # Function: parseEncPublicKeyToHex() > **parseEncPublicKeyToHex**(`possibleBech32`, `zswapNetworkId`): `string` Parses an encryption public key (in Bech32m or hex format) into a hex formatted string. ## Parameters[​](#parameters "Direct link to Parameters") ### possibleBech32[​](#possiblebech32 "Direct link to possibleBech32") `string` The input string, which can be a Bech32m-encoded encryption public key or a hex string. ### zswapNetworkId[​](#zswapnetworkid "Direct link to zswapNetworkId") `string` The network ID used for decoding the Bech32m formatted string. ## Returns[​](#returns "Direct link to Returns") `string` The hex string representation of the encryption public key. ## Throws[​](#throws "Direct link to Throws") `Error` If the input string is not a valid hex string or a valid Bech32m-encoded encryption public key. --- # parseHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / parseHex # Function: parseHex() > **parseHex**(`source`): [`ParsedHexString`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/type-aliases/ParsedHexString.md) Parses a string as a hex-encoded string. ## Parameters[​](#parameters "Direct link to Parameters") ### source[​](#source "Direct link to source") `string` The source string to parse. ## Returns[​](#returns "Direct link to Returns") [`ParsedHexString`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/type-aliases/ParsedHexString.md) A [ParsedHexString](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils/type-aliases/ParsedHexString.md) describing the parsed elements of `source`. ## Examples[​](#examples "Direct link to Examples") ``` parseHex('Hello') => { hasPrefix: false, incompleteChars: 'Hello' } ``` ``` parseHex('ab12e') => { hasPrefix: false, byteChars: 'ab12' incompleteChars: 'e' } ``` ``` parseHex('0xab12') => { hasPrefix: true, byteChars: 'ab12' incompleteChars: '' } ``` --- # toHex > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / toHex # Function: toHex() > **toHex**(`bytes`): `string` Converts a byte string into a hex string. ## Parameters[​](#parameters "Direct link to Parameters") ### bytes[​](#bytes "Direct link to bytes") `Uint8Array` The byte string to encode. ## Returns[​](#returns "Direct link to Returns") `string` --- # ttlOneHour > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / ttlOneHour # Function: ttlOneHour() > **ttlOneHour**(): `Date` ## Returns[​](#returns "Direct link to Returns") `Date` --- # ParsedHexString > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / ParsedHexString # Type Alias: ParsedHexString > **ParsedHexString** = `object` The result of parsing a string as a hex-encoded string. ## Properties[​](#properties "Direct link to Properties") ### byteChars[​](#bytechars "Direct link to byteChars") > `readonly` **byteChars**: `string` The captured sequence of *whole* bytes found in the source string. *** ### hasPrefix[​](#hasprefix "Direct link to hasPrefix") > `readonly` **hasPrefix**: `boolean` A flag indicating if the hex-string has a `'0x'` prefix. *** ### incompleteChars[​](#incompletechars "Direct link to incompleteChars") > `readonly` **incompleteChars**: `string` The remaining characters of incomplete bytes and/or the non hexadecimal characters found in the source string. --- # MAX\_SAFE\_NAME\_LENGTH > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** [Midnight.js API Reference](/api-reference/midnight-js/packages.md) / [@midnight-ntwrk/midnight-js-utils](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) / MAX\_SAFE\_NAME\_LENGTH # Variable: MAX\_SAFE\_NAME\_LENGTH > `const` **MAX\_SAFE\_NAME\_LENGTH**: `255` = `255` --- # packages > For the complete documentation index, see [llms.txt](/llms.txt) [**Midnight.js API Reference v4.0.4**](/api-reference/midnight-js.md) *** # Midnight.js API Reference v4.0.4 ## Packages[​](#packages "Direct link to Packages") * [@midnight-ntwrk/midnight-js](/api-reference/midnight-js/@midnight-ntwrk/midnight-js.md) * [@midnight-ntwrk/midnight-js-contracts - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts.md) * [@midnight-ntwrk/midnight-js-dapp-connector-proof-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-dapp-connector-proof-provider.md) * [@midnight-ntwrk/midnight-js-fetch-zk-config-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-fetch-zk-config-provider.md) * [@midnight-ntwrk/midnight-js-http-client-proof-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-http-client-proof-provider.md) * [@midnight-ntwrk/midnight-js-indexer-public-data-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-indexer-public-data-provider.md) * [@midnight-ntwrk/midnight-js-level-private-state-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-level-private-state-provider.md) * [@midnight-ntwrk/midnight-js-logger-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-logger-provider.md) * [@midnight-ntwrk/midnight-js-network-id - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-network-id.md) * [@midnight-ntwrk/midnight-js-node-zk-config-provider - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-node-zk-config-provider.md) * [@midnight-ntwrk/midnight-js-protocol](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-protocol.md) * [@midnight-ntwrk/midnight-js-types - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-types.md) * [@midnight-ntwrk/midnight-js-utils - v4.0.4](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-utils.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Onchain Runtime API **@midnight-ntwrk/onchain-runtime v3.0.0** *** # Midnight Onchain Runtime TypeScript API This API provides a TypeScript interface to Midnight's onchain runtime, including the execution of VM instructions, and the primitives required to successfully use them. Key parts of this API are: * [ContractState](/api-reference/onchain-runtime/classes/ContractState.md), encapsulating the entirety of a smart contract's on-chain state * [StateValue](/api-reference/onchain-runtime/classes/StateValue.md), encoding data a contract maintains on-chain * [QueryContext](/api-reference/onchain-runtime/classes/QueryContext.md), providing an annotated view into the contract state, against which on-chain VM programs can be run * [Op](/api-reference/onchain-runtime/type-aliases/Op.md), providing the TypeScript encoding of on-chain VM programs * [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md), the "base" value type that encodes all user data stored on-chain --- # ChargedState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ChargedState # Class: ChargedState Represents a [StateValue](/api-reference/onchain-runtime/classes/StateValue.md) with storage annotations. These track the state usage that has been charged for so far. ## Constructors[​](#constructors "Direct link to Constructors") ### new ChargedState()[​](#new-chargedstate "Direct link to new ChargedState()") ``` new ChargedState(state): ChargedState ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) #### Returns[​](#returns "Direct link to Returns") [`ChargedState`](/api-reference/onchain-runtime/classes/ChargedState.md) ## Properties[​](#properties "Direct link to Properties") ### state[​](#state-1 "Direct link to state") ``` readonly state: StateValue; ``` ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` --- # CoinSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CoinSecretKey # Class: CoinSecretKey Holds the coin secret key of a user, serialized as a hex-encoded 32-byte string ## Methods[​](#methods "Direct link to Methods") ### clear()[​](#clear "Direct link to clear()") ``` clear(): void ``` Clears the coin secret key, so that it is no longer usable nor held in memory #### Returns[​](#returns "Direct link to Returns") `void` *** ### yesIKnowTheSecurityImplicationsOfThis\_serialize()[​](#yesiknowthesecurityimplicationsofthis_serialize "Direct link to yesIKnowTheSecurityImplicationsOfThis_serialize()") ``` yesIKnowTheSecurityImplicationsOfThis_serialize(): Uint8Array ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): CoinSecretKey ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") [`CoinSecretKey`](/api-reference/onchain-runtime/classes/CoinSecretKey.md) --- # ContractMaintenanceAuthority > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ContractMaintenanceAuthority # Class: ContractMaintenanceAuthority A committee permitted to make changes to this contract. If a threshold of the public keys in this committee sign off, they can change the rules of this contract, or recompile it for a new version. If the threshold is greater than the number of committee members, it is impossible for them to sign anything. ## Constructors[​](#constructors "Direct link to Constructors") ### new ContractMaintenanceAuthority()[​](#new-contractmaintenanceauthority "Direct link to new ContractMaintenanceAuthority()") ``` new ContractMaintenanceAuthority( committee, threshold, counter?): ContractMaintenanceAuthority ``` Constructs a new authority from its components If not supplied, `counter` will default to `0n`. Values should be non-negative, and at most 2^32 - 1. At deployment, `counter` must be `0n`, and any subsequent update should set counter to exactly one greater than the current value. #### Parameters[​](#parameters "Direct link to Parameters") ##### committee[​](#committee "Direct link to committee") `string`\[] ##### threshold[​](#threshold "Direct link to threshold") `number` ##### counter?[​](#counter "Direct link to counter?") `bigint` #### Returns[​](#returns "Direct link to Returns") [`ContractMaintenanceAuthority`](/api-reference/onchain-runtime/classes/ContractMaintenanceAuthority.md) ## Properties[​](#properties "Direct link to Properties") ### committee[​](#committee-1 "Direct link to committee") ``` readonly committee: string[]; ``` The committee public keys *** ### counter[​](#counter-1 "Direct link to counter") ``` readonly counter: bigint; ``` The replay protection counter *** ### threshold[​](#threshold-1 "Direct link to threshold") ``` readonly threshold: number; ``` How many keys must sign rule changes ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractState ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") [`ContractState`](/api-reference/onchain-runtime/classes/ContractState.md) --- # ContractOperation > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ContractOperation # Class: ContractOperation An individual operation, or entry point of a contract, consisting primarily of a ZK verifier keys, potentially for different versions of the proving system. Only the latest available version is exposed to this API. Note that the serialized form of the key is checked on initialization ## Constructors[​](#constructors "Direct link to Constructors") ### new ContractOperation()[​](#new-contractoperation "Direct link to new ContractOperation()") ``` new ContractOperation(): ContractOperation ``` #### Returns[​](#returns "Direct link to Returns") [`ContractOperation`](/api-reference/onchain-runtime/classes/ContractOperation.md) ## Properties[​](#properties "Direct link to Properties") ### verifierKey[​](#verifierkey "Direct link to verifierKey") ``` verifierKey: Uint8Array; ``` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array ``` #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractOperation ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-3 "Direct link to Returns") [`ContractOperation`](/api-reference/onchain-runtime/classes/ContractOperation.md) --- # ContractState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ContractState # Class: ContractState The state of a contract, consisting primarily of the [data](/api-reference/onchain-runtime/classes/ContractState.md#data) accessible directly to the contract, and the map of [ContractOperation](/api-reference/onchain-runtime/classes/ContractOperation.md)s that can be called on it, the keys of which can be accessed with [operations](/api-reference/onchain-runtime/classes/ContractState.md#operations), and the individual operations can be read with [operation](/api-reference/onchain-runtime/classes/ContractState.md#operation) and written to with [setOperation](/api-reference/onchain-runtime/classes/ContractState.md#setoperation). ## Constructors[​](#constructors "Direct link to Constructors") ### new ContractState()[​](#new-contractstate "Direct link to new ContractState()") ``` new ContractState(): ContractState ``` Creates a blank contract state #### Returns[​](#returns "Direct link to Returns") [`ContractState`](/api-reference/onchain-runtime/classes/ContractState.md) ## Properties[​](#properties "Direct link to Properties") ### balance[​](#balance "Direct link to balance") ``` balance: Map; ``` The public balances held by this contract *** ### data[​](#data "Direct link to data") ``` data: ChargedState; ``` The current value of the primary state of the contract *** ### maintenanceAuthority[​](#maintenanceauthority "Direct link to maintenanceAuthority") ``` maintenanceAuthority: ContractMaintenanceAuthority; ``` The maintenance authority associated with this contract ## Methods[​](#methods "Direct link to Methods") ### operation()[​](#operation "Direct link to operation()") ``` operation(operation): undefined | ContractOperation ``` Get the operation at a specific entry point name #### Parameters[​](#parameters "Direct link to Parameters") ##### operation[​](#operation-1 "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`ContractOperation`](/api-reference/onchain-runtime/classes/ContractOperation.md) *** ### operations()[​](#operations "Direct link to operations()") ``` operations(): (string | Uint8Array)[] ``` Return a list of the entry points currently registered on this contract #### Returns[​](#returns-2 "Direct link to Returns") (`string` | `Uint8Array`<`ArrayBufferLike`>)\[] *** ### query()[​](#query "Direct link to query()") ``` query(query, cost_model): GatherResult[] ``` Runs a series of operations against the current state, and returns the results #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### query[​](#query-1 "Direct link to query") [`Op`](/api-reference/onchain-runtime/type-aliases/Op.md)<`null`>\[] ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/onchain-runtime/classes/CostModel.md) #### Returns[​](#returns-3 "Direct link to Returns") [`GatherResult`](/api-reference/onchain-runtime/type-aliases/GatherResult.md)\[] *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(): Uint8Array ``` #### Returns[​](#returns-4 "Direct link to Returns") `Uint8Array` *** ### setOperation()[​](#setoperation "Direct link to setOperation()") ``` setOperation(operation, value): void ``` Set a specific entry point name to contain a given operation #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### operation[​](#operation-2 "Direct link to operation") `string` | `Uint8Array`<`ArrayBufferLike`> ##### value[​](#value "Direct link to value") [`ContractOperation`](/api-reference/onchain-runtime/classes/ContractOperation.md) #### Returns[​](#returns-5 "Direct link to Returns") `void` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw): ContractState ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array` #### Returns[​](#returns-7 "Direct link to Returns") [`ContractState`](/api-reference/onchain-runtime/classes/ContractState.md) --- # CostModel > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CostModel # Class: CostModel A cost model for calculating transaction fees ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` *** ### initialCostModel()[​](#initialcostmodel "Direct link to initialCostModel()") ``` static initialCostModel(): CostModel ``` The initial cost model of Midnight #### Returns[​](#returns-1 "Direct link to Returns") [`CostModel`](/api-reference/onchain-runtime/classes/CostModel.md) --- # QueryContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / QueryContext # Class: QueryContext Provides the information needed to fully process a transaction, including information about the rest of the transaction, and the state of the chain at the time of execution. ## Constructors[​](#constructors "Direct link to Constructors") ### new QueryContext()[​](#new-querycontext "Direct link to new QueryContext()") ``` new QueryContext(state, address): QueryContext ``` Construct a basic context from a contract's address and current state value #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`ChargedState`](/api-reference/onchain-runtime/classes/ChargedState.md) ##### address[​](#address "Direct link to address") `string` #### Returns[​](#returns "Direct link to Returns") [`QueryContext`](/api-reference/onchain-runtime/classes/QueryContext.md) ## Properties[​](#properties "Direct link to Properties") ### address[​](#address-1 "Direct link to address") ``` readonly address: string; ``` The address of the contract *** ### block[​](#block "Direct link to block") ``` block: CallContext; ``` The block-level information accessible to the contract *** ### comIndices[​](#comindices "Direct link to comIndices") ``` readonly comIndices: Map; ``` The commitment indices map accessible to the contract, primarily via [qualify](/api-reference/onchain-runtime/classes/QueryContext.md#qualify) *** ### effects[​](#effects "Direct link to effects") ``` effects: Effects; ``` The effects that occurred during execution against this context, should match those declared in a [Transcript](/api-reference/onchain-runtime/type-aliases/Transcript.md) *** ### state[​](#state-1 "Direct link to state") ``` readonly state: ChargedState; ``` The current contract state retained in the context ## Methods[​](#methods "Direct link to Methods") ### insertCommitment()[​](#insertcommitment "Direct link to insertCommitment()") ``` insertCommitment(comm, index): QueryContext ``` Register a given coin commitment as being accessible at a specific index, for use when receiving coins in-contract, and needing to record their index to later spend them #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### comm[​](#comm "Direct link to comm") `string` ##### index[​](#index "Direct link to index") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") [`QueryContext`](/api-reference/onchain-runtime/classes/QueryContext.md) *** ### qualify()[​](#qualify "Direct link to qualify()") ``` qualify(coin): undefined | Value ``` **`Internal`** Internal counterpart to [insertCommitment](/api-reference/onchain-runtime/classes/QueryContext.md#insertcommitment); upgrades an encoded [ShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md) to an encoded [QualifiedShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md) using the inserted commitments #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) *** ### query()[​](#query "Direct link to query()") ``` query( ops, cost_model, gas_limit?): QueryResults ``` Runs a sequence of operations in gather mode, returning the results of the gather. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### ops[​](#ops "Direct link to ops") [`Op`](/api-reference/onchain-runtime/type-aliases/Op.md)<`null`>\[] ##### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/onchain-runtime/classes/CostModel.md) ##### gas\_limit?[​](#gas_limit "Direct link to gas_limit?") [`RunningCost`](/api-reference/onchain-runtime/type-aliases/RunningCost.md) #### Returns[​](#returns-3 "Direct link to Returns") [`QueryResults`](/api-reference/onchain-runtime/classes/QueryResults.md) *** ### runTranscript()[​](#runtranscript "Direct link to runTranscript()") ``` runTranscript(transcript, cost_model): QueryContext ``` Runs a transcript in verifying mode against the current query context, outputting a new query context, with the [state](/api-reference/onchain-runtime/classes/QueryContext.md#state-1) and [effects](/api-reference/onchain-runtime/classes/QueryContext.md#effects) from after the execution. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### transcript[​](#transcript "Direct link to transcript") [`Transcript`](/api-reference/onchain-runtime/type-aliases/Transcript.md)<[`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)> ##### cost\_model[​](#cost_model-1 "Direct link to cost_model") [`CostModel`](/api-reference/onchain-runtime/classes/CostModel.md) #### Returns[​](#returns-4 "Direct link to Returns") [`QueryContext`](/api-reference/onchain-runtime/classes/QueryContext.md) *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` *** ### toVmStack()[​](#tovmstack "Direct link to toVmStack()") ``` toVmStack(): VmStack ``` Converts the QueryContext to [VmStack](/api-reference/onchain-runtime/classes/VmStack.md). #### Returns[​](#returns-6 "Direct link to Returns") [`VmStack`](/api-reference/onchain-runtime/classes/VmStack.md) --- # QueryResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / QueryResults # Class: QueryResults The results of making a query against a specific state or context ## Properties[​](#properties "Direct link to Properties") ### context[​](#context "Direct link to context") ``` readonly context: QueryContext; ``` The context state after executing the query. This can be used to execute further queries *** ### events[​](#events "Direct link to events") ``` readonly events: GatherResult[]; ``` Any events/results that occurred during or from the query *** ### gasCost[​](#gascost "Direct link to gasCost") ``` readonly gasCost: RunningCost; ``` The measured cost of executing the query ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # StateBoundedMerkleTree > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / StateBoundedMerkleTree # Class: StateBoundedMerkleTree Represents a fixed-depth Merkle tree storing hashed data, whose preimages are unknown ## Constructors[​](#constructors "Direct link to Constructors") ### new StateBoundedMerkleTree()[​](#new-stateboundedmerkletree "Direct link to new StateBoundedMerkleTree()") ``` new StateBoundedMerkleTree(height): StateBoundedMerkleTree ``` Create a blank tree with the given height #### Parameters[​](#parameters "Direct link to Parameters") ##### height[​](#height "Direct link to height") `number` #### Returns[​](#returns "Direct link to Returns") [`StateBoundedMerkleTree`](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) ## Properties[​](#properties "Direct link to Properties") ### height[​](#height-1 "Direct link to height") ``` readonly height: number; ``` ## Methods[​](#methods "Direct link to Methods") ### collapse()[​](#collapse "Direct link to collapse()") ``` collapse(start, end): StateBoundedMerkleTree ``` **`Internal`** Erases all but necessary hashes between, and inclusive of, `start` and `end` inidices #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### start[​](#start "Direct link to start") `bigint` ##### end[​](#end "Direct link to end") `bigint` #### Returns[​](#returns-1 "Direct link to Returns") [`StateBoundedMerkleTree`](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) #### Throws[​](#throws "Direct link to Throws") If the indices are out-of-bounds for the tree, or `end < start` *** ### findPathForLeaf()[​](#findpathforleaf "Direct link to findPathForLeaf()") ``` findPathForLeaf(leaf): undefined | AlignedValue ``` **`Internal`** Internal implementation of the finding path primitive. Returns undefined if the leaf is not in the tree. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### leaf[​](#leaf "Direct link to leaf") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) *** ### pathForLeaf()[​](#pathforleaf "Direct link to pathForLeaf()") ``` pathForLeaf(index, leaf): AlignedValue ``` **`Internal`** Internal implementation of the path construction primitive #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### index[​](#index "Direct link to index") `bigint` ##### leaf[​](#leaf-1 "Direct link to leaf") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Throws[​](#throws-1 "Direct link to Throws") If the index is out-of-bounds for the tree *** ### rehash()[​](#rehash "Direct link to rehash()") ``` rehash(): StateBoundedMerkleTree ``` Rehashes the tree, updating all internal hashes and ensuring all node hashes are present. Necessary because the onchain runtime does not automatically rehash trees. #### Returns[​](#returns-4 "Direct link to Returns") [`StateBoundedMerkleTree`](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) *** ### root()[​](#root "Direct link to root()") ``` root(): undefined | AlignedValue ``` **`Internal`** Internal implementation of the merkle tree root primitive. Returns undefined if the tree has not been fully hashed. #### Returns[​](#returns-5 "Direct link to Returns") `undefined` | [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### update()[​](#update "Direct link to update()") ``` update(index, leaf): StateBoundedMerkleTree ``` Inserts a value into the Merkle tree, returning the updated tree #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### index[​](#index-1 "Direct link to index") `bigint` ##### leaf[​](#leaf-2 "Direct link to leaf") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-7 "Direct link to Returns") [`StateBoundedMerkleTree`](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) #### Throws[​](#throws-2 "Direct link to Throws") If the index is out-of-bounds for the tree --- # StateMap > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / StateMap # Class: StateMap Represents a key-value map, where keys are [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)s, and values are [StateValue](/api-reference/onchain-runtime/classes/StateValue.md)s. ## Constructors[​](#constructors "Direct link to Constructors") ### new StateMap()[​](#new-statemap "Direct link to new StateMap()") ``` new StateMap(): StateMap ``` #### Returns[​](#returns "Direct link to Returns") [`StateMap`](/api-reference/onchain-runtime/classes/StateMap.md) ## Methods[​](#methods "Direct link to Methods") ### get()[​](#get "Direct link to get()") ``` get(key): undefined | StateValue ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### key[​](#key "Direct link to key") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### insert()[​](#insert "Direct link to insert()") ``` insert(key, value): StateMap ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### key[​](#key-1 "Direct link to key") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) #### Returns[​](#returns-2 "Direct link to Returns") [`StateMap`](/api-reference/onchain-runtime/classes/StateMap.md) *** ### keys()[​](#keys "Direct link to keys()") ``` keys(): AlignedValue[] ``` #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)\[] *** ### remove()[​](#remove "Direct link to remove()") ``` remove(key): StateMap ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### key[​](#key-2 "Direct link to key") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-4 "Direct link to Returns") [`StateMap`](/api-reference/onchain-runtime/classes/StateMap.md) *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` --- # StateValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / StateValue # Class: StateValue Represents the core of a contract's state, and recursively represents each of its components. There are different *classes* of state values: * `null` * Cells of [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)s * Maps from [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)s to state values * Bounded Merkle trees containing [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) leaves * Short (<= 15 element) arrays of state values State values are *immutable*, any operations that mutate states will return a new state instead. ## Methods[​](#methods "Direct link to Methods") ### arrayPush()[​](#arraypush "Direct link to arrayPush()") ``` arrayPush(value): StateValue ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) #### Returns[​](#returns "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### asArray()[​](#asarray "Direct link to asArray()") ``` asArray(): undefined | StateValue[] ``` #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md)\[] *** ### asBoundedMerkleTree()[​](#asboundedmerkletree "Direct link to asBoundedMerkleTree()") ``` asBoundedMerkleTree(): undefined | StateBoundedMerkleTree ``` #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | [`StateBoundedMerkleTree`](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) *** ### asCell()[​](#ascell "Direct link to asCell()") ``` asCell(): AlignedValue ``` #### Returns[​](#returns-3 "Direct link to Returns") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) *** ### asMap()[​](#asmap "Direct link to asMap()") ``` asMap(): undefined | StateMap ``` #### Returns[​](#returns-4 "Direct link to Returns") `undefined` | [`StateMap`](/api-reference/onchain-runtime/classes/StateMap.md) *** ### encode()[​](#encode "Direct link to encode()") ``` encode(): EncodedStateValue ``` **`Internal`** #### Returns[​](#returns-5 "Direct link to Returns") [`EncodedStateValue`](/api-reference/onchain-runtime/type-aliases/EncodedStateValue.md) *** ### logSize()[​](#logsize "Direct link to logSize()") ``` logSize(): number ``` #### Returns[​](#returns-6 "Direct link to Returns") `number` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-7 "Direct link to Returns") `string` *** ### type()[​](#type "Direct link to type()") ``` type(): | "map" | "null" | "cell" | "array" | "boundedMerkleTree" ``` #### Returns[​](#returns-8 "Direct link to Returns") \| `"map"` | `"null"` | `"cell"` | `"array"` | `"boundedMerkleTree"` *** ### decode()[​](#decode "Direct link to decode()") ``` static decode(value): StateValue ``` **`Internal`** #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value-1 "Direct link to value") [`EncodedStateValue`](/api-reference/onchain-runtime/type-aliases/EncodedStateValue.md) #### Returns[​](#returns-9 "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### newArray()[​](#newarray "Direct link to newArray()") ``` static newArray(): StateValue ``` #### Returns[​](#returns-10 "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### newBoundedMerkleTree()[​](#newboundedmerkletree "Direct link to newBoundedMerkleTree()") ``` static newBoundedMerkleTree(tree): StateValue ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### tree[​](#tree "Direct link to tree") [`StateBoundedMerkleTree`](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) #### Returns[​](#returns-11 "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### newCell()[​](#newcell "Direct link to newCell()") ``` static newCell(value): StateValue ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### value[​](#value-2 "Direct link to value") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) #### Returns[​](#returns-12 "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### newMap()[​](#newmap "Direct link to newMap()") ``` static newMap(map): StateValue ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### map[​](#map "Direct link to map") [`StateMap`](/api-reference/onchain-runtime/classes/StateMap.md) #### Returns[​](#returns-13 "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### newNull()[​](#newnull "Direct link to newNull()") ``` static newNull(): StateValue ``` #### Returns[​](#returns-14 "Direct link to Returns") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) --- # VmResults > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / VmResults # Class: VmResults Represents the results of a VM call ## Properties[​](#properties "Direct link to Properties") ### events[​](#events "Direct link to events") ``` readonly events: GatherResult[]; ``` The events that got emitted by this VM invocation *** ### gasCost[​](#gascost "Direct link to gasCost") ``` readonly gasCost: RunningCost; ``` The computed gas cost of running this VM invocation *** ### stack[​](#stack "Direct link to stack") ``` readonly stack: VmStack; ``` The VM stack at the end of the VM invocation ## Methods[​](#methods "Direct link to Methods") ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns "Direct link to Returns") `string` --- # VmStack > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / VmStack # Class: VmStack Represents the state of the VM's stack at a specific point. The stack is an array of [StateValue](/api-reference/onchain-runtime/classes/StateValue.md)s, each of which is also annotated with whether it is "strong" or "weak"; that is, whether it is permitted to be stored on-chain or not. ## Constructors[​](#constructors "Direct link to Constructors") ### new VmStack()[​](#new-vmstack "Direct link to new VmStack()") ``` new VmStack(): VmStack ``` #### Returns[​](#returns "Direct link to Returns") [`VmStack`](/api-reference/onchain-runtime/classes/VmStack.md) ## Methods[​](#methods "Direct link to Methods") ### get()[​](#get "Direct link to get()") ``` get(idx): undefined | StateValue ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### idx[​](#idx "Direct link to idx") `number` #### Returns[​](#returns-1 "Direct link to Returns") `undefined` | [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) *** ### isStrong()[​](#isstrong "Direct link to isStrong()") ``` isStrong(idx): undefined | boolean ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### idx[​](#idx-1 "Direct link to idx") `number` #### Returns[​](#returns-2 "Direct link to Returns") `undefined` | `boolean` *** ### length()[​](#length "Direct link to length()") ``` length(): number ``` #### Returns[​](#returns-3 "Direct link to Returns") `number` *** ### push()[​](#push "Direct link to push()") ``` push(value, is_strong): void ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### value[​](#value "Direct link to value") [`StateValue`](/api-reference/onchain-runtime/classes/StateValue.md) ##### is\_strong[​](#is_strong "Direct link to is_strong") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `void` *** ### removeLast()[​](#removelast "Direct link to removeLast()") ``` removeLast(): void ``` #### Returns[​](#returns-5 "Direct link to Returns") `void` *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` --- # bigIntModFr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / bigIntModFr # Function: bigIntModFr() ``` function bigIntModFr(x): bigint ``` Takes a bigint modulus the proof systems scalar field ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") `bigint` --- # bigIntToValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / bigIntToValue # Function: bigIntToValue() ``` function bigIntToValue(x): Value ``` **`Internal`** Internal conversion between bigints and their field-aligned binary representation ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") `bigint` ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) --- # communicationCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / communicationCommitment # Function: communicationCommitment() ``` function communicationCommitment( input, output, rand): string ``` Computes the communication commitment corresponding to an input/output pair and randomness. ## Parameters[​](#parameters "Direct link to Parameters") ### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ### rand[​](#rand "Direct link to rand") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # communicationCommitmentRandomness > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / communicationCommitmentRandomness # Function: communicationCommitmentRandomness() ``` function communicationCommitmentRandomness(): string ``` Samples a new [CommunicationCommitmentRand](/api-reference/onchain-runtime/type-aliases/CommunicationCommitmentRand.md) uniformly ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / decodeCoinPublicKey # Function: decodeCoinPublicKey() ``` function decodeCoinPublicKey(pk): string ``` Decode a [CoinPublicKey](/api-reference/onchain-runtime/type-aliases/CoinPublicKey.md) from a `Uint8Array` originating from Compact's `CoinPublicKey` type ## Parameters[​](#parameters "Direct link to Parameters") ### pk[​](#pk "Direct link to pk") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / decodeContractAddress # Function: decodeContractAddress() ``` function decodeContractAddress(addr): string ``` Decode a [ContractAddress](/api-reference/onchain-runtime/type-aliases/ContractAddress.md) from a `Uint8Array` originating from Compact's `ContractAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / decodeQualifiedShieldedCoinInfo # Function: decodeQualifiedShieldedCoinInfo() ``` function decodeQualifiedShieldedCoinInfo(coin): QualifiedShieldedCoinInfo ``` Decode a [QualifiedShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md) from Compact's `QualifiedShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### mt\_index[​](#mt_index "Direct link to mt_index") `bigint` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`QualifiedShieldedCoinInfo`](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md) --- # decodeRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / decodeRawTokenType # Function: decodeRawTokenType() ``` function decodeRawTokenType(tt): string ``` Decode a raw [RawTokenType](/api-reference/onchain-runtime/type-aliases/RawTokenType.md) from a `Uint8Array` originating from Compact's `RawTokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # decodeShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / decodeShieldedCoinInfo # Function: decodeShieldedCoinInfo() ``` function decodeShieldedCoinInfo(coin): ShieldedCoinInfo ``` Decode a [ShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md) from Compact's `ShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") #### color[​](#color "Direct link to color") `Uint8Array` #### nonce[​](#nonce "Direct link to nonce") `Uint8Array` #### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`ShieldedCoinInfo`](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md) --- # decodeUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / decodeUserAddress # Function: decodeUserAddress() ``` function decodeUserAddress(addr): string ``` Decode a [UserAddress](/api-reference/onchain-runtime/type-aliases/UserAddress.md) from a `Uint8Array` originating from Compact's `UserAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # degradeToTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / degradeToTransient # Function: degradeToTransient() ``` function degradeToTransient(persistent): Value ``` **`Internal`** Internal implementation of the degrade to transient primitive ## Parameters[​](#parameters "Direct link to Parameters") ### persistent[​](#persistent "Direct link to persistent") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [persistent](/api-reference/onchain-runtime/functions/degradeToTransient.md#persistent) does not encode a 32-byte bytestring --- # dummyContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / dummyContractAddress # Function: dummyContractAddress() ``` function dummyContractAddress(): string ``` A sample contract address ## Returns[​](#returns "Direct link to Returns") `string` --- # dummyUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / dummyUserAddress # Function: dummyUserAddress() ``` function dummyUserAddress(): string ``` A sample user address ## Returns[​](#returns "Direct link to Returns") `string` --- # ecAdd > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ecAdd # Function: ecAdd() ``` function ecAdd(a, b): Value ``` **`Internal`** Internal implementation of the elliptic curve addition primitive ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ### b[​](#b "Direct link to b") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If either input does not encode an elliptic curve point --- # ecMul > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ecMul # Function: ecMul() ``` function ecMul(a, b): Value ``` **`Internal`** Internal implementation of the elliptic curve multiplication primitive ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ### b[​](#b "Direct link to b") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [a](/api-reference/onchain-runtime/functions/ecMul.md#a) does not encode an elliptic curve point or [b](/api-reference/onchain-runtime/functions/ecMul.md#b) does not encode a field element --- # ecMulGenerator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ecMulGenerator # Function: ecMulGenerator() ``` function ecMulGenerator(val): Value ``` **`Internal`** Internal implementation of the elliptic curve generator multiplication primitive ## Parameters[​](#parameters "Direct link to Parameters") ### val[​](#val "Direct link to val") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") if [val](/api-reference/onchain-runtime/functions/ecMulGenerator.md#val) does not encode a field element --- # encodeCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / encodeCoinPublicKey # Function: encodeCoinPublicKey() ``` function encodeCoinPublicKey(pk): Uint8Array ``` Encode a [CoinPublicKey](/api-reference/onchain-runtime/type-aliases/CoinPublicKey.md) into a `Uint8Array` for use in Compact's `CoinPublicKey` type ## Parameters[​](#parameters "Direct link to Parameters") ### pk[​](#pk "Direct link to pk") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / encodeContractAddress # Function: encodeContractAddress() ``` function encodeContractAddress(addr): Uint8Array ``` Encode a [ContractAddress](/api-reference/onchain-runtime/type-aliases/ContractAddress.md) into a `Uint8Array` for use in Compact's `ContractAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeQualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / encodeQualifiedShieldedCoinInfo # Function: encodeQualifiedShieldedCoinInfo() ``` function encodeQualifiedShieldedCoinInfo(coin): { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; } ``` Encode a [QualifiedShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md) into a Compact's `QualifiedShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`QualifiedShieldedCoinInfo`](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; mt_index: bigint; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / encodeRawTokenType # Function: encodeRawTokenType() ``` function encodeRawTokenType(tt): Uint8Array ``` Encode a raw [RawTokenType](/api-reference/onchain-runtime/type-aliases/RawTokenType.md) into a `Uint8Array` for use in Compact's `RawTokenType` type ## Parameters[​](#parameters "Direct link to Parameters") ### tt[​](#tt "Direct link to tt") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # encodeShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / encodeShieldedCoinInfo # Function: encodeShieldedCoinInfo() ``` function encodeShieldedCoinInfo(coin): { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` Encode a [ShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md) into a Compact's `ShieldedCoinInfo` TypeScript representation ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`ShieldedCoinInfo`](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md) ## Returns[​](#returns "Direct link to Returns") ``` { color: Uint8Array; nonce: Uint8Array; value: bigint; } ``` ### color[​](#color "Direct link to color") ``` color: Uint8Array; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Uint8Array; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # encodeUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / encodeUserAddress # Function: encodeUserAddress() ``` function encodeUserAddress(addr): Uint8Array ``` Encode a [UserAddress](/api-reference/onchain-runtime/type-aliases/UserAddress.md) into a `Uint8Array` for use in Compact's `UserAddress` type ## Parameters[​](#parameters "Direct link to Parameters") ### addr[​](#addr "Direct link to addr") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # entryPointHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / entryPointHash # Function: entryPointHash() ``` function entryPointHash(entryPoint): string ``` Computes the (hex-encoded) hash of a given contract entry point. Used in composable contracts to reference the called contract's entry point ID in-circuit. ## Parameters[​](#parameters "Direct link to Parameters") ### entryPoint[​](#entrypoint "Direct link to entryPoint") `string` | `Uint8Array`<`ArrayBufferLike`> ## Returns[​](#returns "Direct link to Returns") `string` --- # hashToCurve > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / hashToCurve # Function: hashToCurve() ``` function hashToCurve(align, val): Value ``` **`Internal`** Internal implementation of the hash to curve primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/onchain-runtime/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](/api-reference/onchain-runtime/functions/hashToCurve.md#val) does not have alignment [align](/api-reference/onchain-runtime/functions/hashToCurve.md#align) --- # leafHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / leafHash # Function: leafHash() ``` function leafHash(value): AlignedValue ``` **`Internal`** Internal implementation of the Merkle tree leaf hash primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### value[​](#value "Direct link to value") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) --- # maxAlignedSize > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / maxAlignedSize # Function: maxAlignedSize() ``` function maxAlignedSize(alignment): bigint ``` **`Internal`** Internal implementation of the max aligned size primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### alignment[​](#alignment "Direct link to alignment") [`Alignment`](/api-reference/onchain-runtime/type-aliases/Alignment.md) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # maxField > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / maxField # Function: maxField() ``` function maxField(): bigint ``` Returns the maximum representable value in the proof systems scalar field (that is, 1 less than the prime modulus) ## Returns[​](#returns "Direct link to Returns") `bigint` --- # persistentCommit > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / persistentCommit # Function: persistentCommit() ``` function persistentCommit( align, val, opening): Value ``` **`Internal`** Internal implementation of the persistent commitment primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/onchain-runtime/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ### opening[​](#opening "Direct link to opening") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](/api-reference/onchain-runtime/functions/persistentCommit.md#val) does not have alignment [align](/api-reference/onchain-runtime/functions/persistentCommit.md#align), [opening](/api-reference/onchain-runtime/functions/persistentCommit.md#opening) does not encode a 32-byte bytestring, or any component has a compress alignment --- # persistentHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / persistentHash # Function: persistentHash() ``` function persistentHash(align, val): Value ``` **`Internal`** Internal implementation of the persistent hash primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/onchain-runtime/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](/api-reference/onchain-runtime/functions/persistentHash.md#val) does not have alignment [align](/api-reference/onchain-runtime/functions/persistentHash.md#align), or any component has a compress alignment --- # proofDataIntoSerializedPreimage > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / proofDataIntoSerializedPreimage # Function: proofDataIntoSerializedPreimage() ``` function proofDataIntoSerializedPreimage( input, output, public_transcript, private_transcript_outputs, key_location?): Uint8Array ``` Converts input, output, and transcript information into a proof preimage suitable to pass to a `ProvingProvider`. The `key_location` parameter is a string used to identify the circuit by proving machinery, for backwards-compatibility, if unset it defaults to `'dummy'`. ## Parameters[​](#parameters "Direct link to Parameters") ### input[​](#input "Direct link to input") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ### output[​](#output "Direct link to output") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ### public\_transcript[​](#public_transcript "Direct link to public_transcript") [`Op`](/api-reference/onchain-runtime/type-aliases/Op.md)<[`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)>\[] ### private\_transcript\_outputs[​](#private_transcript_outputs "Direct link to private_transcript_outputs") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md)\[] ### key\_location?[​](#key_location "Direct link to key_location?") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # rawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / rawTokenType # Function: rawTokenType() ``` function rawTokenType(domain_sep, contract): string ``` Derives the raw [RawTokenType](/api-reference/onchain-runtime/type-aliases/RawTokenType.md) associated with a particular [DomainSeparator](/api-reference/onchain-runtime/type-aliases/DomainSeparator.md) and contract. ## Parameters[​](#parameters "Direct link to Parameters") ### domain\_sep[​](#domain_sep "Direct link to domain_sep") [`DomainSeparator`](/api-reference/onchain-runtime/type-aliases/DomainSeparator.md) ### contract[​](#contract "Direct link to contract") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # runProgram > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / runProgram # Function: runProgram() ``` function runProgram( initial, ops, cost_model, gas_limit?): VmResults ``` Runs a VM program against an initial stack, with an optional gas limit ## Parameters[​](#parameters "Direct link to Parameters") ### initial[​](#initial "Direct link to initial") [`VmStack`](/api-reference/onchain-runtime/classes/VmStack.md) ### ops[​](#ops "Direct link to ops") [`Op`](/api-reference/onchain-runtime/type-aliases/Op.md)<`null`>\[] ### cost\_model[​](#cost_model "Direct link to cost_model") [`CostModel`](/api-reference/onchain-runtime/classes/CostModel.md) ### gas\_limit?[​](#gas_limit "Direct link to gas_limit?") [`RunningCost`](/api-reference/onchain-runtime/type-aliases/RunningCost.md) ## Returns[​](#returns "Direct link to Returns") [`VmResults`](/api-reference/onchain-runtime/classes/VmResults.md) --- # runtimeCoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / runtimeCoinCommitment # Function: runtimeCoinCommitment() ``` function runtimeCoinCommitment(coin, recipient): AlignedValue ``` **`Internal`** Internal implementation of the runtime's coin commitment primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ### recipient[​](#recipient "Direct link to recipient") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) --- # runtimeCoinNullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / runtimeCoinNullifier # Function: runtimeCoinNullifier() ``` function runtimeCoinNullifier(coin, sender_evidence): AlignedValue ``` **`Internal`** Internal implementation of the runtime's coin nullifier primitive. ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ### sender\_evidence[​](#sender_evidence "Direct link to sender_evidence") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) ## Returns[​](#returns "Direct link to Returns") [`AlignedValue`](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) --- # sampleContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / sampleContractAddress # Function: sampleContractAddress() ``` function sampleContractAddress(): string ``` Samples a uniform contract address, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleRawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / sampleRawTokenType # Function: sampleRawTokenType() ``` function sampleRawTokenType(): string ``` Samples a uniform raw token type, for use in testing to construct both the shielded and unshielded token types. ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleSigningKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / sampleSigningKey # Function: sampleSigningKey() ``` function sampleSigningKey(): string ``` Randomly samples a [SigningKey](/api-reference/onchain-runtime/type-aliases/SigningKey.md). ## Returns[​](#returns "Direct link to Returns") `string` --- # sampleUserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / sampleUserAddress # Function: sampleUserAddress() ``` function sampleUserAddress(): string ``` Samples a uniform user address, for use in testing ## Returns[​](#returns "Direct link to Returns") `string` --- # signatureVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / signatureVerifyingKey # Function: signatureVerifyingKey() ``` function signatureVerifyingKey(sk): string ``` Returns the verifying key for a given signing key ## Parameters[​](#parameters "Direct link to Parameters") ### sk[​](#sk "Direct link to sk") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # signData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / signData # Function: signData() ``` function signData(key, data): string ``` Signs arbitrary data with the given signing key. WARNING: Do not expose access to this function for valuable keys for data that is not strictly controlled! ## Parameters[​](#parameters "Direct link to Parameters") ### key[​](#key "Direct link to key") `string` ### data[​](#data "Direct link to data") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # signingKeyFromBip340 > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / signingKeyFromBip340 # Function: signingKeyFromBip340() ``` function signingKeyFromBip340(data): string ``` Creates a [SigningKey](/api-reference/onchain-runtime/type-aliases/SigningKey.md) from provided Bip340 private key. ## Parameters[​](#parameters "Direct link to Parameters") ### data[​](#data "Direct link to data") `Uint8Array` ## Returns[​](#returns "Direct link to Returns") `string` --- # transientCommit > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / transientCommit # Function: transientCommit() ``` function transientCommit( align, val, opening): Value ``` **`Internal`** Internal implementation of the transient commitment primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/onchain-runtime/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ### opening[​](#opening "Direct link to opening") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](/api-reference/onchain-runtime/functions/transientCommit.md#val) does not have alignment [align](/api-reference/onchain-runtime/functions/transientCommit.md#align), or [opening](/api-reference/onchain-runtime/functions/transientCommit.md#opening) does not encode a field element --- # transientHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / transientHash # Function: transientHash() ``` function transientHash(align, val): Value ``` **`Internal`** Internal implementation of the transient hash primitive ## Parameters[​](#parameters "Direct link to Parameters") ### align[​](#align "Direct link to align") [`Alignment`](/api-reference/onchain-runtime/type-aliases/Alignment.md) ### val[​](#val "Direct link to val") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [val](/api-reference/onchain-runtime/functions/transientHash.md#val) does not have alignment [align](/api-reference/onchain-runtime/functions/transientHash.md#align) --- # upgradeFromTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / upgradeFromTransient # Function: upgradeFromTransient() ``` function upgradeFromTransient(transient): Value ``` **`Internal`** Internal implementation of the upgrade from transient primitive ## Parameters[​](#parameters "Direct link to Parameters") ### transient[​](#transient "Direct link to transient") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Throws[​](#throws "Direct link to Throws") If [transient](/api-reference/onchain-runtime/functions/upgradeFromTransient.md#transient) does not encode a field element --- # valueToBigInt > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / valueToBigInt # Function: valueToBigInt() ``` function valueToBigInt(x): bigint ``` **`Internal`** Internal conversion between field-aligned binary values and bigints within the scalar field ## Parameters[​](#parameters "Direct link to Parameters") ### x[​](#x "Direct link to x") [`Value`](/api-reference/onchain-runtime/type-aliases/Value.md) ## Returns[​](#returns "Direct link to Returns") `bigint` ## Throws[​](#throws "Direct link to Throws") If the value does not encode a field element --- # verifySignature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / verifySignature # Function: verifySignature() ``` function verifySignature( vk, data, signature): boolean ``` Verifies if a signature is correct ## Parameters[​](#parameters "Direct link to Parameters") ### vk[​](#vk "Direct link to vk") `string` ### data[​](#data "Direct link to data") `Uint8Array` ### signature[​](#signature "Direct link to signature") `string` ## Returns[​](#returns "Direct link to Returns") `boolean` --- # globals > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** # @midnight-ntwrk/onchain-runtime v3.0.0 ## Classes[​](#classes "Direct link to Classes") * [ChargedState](/api-reference/onchain-runtime/classes/ChargedState.md) * [CoinSecretKey](/api-reference/onchain-runtime/classes/CoinSecretKey.md) * [ContractMaintenanceAuthority](/api-reference/onchain-runtime/classes/ContractMaintenanceAuthority.md) * [ContractOperation](/api-reference/onchain-runtime/classes/ContractOperation.md) * [ContractState](/api-reference/onchain-runtime/classes/ContractState.md) * [CostModel](/api-reference/onchain-runtime/classes/CostModel.md) * [QueryContext](/api-reference/onchain-runtime/classes/QueryContext.md) * [QueryResults](/api-reference/onchain-runtime/classes/QueryResults.md) * [StateBoundedMerkleTree](/api-reference/onchain-runtime/classes/StateBoundedMerkleTree.md) * [StateMap](/api-reference/onchain-runtime/classes/StateMap.md) * [StateValue](/api-reference/onchain-runtime/classes/StateValue.md) * [VmResults](/api-reference/onchain-runtime/classes/VmResults.md) * [VmStack](/api-reference/onchain-runtime/classes/VmStack.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md) * [Alignment](/api-reference/onchain-runtime/type-aliases/Alignment.md) * [AlignmentAtom](/api-reference/onchain-runtime/type-aliases/AlignmentAtom.md) * [AlignmentSegment](/api-reference/onchain-runtime/type-aliases/AlignmentSegment.md) * [BlockContext](/api-reference/onchain-runtime/type-aliases/BlockContext.md) * [CallContext](/api-reference/onchain-runtime/type-aliases/CallContext.md) * [CoinCommitment](/api-reference/onchain-runtime/type-aliases/CoinCommitment.md) * [CoinPublicKey](/api-reference/onchain-runtime/type-aliases/CoinPublicKey.md) * [CommunicationCommitment](/api-reference/onchain-runtime/type-aliases/CommunicationCommitment.md) * [CommunicationCommitmentRand](/api-reference/onchain-runtime/type-aliases/CommunicationCommitmentRand.md) * [ContractAddress](/api-reference/onchain-runtime/type-aliases/ContractAddress.md) * [DomainSeparator](/api-reference/onchain-runtime/type-aliases/DomainSeparator.md) * [DustTokenType](/api-reference/onchain-runtime/type-aliases/DustTokenType.md) * [Effects](/api-reference/onchain-runtime/type-aliases/Effects.md) * [EncodedStateValue](/api-reference/onchain-runtime/type-aliases/EncodedStateValue.md) * [FeePrices](/api-reference/onchain-runtime/type-aliases/FeePrices.md) * [Fr](/api-reference/onchain-runtime/type-aliases/Fr.md) * [GatherResult](/api-reference/onchain-runtime/type-aliases/GatherResult.md) * [Key](/api-reference/onchain-runtime/type-aliases/Key.md) * [Nonce](/api-reference/onchain-runtime/type-aliases/Nonce.md) * [Nullifier](/api-reference/onchain-runtime/type-aliases/Nullifier.md) * [Op](/api-reference/onchain-runtime/type-aliases/Op.md) * [PublicAddress](/api-reference/onchain-runtime/type-aliases/PublicAddress.md) * [QualifiedShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/QualifiedShieldedCoinInfo.md) * [RawTokenType](/api-reference/onchain-runtime/type-aliases/RawTokenType.md) * [RunningCost](/api-reference/onchain-runtime/type-aliases/RunningCost.md) * [ShieldedCoinInfo](/api-reference/onchain-runtime/type-aliases/ShieldedCoinInfo.md) * [ShieldedTokenType](/api-reference/onchain-runtime/type-aliases/ShieldedTokenType.md) * [Signature](/api-reference/onchain-runtime/type-aliases/Signature.md) * [SignatureVerifyingKey](/api-reference/onchain-runtime/type-aliases/SignatureVerifyingKey.md) * [SigningKey](/api-reference/onchain-runtime/type-aliases/SigningKey.md) * [TokenType](/api-reference/onchain-runtime/type-aliases/TokenType.md) * [Transcript](/api-reference/onchain-runtime/type-aliases/Transcript.md) * [UnshieldedTokenType](/api-reference/onchain-runtime/type-aliases/UnshieldedTokenType.md) * [UserAddress](/api-reference/onchain-runtime/type-aliases/UserAddress.md) * [Value](/api-reference/onchain-runtime/type-aliases/Value.md) ## Functions[​](#functions "Direct link to Functions") * [bigIntModFr](/api-reference/onchain-runtime/functions/bigIntModFr.md) * [bigIntToValue](/api-reference/onchain-runtime/functions/bigIntToValue.md) * [communicationCommitment](/api-reference/onchain-runtime/functions/communicationCommitment.md) * [communicationCommitmentRandomness](/api-reference/onchain-runtime/functions/communicationCommitmentRandomness.md) * [decodeCoinPublicKey](/api-reference/onchain-runtime/functions/decodeCoinPublicKey.md) * [decodeContractAddress](/api-reference/onchain-runtime/functions/decodeContractAddress.md) * [decodeQualifiedShieldedCoinInfo](/api-reference/onchain-runtime/functions/decodeQualifiedShieldedCoinInfo.md) * [decodeRawTokenType](/api-reference/onchain-runtime/functions/decodeRawTokenType.md) * [decodeShieldedCoinInfo](/api-reference/onchain-runtime/functions/decodeShieldedCoinInfo.md) * [decodeUserAddress](/api-reference/onchain-runtime/functions/decodeUserAddress.md) * [degradeToTransient](/api-reference/onchain-runtime/functions/degradeToTransient.md) * [dummyContractAddress](/api-reference/onchain-runtime/functions/dummyContractAddress.md) * [dummyUserAddress](/api-reference/onchain-runtime/functions/dummyUserAddress.md) * [ecAdd](/api-reference/onchain-runtime/functions/ecAdd.md) * [ecMul](/api-reference/onchain-runtime/functions/ecMul.md) * [ecMulGenerator](/api-reference/onchain-runtime/functions/ecMulGenerator.md) * [encodeCoinPublicKey](/api-reference/onchain-runtime/functions/encodeCoinPublicKey.md) * [encodeContractAddress](/api-reference/onchain-runtime/functions/encodeContractAddress.md) * [encodeQualifiedShieldedCoinInfo](/api-reference/onchain-runtime/functions/encodeQualifiedShieldedCoinInfo.md) * [encodeRawTokenType](/api-reference/onchain-runtime/functions/encodeRawTokenType.md) * [encodeShieldedCoinInfo](/api-reference/onchain-runtime/functions/encodeShieldedCoinInfo.md) * [encodeUserAddress](/api-reference/onchain-runtime/functions/encodeUserAddress.md) * [entryPointHash](/api-reference/onchain-runtime/functions/entryPointHash.md) * [hashToCurve](/api-reference/onchain-runtime/functions/hashToCurve.md) * [leafHash](/api-reference/onchain-runtime/functions/leafHash.md) * [maxAlignedSize](/api-reference/onchain-runtime/functions/maxAlignedSize.md) * [maxField](/api-reference/onchain-runtime/functions/maxField.md) * [persistentCommit](/api-reference/onchain-runtime/functions/persistentCommit.md) * [persistentHash](/api-reference/onchain-runtime/functions/persistentHash.md) * [proofDataIntoSerializedPreimage](/api-reference/onchain-runtime/functions/proofDataIntoSerializedPreimage.md) * [rawTokenType](/api-reference/onchain-runtime/functions/rawTokenType.md) * [runProgram](/api-reference/onchain-runtime/functions/runProgram.md) * [runtimeCoinCommitment](/api-reference/onchain-runtime/functions/runtimeCoinCommitment.md) * [runtimeCoinNullifier](/api-reference/onchain-runtime/functions/runtimeCoinNullifier.md) * [sampleContractAddress](/api-reference/onchain-runtime/functions/sampleContractAddress.md) * [sampleRawTokenType](/api-reference/onchain-runtime/functions/sampleRawTokenType.md) * [sampleSigningKey](/api-reference/onchain-runtime/functions/sampleSigningKey.md) * [sampleUserAddress](/api-reference/onchain-runtime/functions/sampleUserAddress.md) * [signatureVerifyingKey](/api-reference/onchain-runtime/functions/signatureVerifyingKey.md) * [signData](/api-reference/onchain-runtime/functions/signData.md) * [signingKeyFromBip340](/api-reference/onchain-runtime/functions/signingKeyFromBip340.md) * [transientCommit](/api-reference/onchain-runtime/functions/transientCommit.md) * [transientHash](/api-reference/onchain-runtime/functions/transientHash.md) * [upgradeFromTransient](/api-reference/onchain-runtime/functions/upgradeFromTransient.md) * [valueToBigInt](/api-reference/onchain-runtime/functions/valueToBigInt.md) * [verifySignature](/api-reference/onchain-runtime/functions/verifySignature.md) --- # AlignedValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / AlignedValue # Type Alias: AlignedValue ``` type AlignedValue: { alignment: Alignment; value: Value; }; ``` An onchain data value, in field-aligned binary format, annotated with its alignment. ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### alignment[​](#alignment "Direct link to alignment") ``` alignment: Alignment; ``` ### value[​](#value "Direct link to value") ``` value: Value; ``` --- # Alignment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Alignment # Type Alias: Alignment ``` type Alignment: AlignmentSegment[]; ``` The alignment of an onchain field-aligned binary data value. --- # AlignmentAtom > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / AlignmentAtom # Type Alias: AlignmentAtom ``` type AlignmentAtom: { tag: "compress"; } | { tag: "field"; } | { length: number; tag: "bytes"; }; ``` A atom in a larger [Alignment](/api-reference/onchain-runtime/type-aliases/Alignment.md). --- # AlignmentSegment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / AlignmentSegment # Type Alias: AlignmentSegment ``` type AlignmentSegment: { tag: "option"; value: Alignment[]; } | { tag: "atom"; value: AlignmentAtom; }; ``` A segment in a larger [Alignment](/api-reference/onchain-runtime/type-aliases/Alignment.md). --- # BlockContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / BlockContext # Type Alias: BlockContext ``` type BlockContext: { lastBlockTime: bigint; parentBlockHash: string; secondsSinceEpoch: bigint; secondsSinceEpochErr: number; }; ``` Context information about the block forwarded to [CallContext](/api-reference/onchain-runtime/type-aliases/CallContext.md). ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### lastBlockTime[​](#lastblocktime "Direct link to lastBlockTime") ``` lastBlockTime: bigint; ``` The [secondsSinceEpoch](/api-reference/onchain-runtime/type-aliases/BlockContext.md#secondssinceepoch) of the previous block ### parentBlockHash[​](#parentblockhash "Direct link to parentBlockHash") ``` parentBlockHash: string; ``` The hash of the block prior to this transaction, as a hex-encoded string ### secondsSinceEpoch[​](#secondssinceepoch "Direct link to secondsSinceEpoch") ``` secondsSinceEpoch: bigint; ``` The seconds since the UNIX epoch that have elapsed ### secondsSinceEpochErr[​](#secondssinceepocherr "Direct link to secondsSinceEpochErr") ``` secondsSinceEpochErr: number; ``` The maximum error on [secondsSinceEpoch](/api-reference/onchain-runtime/type-aliases/BlockContext.md#secondssinceepoch) that should occur, as a positive seconds value --- # CallContext > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CallContext # Type Alias: CallContext ``` type CallContext: { balance: Map; caller: PublicAddress; comIndices: Map; lastBlockTime: bigint; ownAddress: ContractAddress; parentBlockHash: string; secondsSinceEpoch: bigint; secondsSinceEpochErr: number; }; ``` The context information of a call provided to the VM. ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### balance[​](#balance "Direct link to balance") ``` balance: Map; ``` The balances held by the called contract at the time it was called. ### caller?[​](#caller "Direct link to caller?") ``` optional caller: PublicAddress; ``` A public address identifying an entity. ### comIndices[​](#comindices "Direct link to comIndices") ``` comIndices: Map; ``` The commitment indices map accessible to the contract. ### lastBlockTime[​](#lastblocktime "Direct link to lastBlockTime") ``` lastBlockTime: bigint; ``` The [secondsSinceEpoch](/api-reference/onchain-runtime/type-aliases/CallContext.md#secondssinceepoch) of the previous block ### ownAddress[​](#ownaddress "Direct link to ownAddress") ``` ownAddress: ContractAddress; ``` ### parentBlockHash[​](#parentblockhash "Direct link to parentBlockHash") ``` parentBlockHash: string; ``` The hash of the block prior to this transaction, as a hex-encoded string ### secondsSinceEpoch[​](#secondssinceepoch "Direct link to secondsSinceEpoch") ``` secondsSinceEpoch: bigint; ``` The seconds since the UNIX epoch that have elapsed ### secondsSinceEpochErr[​](#secondssinceepocherr "Direct link to secondsSinceEpochErr") ``` secondsSinceEpochErr: number; ``` The maximum error on [secondsSinceEpoch](/api-reference/onchain-runtime/type-aliases/CallContext.md#secondssinceepoch) that should occur, as a positive seconds value --- # CoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CoinCommitment # Type Alias: CoinCommitment ``` type CoinCommitment: string; ``` A Zswap coin commitment, as a hex-encoded 256-bit bitstring --- # CoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CoinPublicKey # Type Alias: CoinPublicKey ``` type CoinPublicKey: string; ``` A user public key capable of receiving Zswap coins, as a hex-encoded 35-byte string --- # CommunicationCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CommunicationCommitment # Type Alias: CommunicationCommitment ``` type CommunicationCommitment: string; ``` A hex-encoded commitment of data shared between two contracts in a call --- # CommunicationCommitmentRand > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / CommunicationCommitmentRand # Type Alias: CommunicationCommitmentRand ``` type CommunicationCommitmentRand: string; ``` The hex-encoded randomness to [CommunicationCommitment](/api-reference/onchain-runtime/type-aliases/CommunicationCommitment.md) --- # ContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ContractAddress # Type Alias: ContractAddress ``` type ContractAddress: string; ``` A contract address, as a hex-encoded 35-byte string --- # DomainSeparator > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / DomainSeparator # Type Alias: DomainSeparator ``` type DomainSeparator: Uint8Array; ``` A token domain seperator, the pre-stage of `TokenType`, as 32-byte bytearray --- # DustTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / DustTokenType # Type Alias: DustTokenType ``` type DustTokenType: { tag: "dust"; }; ``` Dust token type ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### tag[​](#tag "Direct link to tag") ``` tag: "dust"; ``` --- # Effects > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Effects # Type Alias: Effects ``` type Effects: { claimedContractCalls: [bigint, ContractAddress, string, Fr][]; claimedNullifiers: Nullifier[]; claimedShieldedReceives: CoinCommitment[]; claimedShieldedSpends: CoinCommitment[]; claimedUnshieldedSpends: Map<[TokenType, PublicAddress], bigint>; shieldedMints: Map; unshieldedInputs: Map; unshieldedMints: Map; unshieldedOutputs: Map; }; ``` The contract-external effects of a transcript. ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### claimedContractCalls[​](#claimedcontractcalls "Direct link to claimedContractCalls") ``` claimedContractCalls: [bigint, ContractAddress, string, Fr][]; ``` The contracts called from this contract. The values are, in order: * The sequence number of this call * The contract being called * The entry point being called * The communications commitment ### claimedNullifiers[​](#claimednullifiers "Direct link to claimedNullifiers") ``` claimedNullifiers: Nullifier[]; ``` The nullifiers (spends) this contract call requires ### claimedShieldedReceives[​](#claimedshieldedreceives "Direct link to claimedShieldedReceives") ``` claimedShieldedReceives: CoinCommitment[]; ``` The coin commitments (outputs) this contract call requires, as coins received ### claimedShieldedSpends[​](#claimedshieldedspends "Direct link to claimedShieldedSpends") ``` claimedShieldedSpends: CoinCommitment[]; ``` The coin commitments (outputs) this contract call requires, as coins sent ### claimedUnshieldedSpends[​](#claimedunshieldedspends "Direct link to claimedUnshieldedSpends") ``` claimedUnshieldedSpends: Map<[TokenType, PublicAddress], bigint>; ``` The unshielded UTXO outputs this contract expects to be present. ### shieldedMints[​](#shieldedmints "Direct link to shieldedMints") ``` shieldedMints: Map; ``` The shielded tokens minted in this call, as a map from hex-encoded 256-bit domain separators to unsigned 64-bit integers. ### unshieldedInputs[​](#unshieldedinputs "Direct link to unshieldedInputs") ``` unshieldedInputs: Map; ``` The unshielded inputs this contract expects. ### unshieldedMints[​](#unshieldedmints "Direct link to unshieldedMints") ``` unshieldedMints: Map; ``` The unshielded tokens minted in this call, as a map from hex-encoded 256-bit domain separators to unsigned 64-bit integers. ### unshieldedOutputs[​](#unshieldedoutputs "Direct link to unshieldedOutputs") ``` unshieldedOutputs: Map; ``` The unshielded outputs this contract authorizes. --- # EncodedStateValue > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / EncodedStateValue # Type Alias: EncodedStateValue ``` type EncodedStateValue: | { tag: "null"; } | { content: AlignedValue; tag: "cell"; } | { content: Map; tag: "map"; } | { content: EncodedStateValue[]; tag: "array"; } | { content: [number, Map]; tag: "boundedMerkleTree"; }; ``` An alternative encoding of [StateValue](/api-reference/onchain-runtime/classes/StateValue.md) for use in [Op](/api-reference/onchain-runtime/type-aliases/Op.md) for technical reasons --- # FeePrices > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / FeePrices # Type Alias: FeePrices ``` type FeePrices: { blockUsageFactor: number; computeFactor: number; overallPrice: number; readFactor: number; writeFactor: number; }; ``` The fee prices for transaction ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### blockUsageFactor[​](#blockusagefactor "Direct link to blockUsageFactor") ``` blockUsageFactor: number; ``` The price factor of block usage. ### computeFactor[​](#computefactor "Direct link to computeFactor") ``` computeFactor: number; ``` The price factor of time spent in single-threaded compute. ### overallPrice[​](#overallprice "Direct link to overallPrice") ``` overallPrice: number; ``` The overall price of a full block in an average cost dimension. ### readFactor[​](#readfactor "Direct link to readFactor") ``` readFactor: number; ``` The price factor of time spent reading from disk. ### writeFactor[​](#writefactor "Direct link to writeFactor") ``` writeFactor: number; ``` The price factor of time spent writing to disk. --- # Fr > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Fr # Type Alias: Fr ``` type Fr: Uint8Array; ``` An internal encoding of a value of the proof systems scalar field --- # GatherResult > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / GatherResult # Type Alias: GatherResult ``` type GatherResult: { content: AlignedValue; tag: "read"; } | { content: EncodedStateValue; tag: "log"; }; ``` An individual result of observing the results of a non-verifying VM program execution --- # Key > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Key # Type Alias: Key ``` type Key: { tag: "value"; value: AlignedValue; } | { tag: "stack"; }; ``` A key used to index into an array or map in the onchain VM --- # Nonce > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Nonce # Type Alias: Nonce ``` type Nonce: string; ``` A Zswap nonce, as a hex-encoded 256-bit string --- # Nullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Nullifier # Type Alias: Nullifier ``` type Nullifier: string; ``` A Zswap nullifier, as a hex-encoded 256-bit bitstring --- # Op > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Op # Type Alias: Op\ ``` type Op: | { noop: { n: number; }; } | "lt" | "eq" | "type" | "size" | "new" | "and" | "or" | "neg" | "log" | "root" | "pop" | { popeq: { cached: boolean; result: R; }; } | { addi: { immediate: number; }; } | { subi: { immediate: number; }; } | { push: { storage: boolean; value: EncodedStateValue; }; } | { branch: { skip: number; }; } | { jmp: { skip: number; }; } | "add" | "sub" | { concat: { cached: boolean; n: number; }; } | "member" | { rem: { cached: boolean; }; } | { dup: { n: number; }; } | { swap: { n: number; }; } | { idx: { cached: boolean; path: Key[]; pushPath: boolean; }; } | { ins: { cached: boolean; n: number; }; } | "ckpt"; ``` An individual operation in the onchain VM ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") • **R** `null` or [AlignedValue](/api-reference/onchain-runtime/type-aliases/AlignedValue.md), for gathering and verifying mode respectively --- # PublicAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / PublicAddress # Type Alias: PublicAddress ``` type PublicAddress: { address: UserAddress; tag: "user"; } | { address: ContractAddress; tag: "contract"; }; ``` A public address that an entity can be identified by --- # QualifiedShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / QualifiedShieldedCoinInfo # Type Alias: QualifiedShieldedCoinInfo ``` type QualifiedShieldedCoinInfo: { mt_index: bigint; nonce: Nonce; type: RawTokenType; value: bigint; }; ``` Information required to spend an existing coin, alongside authorization of the owner ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` The coin's location in the chain's Merkle tree of coin commitments Bounded to be a non-negative 64-bit integer ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The coin's type, identifying the currency it represents ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # RawTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / RawTokenType # Type Alias: RawTokenType ``` type RawTokenType: string; ``` The internal identifier attached to a [TokenType](/api-reference/onchain-runtime/type-aliases/TokenType.md), as a hex-encoded string. --- # RunningCost > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / RunningCost # Type Alias: RunningCost ``` type RunningCost: { bytesDeleted: bigint; bytesWritten: bigint; computeTime: bigint; readTime: bigint; }; ``` A running tally of synthetic resource costs. ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### bytesDeleted[​](#bytesdeleted "Direct link to bytesDeleted") ``` bytesDeleted: bigint; ``` The number of (modelled) bytes deleted. ### bytesWritten[​](#byteswritten "Direct link to bytesWritten") ``` bytesWritten: bigint; ``` The number of (modelled) bytes written. ### computeTime[​](#computetime "Direct link to computeTime") ``` computeTime: bigint; ``` The amount of (modelled) time spent in single-threaded compute, measured in picoseconds. ### readTime[​](#readtime "Direct link to readTime") ``` readTime: bigint; ``` The amount of (modelled) time spent reading from disk, measured in picoseconds. --- # ShieldedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ShieldedCoinInfo # Type Alias: ShieldedCoinInfo ``` type ShieldedCoinInfo: { nonce: Nonce; type: RawTokenType; value: bigint; }; ``` Information required to create a new coin, alongside details about the recipient ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` The coin's randomness, preventing it from colliding with other coins ### type[​](#type "Direct link to type") ``` type: RawTokenType; ``` The coin's type, identifying the currency it represents ### value[​](#value "Direct link to value") ``` value: bigint; ``` The coin's value, in atomic units dependent on the currency Bounded to be a non-negative 64-bit integer --- # ShieldedTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / ShieldedTokenType # Type Alias: ShieldedTokenType ``` type ShieldedTokenType: { raw: RawTokenType; tag: "shielded"; }; ``` Shielded token type (or color), as a hex-encoded 35-byte string ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### raw[​](#raw "Direct link to raw") ``` raw: RawTokenType; ``` ### tag[​](#tag "Direct link to tag") ``` tag: "shielded"; ``` --- # Signature > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Signature # Type Alias: Signature ``` type Signature: string; ``` A hex-encoded signature BIP-340 signature, with a 3-byte version prefix --- # SignatureVerifyingKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / SignatureVerifyingKey # Type Alias: SignatureVerifyingKey ``` type SignatureVerifyingKey: string; ``` A hex-encoded signature BIP-340 verifying key, with a 3-byte version prefix --- # SigningKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / SigningKey # Type Alias: SigningKey ``` type SigningKey: string; ``` A hex-encoded signature BIP-340 signing key, with a 3-byte version prefix --- # TokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / TokenType # Type Alias: TokenType ``` type TokenType: UnshieldedTokenType | ShieldedTokenType | DustTokenType; ``` A token type (or color), as a hex-encoded 35-byte string, shielded, unshielded, or Dust --- # Transcript > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Transcript # Type Alias: Transcript\ ``` type Transcript: { effects: Effects; gas: RunningCost; program: Op[]; }; ``` A transcript of operations, to be recorded in a transaction ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") • **R** ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### effects[​](#effects "Direct link to effects") ``` effects: Effects; ``` The effects of the transcript, which are checked before execution, and must match those constructed by [program](/api-reference/onchain-runtime/type-aliases/Transcript.md#program) ### gas[​](#gas "Direct link to gas") ``` gas: RunningCost; ``` The execution budget for this transcript, which [program](/api-reference/onchain-runtime/type-aliases/Transcript.md#program) must not exceed ### program[​](#program "Direct link to program") ``` program: Op[]; ``` The sequence of operations that this transcript captured --- # UnshieldedTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / UnshieldedTokenType # Type Alias: UnshieldedTokenType ``` type UnshieldedTokenType: { raw: RawTokenType; tag: "unshielded"; }; ``` Unshielded token type (or color), as a hex-encoded 35-byte string ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### raw[​](#raw "Direct link to raw") ``` raw: RawTokenType; ``` ### tag[​](#tag "Direct link to tag") ``` tag: "unshielded"; ``` --- # UserAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / UserAddress # Type Alias: UserAddress ``` type UserAddress: string; ``` A user public key address, as a hex-encoded 35-byte string --- # Value > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/onchain-runtime v3.0.0**](/api-reference/onchain-runtime.md) *** [@midnight-ntwrk/onchain-runtime](/api-reference/onchain-runtime/globals.md) / Value # Type Alias: Value ``` type Value: Uint8Array[]; ``` An onchain data value, in field-aligned binary format. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Authentication Midnight Network does not use traditional authentication methods. However, to submit transactions and interact with contracts, you must configure providers and sign transaction intents using your wallet address. ## Configure providers[​](#configure-providers "Direct link to Configure providers") The [Midnight.js](/sdks/official/midnight-js.md) package enables you to deploy contracts and interact with them. To configure providers, you need to create a `MidnightProviders` object. This object defines the providers for submitting transactions and interacting with contracts. ``` const providers: MidnightProviders = { privateStateProvider: levelPrivateStateProvider({ privateStoragePasswordProvider: () => password, accountId: walletAddress, }), } ``` The `privateStateProvider` is responsible for storing and retrieving private state from the network. It requires the following properties: * `privateStoragePasswordProvider`: A function that returns the password to the private state provider. * `accountId`: The wallet address to sign transactions with. note The provider implementation above is for demonstration and intentionally omits some configuration. For the full provider configuration, see the [Midnight.js](/sdks/official/midnight-js.md) documentation. ## Submit transactions[​](#submit-transactions "Direct link to Submit transactions") Any operation that modifies the state of the network requires a signature from your wallet address and a transaction. Each transaction cost gas which you must pay using DUST balance on your wallet. DUST is the network resource that fuels transactions on the Midnight Network. Your wallet generates DUST from NIGHT tokens. You must delegate NIGHT tokens in your wallet to generate DUST. If you don't have any DUST balance, then you cannot submit transactions or deploy contracts. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Usage limits Midnight Network includes two types of usage limits: block limits and transaction limits. ## Block limits[​](#block-limits "Direct link to Block limits") Midnight uses a multi-dimensional cost model rather than a single byte cap per block. The following table shows the dimensions and their limits: | Dimension | Limit per block | Description | | ----------------------------------- | --------------- | ----------------------------------------------- | | `block_usage` (broadcast bytes) | 200,000 bytes | Bytes of transaction data included in the block | | `bytes_written` (persistent writes) | 50,000 bytes | Net bytes written to disk permanently | | `bytes_churned` (temp writes) | 1,000,000 bytes | Bytes written temporarily or overwritten | | Read time budget | 1 second | I/O read cost across all txs in the block | | Compute time budget | 1 second | Compute cost across all txs in the block | The Substrate layer also imposes an overall 1 MB block byte limit, with \~786 KB available for normal transactions (75% of 1 MB). Block time is 6 seconds. ## Transaction limits[​](#transaction-limits "Direct link to Transaction limits") The maximum transaction size is 1 MiB (1,048,576 bytes). This is the serialized byte size of the entire transaction. It's enforced during well-formedness validation. Transactions exceeding it are rejected with `MalformedTransaction::TransactionTooLarge`. info Both the block and transaction limits are configurable ledger parameters and can be adjusted via governance. ### Per account transaction limit[​](#per-account-transaction-limit "Direct link to Per account transaction limit") There is also a per-account throttle of up to 10 MB of transaction data per day (across a rolling window of 14,400 blocks at 6s/block). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Testkit JS API **@midnight-ntwrk/testkit-js v4.0.4** *** # What is this? A comprehensive testing solution for your Midnight.JS applications, providing seamless integration with various test environments. This package was created for the [Midnight network](https://midnight.network). Please visit the [Midnight Developer Hub](https://midnight.network/developer-hub) to learn more. # Use only in Midnight test environments Image exclusively for Midnight test environments use. # Agree to Terms By downloading and using this image, you agree to [Midnight’s Terms and Conditions](https://midnight.network/static/terms.pdf), which includes the [Privacy Policy](https://midnight.network/static/privacy-policy.pdf). # License The software provided herein is licensed under the [Apache License V2.0](http://www.apache.org/licenses/LICENSE-2.0). ## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") 1. [Installation](#installation) 2. [Getting Started](#getting-started) 3. [Features](#Features) 4. [Limitations](#Limitations) 5. [Examples of Usage](#Examples-of-Usage) 6. [Containers Configuration](#8-containers-configuration) *** ## Installation[​](#installation "Direct link to Installation") Before using the testing library, ensure you have the following prerequisites: 1. Node.js and yarn installed 2. Docker Desktop (optional for local dockerized tests) 3. Midnight.JS project set up Install the testing library by running the following command in your terminal: ``` yarn add -D @midnight-ntwrk/testkit-js ``` ## Getting Started[​](#getting-started "Direct link to Getting Started") To use the testing library, create a new file called `midnight.test.js` in the `__tests__` directory of your project. In this file, import the necessary dependencies: ``` import { getTestEnvironment } from '@midnight-ntwrk/testkit-js'; beforeAll(async () => { testEnvironment = getTestEnvironment(logger); environmentConfiguration = await testEnvironment.start(); walletProvider = await testEnvironment.getMidnightWalletProvider(); }); afterAll(async () => { await testEnvironment.shutdown(); }); ``` *** ## Features[​](#features "Direct link to Features") Set of functions that simplify testing of DApps in Midnight * Standard Dockerized environment setup - both live and local * Predefined Midnight environments configuration * Proof server control * Wallets management * Fund wallets * Check system health *** ## Environment variables[​](#environment-variables "Direct link to Environment variables") ### Environment selection:[​](#environment-selection "Direct link to Environment selection:") * MN\_TEST\_ENVIRONMENT controls the environment to be used for testing. It can take one of these values: * undeployed * qanet * preview * preprod * env-var-remote If **MN\_TEST\_ENVIRONMENT** is not set, the default value will be `undeployed`. If **MN\_TEST\_ENVIRONMENT** is set to `undeployed`, the testing environment will be deployed locally using Docker. If **MN\_TEST\_ENVIRONMENT** is set to `qanet`, `preview`, `preprod`, or `env-var-remote` the testing environment will be the corresponding live network, with proof server setup using predefined NETWORK\_ID. If **MN\_TEST\_ENVIRONMENT** is set to `env-var-remote`, below environment variables must be set: * *MN\_TEST\_NETWORK\_ID* - Proof server NETWORK\_ID * *MN\_TEST\_INDEXER* - Indexer URL * *MN\_TEST\_INDEXER\_WS* - Indexer WebSocket URL * *MN\_TEST\_NODE* - Node URL * *MN\_TEST\_FAUCET* - Faucet URL ### Wallet setup:[​](#wallet-setup "Direct link to Wallet setup:") * MN\_TEST\_WALLET\_SEED can be used to set a specific seed phrase for the wallet. If not set, a random seed phrase will be used. *** ## Limitations[​](#limitations "Direct link to Limitations") * Localnet wallets limit count is 4 *** ## Examples of Usage[​](#examples-of-usage "Direct link to Examples of Usage") ### 1. Selecting Different Environments[​](#1-selecting-different-environments "Direct link to 1. Selecting Different Environments") You can control the test environment using the `MN_TEST_ENVIRONMENT` environment variable. Here's how you can set it: ``` const testEnvironment = getTestEnvironment(logger); environmentConfiguration = await testEnvironment.start(); ``` ``` # Example: Set the environment variable before initializing the test environment MN_TEST_ENVIRONMENT='preview'; yarn test ``` This allows you to easily switch between predefined environments like `qanet`, `preview`, `preprod`, and others. Default (undefined) value is `undeployed` which will deploy the testing environment locally using Docker. *** ### 2. Creating and Managing Wallets[​](#2-creating-and-managing-wallets "Direct link to 2. Creating and Managing Wallets") Here's an example of creating wallets in your test environment: ``` // Example: Create multiple wallets in a test environment const testEnvironment = getTestEnvironment(logger); await testEnvironment.start(); // Create 2 wallets const wallets = await testEnvironment.startMidnightWalletProviders(2); // Verify wallet properties expect(wallets).toHaveLength(2); wallets.forEach(async (wallet) => { expect(wallet.coinPublicKey).not.toBeUndefined(); }); // Shutdown the environment after testing await testEnvironment.shutdown(); ``` This demonstrates how to create wallets and verify their properties, such as the `coinPublicKey`. *** ### 3. Setting Wallet Seeds[​](#3-setting-wallet-seeds "Direct link to 3. Setting Wallet Seeds") If you need to use specific wallet seeds for testing, you can do the following: ``` // Example: Create a wallet with a predefined seed phrase const wallet = await testEnvironment.getMidnightWalletProvider(); expect(wallet.coinPublicKey).not.toBeUndefined(); ``` ``` # Example: Set the environment variable before initializing the test environment MN_TEST_WALLET_SEED='00000000000000000000000000000042'; yarn test ``` This allows you to test specific scenarios using known wallet seeds. *** ### 4. Handling Environment Configuration[​](#4-handling-environment-configuration "Direct link to 4. Handling Environment Configuration") You can also customize the test environment configuration by modifying the `defaultContainersConfiguration` object: ``` import { defaultContainersConfiguration, getContainersConfiguration, setContainersConfiguration } from '../configuration'; // Example: Modify default environment configuration before starting const config: ContainersConfiguration = { ...defaultContainersConfiguration, proofServer: { ...defaultContainersConfiguration.proofServer, fileName: 'proof-server.yml' } }; setContainersConfiguration(config); ``` This gives developers flexibility in configuring the test environment according to their needs. *** ### 5. Error Handling[​](#5-error-handling "Direct link to 5. Error Handling") Here's an example of handling errors when setting up wallets: ``` // Example: Test for maximum wallet limit exceeded process.env.MN_TEST_ENVIRONMENT = undefined; // Use local environment const testEnvironment = getTestEnvironment(logger); await testEnvironment.start(); try { await testEnvironment.startMidnightWalletProviders(5); // Assuming max is 4 } catch (error) { expect(error.message).toContain('Maximum supported number of wallets for this environment reached'); } await testEnvironment.shutdown(); ``` This demonstrates how to handle cases where the wallet limit is exceeded. *** ### 6. Advanced Usage with Proof Server[​](#6-advanced-usage-with-proof-server "Direct link to 6. Advanced Usage with Proof Server") Here's an example of integrating with the proof server: ``` // Example: Start a proof server with network ID = preview and ID = 123 const proofServer = await DynamicProofServerContainer.start(logger, '123', 'preview'); //stop the proof server await proofServer.stop(); ``` This shows how to integrate with and customize the proof server for testing. *** ### 7. Customized test environments[​](#7-customized-test-environments "Direct link to 7. Customized test environments") Library is provided with set of predefined environment configurations i.e.: * LocalTestEnvironment * PreviewTestEnvironment * PreprodTestEnvironment By using `getTestEnvironment(logger);` based on environment variable MN\_TEST\_ENVIRONMENT test environment configuration is provided. However, you can either create your own class defining the environment endpoints or use below enviroment variables. Here's an example of fully customized endpoints of the test environment, that you can provide using environment variables: ``` MN_TEST_ENVIRONMENT="env-var-remote" \ MN_TEST_NETWORK_ID="undeployed" \ MN_TEST_INDEXER="http://localhost:3085/api/" \ MN_TEST_INDEXER_WS="ws://localhost:3085/ws/" \ MN_TEST_NODE="http://localhost:3086" \ yarn test ``` *** ### 8. Containers Configuration[​](#8-containers-configuration "Direct link to 8. Containers Configuration") The testkit uses a centralized `ContainersConfiguration` object that controls proof server, standalone containers, and logging. Two predefined configurations are available: * `defaultContainersConfiguration` — uses `proof-server.yml` and `compose.yml` * `latestContainersConfiguration` — uses `proof-server-latest.yml` and `compose-latest.yml` You can read and modify the active configuration at any time using `getContainersConfiguration()` and `setContainersConfiguration()`. #### Configuration structure[​](#configuration-structure "Direct link to Configuration structure") ``` interface ContainersConfiguration { proofServer: { path: string; // Directory with the compose file (default: cwd) fileName: string; // Compose file name (default: 'proof-server.yml') container: { name: string; // Container name (default: 'proof-server') port: number; // Exposed port (default: 6300) waitStrategy: WaitStrategy; }; }; standalone: { path: string; // Directory with the compose file (default: cwd) fileName: string; // Compose file name (default: 'compose.yml') container: { proofServer: { name, port, waitStrategy }; // default: 'proof-server', 6300 node: { name, port, waitStrategy }; // default: 'node', 9944 indexer: { name, port, waitStrategy }; // default: 'indexer', 8088 }; }; log: { path: string; // Log directory (default: '/logs/tests/') fileName: string; // Log file name (default: 'tests_.log') level: string; // Log level (default: 'info') }; } ``` #### Proof server configuration[​](#proof-server-configuration "Direct link to Proof server configuration") Controls the proof server container used in both standalone and remote environments. ``` import { defaultContainersConfiguration, setContainersConfiguration } from '@midnight-ntwrk/testkit-js'; setContainersConfiguration({ ...defaultContainersConfiguration, proofServer: { ...defaultContainersConfiguration.proofServer, fileName: 'my-proof-server.yml', container: { ...defaultContainersConfiguration.proofServer.container, port: 7300 } } }); ``` #### Standalone containers configuration[​](#standalone-containers-configuration "Direct link to Standalone containers configuration") Controls the full local environment (node, indexer, proof server) started via Docker Compose. ``` import { Wait } from 'testcontainers'; import { defaultContainersConfiguration, setContainersConfiguration } from '@midnight-ntwrk/testkit-js'; setContainersConfiguration({ ...defaultContainersConfiguration, standalone: { ...defaultContainersConfiguration.standalone, fileName: 'my-compose.yml', container: { ...defaultContainersConfiguration.standalone.container, node: { ...defaultContainersConfiguration.standalone.container.node, port: 9955, waitStrategy: Wait.forListeningPorts().withStartupTimeout(5 * 60_000) } } } }); ``` #### Logging configuration[​](#logging-configuration "Direct link to Logging configuration") The testkit uses [pino](https://github.com/pinojs/pino) with pretty-printing. Logs are written both to the console and to a file. **Default values:** * **Log level**: `info` * **Log file**: `tests_.log` (e.g. `tests_2026-03-10T12_00_00.000Z.log`) * **Log directory**: `/logs/tests/` **Available log levels** (from least to most verbose): `fatal`, `error`, `warn`, `info`, `debug`, `trace` ``` import { defaultContainersConfiguration, setContainersConfiguration } from '@midnight-ntwrk/testkit-js'; setContainersConfiguration({ ...defaultContainersConfiguration, log: { ...defaultContainersConfiguration.log, level: 'debug', path: '/custom/log/directory', fileName: 'my-tests.log' } }); ``` **Creating custom loggers:** ``` import { createLogger, createDefaultTestLogger } from '@midnight-ntwrk/testkit-js'; // Logger with default configuration const logger = createDefaultTestLogger(); // Logger writing to a specific file (within the configured log directory) const customLogger = createLogger('my-custom-test.log'); // Logger writing to an absolute path const absoluteLogger = createLogger('/tmp/my-test.log'); ``` #### Using the latest configuration[​](#using-the-latest-configuration "Direct link to Using the latest configuration") To use the latest container images instead of the default pinned versions: ``` import { latestContainersConfiguration, setContainersConfiguration } from '@midnight-ntwrk/testkit-js'; setContainersConfiguration(latestContainersConfiguration); ``` *** ### 9. System health check before tests[​](#9-system-health-check-before-tests "Direct link to 9. System health check before tests") For the remote test environments (preview, preprod, ...) simple health check is performed for each of the components to check their state before test. --- # DAppConnectorInitialAPI > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Implements[​](#implements "Direct link to Implements") * `InitialAPI` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new DAppConnectorInitialAPI**(`connectedWallet`, `networkId`, `options?`): `DAppConnectorInitialAPI` #### Parameters[​](#parameters "Direct link to Parameters") ##### connectedWallet[​](#connectedwallet "Direct link to connectedWallet") `ConnectedAPI` ##### networkId[​](#networkid "Direct link to networkId") `string` ##### options?[​](#options "Direct link to options?") ###### apiVersion?[​](#apiversion "Direct link to apiVersion?") `string` ###### icon?[​](#icon "Direct link to icon?") `string` ###### name?[​](#name "Direct link to name?") `string` ###### rdns?[​](#rdns "Direct link to rdns?") `string` #### Returns[​](#returns "Direct link to Returns") `DAppConnectorInitialAPI` ## Properties[​](#properties "Direct link to Properties") ### apiVersion[​](#apiversion-1 "Direct link to apiVersion") > `readonly` **apiVersion**: `string` Version of the API implemented by this instance of the API, string containing a version of the API package @midnight-ntwrk/dapp-connector-api that was used in implementation E.g. wallet implementing version 3.1.5 provides apiVersion with value '3.1.5' This value lets DApps to differentiate between different versions of the API and implement appropriate logic for each version or not use some versions at all #### Implementation of[​](#implementation-of "Direct link to Implementation of") `InitialAPI.apiVersion` *** ### icon[​](#icon-1 "Direct link to icon") > `readonly` **icon**: `string` Wallet icon, as an URL, either reference to a hosted resource, or a base64 encoded data URL. It is expected to be displayed to the user. Because of this, DApps need to display the icon in a secure fashion to prevent XSS. For example, displaying the icon using an `img` tag. #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") `InitialAPI.icon` *** ### name[​](#name-1 "Direct link to name") > `readonly` **name**: `string` Wallet name, expected to be displayed to the user. As such, DApps need to sanitize the name to prevent XSS when displaying it to the user. An example of sanitization is displaying the name using a text node. #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") `InitialAPI.name` *** ### rdns[​](#rdns-1 "Direct link to rdns") > `readonly` **rdns**: `string` Wallet identifier, in a reverse DNS notation (e.g. `com.example.wallet`). Wallets should keep this identifier stable throughout the lifecycle of the product. DApps can use this property to identify the wallet, but should be prepared to handle values that are unknown, invalid, or potentially misleading, similar to handling user agent strings in web browsers. #### Implementation of[​](#implementation-of-3 "Direct link to Implementation of") `InitialAPI.rdns` ## Methods[​](#methods "Direct link to Methods") ### connect()[​](#connect "Direct link to connect()") > **connect**(`networkId`): `Promise`<`ConnectedAPI`> Connect to wallet, hinting desired network id; Use 'mainnet' for mainnet. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### networkId[​](#networkid-1 "Direct link to networkId") `string` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`ConnectedAPI`> #### Implementation of[​](#implementation-of-4 "Direct link to Implementation of") `InitialAPI.connect` --- # DAppConnectorWalletAdapter > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Implements[​](#implements "Direct link to Implements") * `ConnectedAPI` ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new DAppConnectorWalletAdapter**(`walletProvider`, `environmentConfiguration`): `DAppConnectorWalletAdapter` #### Parameters[​](#parameters "Direct link to Parameters") ##### walletProvider[​](#walletprovider "Direct link to walletProvider") `Pick`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md), `"wallet"` | `"unshieldedKeystore"` | `"zswapSecretKeys"` | `"dustSecretKey"`> ##### environmentConfiguration[​](#environmentconfiguration "Direct link to environmentConfiguration") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) #### Returns[​](#returns "Direct link to Returns") `DAppConnectorWalletAdapter` ## Methods[​](#methods "Direct link to Methods") ### balanceSealedTransaction()[​](#balancesealedtransaction "Direct link to balanceSealedTransaction()") > **balanceSealedTransaction**(`tx`, `options?`): `Promise`<{ `tx`: `string`; }> Take sealed transaction (with proofs, signatures and cryptographically bound), pay fees, add necessary inputs and outputs to remove imbalances from it, returning a transaction ready for submission This method is mainly expected to be used by DApps when they operate on transactions created by the wallet or when the DApp wants to be sure that wallet performs balancing in a separate intent. In such case, it is important to remember that some contracts might make use of fallible sections, in which case wallet won't be able to properly balance the transaction. In such cases, the DApp should use [balanceUnsealedTransaction](#balanceunsealedtransaction) instead. In relation to Ledger API (`@midnight-ntwrk/ledger-v`), this method expects a serialized transaction of type `Transaction` Options: `payFees` - whether wallet should pay fees for the issued transaction or not, true by default #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### tx[​](#tx "Direct link to tx") `string` ##### options?[​](#options "Direct link to options?") ###### payFees?[​](#payfees "Direct link to payFees?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> #### Implementation of[​](#implementation-of "Direct link to Implementation of") `ConnectedAPI.balanceSealedTransaction` *** ### balanceUnsealedTransaction()[​](#balanceunsealedtransaction "Direct link to balanceUnsealedTransaction()") > **balanceUnsealedTransaction**(`tx`, `options?`): `Promise`<{ `tx`: `string`; }> Take unsealed transaction (with proofs, with no signatures and with preimage data for cryptographic binding), pay fees, add necessary inputs and outputs to remove imbalances from it, returning a transaction ready for submission This method is expected to be used by DApps when interacting with contracts - in many cases when contracts interact with native tokens, where wallet may need to add inputs and outputs to an existing intent to properly balance the transaction. In relation to Ledger API (`@midnight-ntwrk/ledger-v`), this method expects a serialized transaction of type `Transaction` Options: `payFees` - whether wallet should pay fees for the issued transaction or not, true by default #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### tx[​](#tx-1 "Direct link to tx") `string` ##### options?[​](#options-1 "Direct link to options?") ###### payFees?[​](#payfees-1 "Direct link to payFees?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") `ConnectedAPI.balanceUnsealedTransaction` *** ### getConfiguration()[​](#getconfiguration "Direct link to getConfiguration()") > **getConfiguration**(): `Promise`<`Configuration`> Get the configuration of the services used by the wallet. It is important for DApps to make use of those services whenever possible, as the wallet user might have some preferences in this regard, which e.g. improve privacy or performance. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`Configuration`> #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") `ConnectedAPI.getConfiguration` *** ### getConnectionStatus()[​](#getconnectionstatus "Direct link to getConnectionStatus()") > **getConnectionStatus**(): `Promise`<`ConnectionStatus`> Status of an existing connection to wallet DApps can use this method to check if the connection is still valid. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`ConnectionStatus`> #### Implementation of[​](#implementation-of-3 "Direct link to Implementation of") `ConnectedAPI.getConnectionStatus` *** ### getDustAddress()[​](#getdustaddress "Direct link to getDustAddress()") > **getDustAddress**(): `Promise`<{ `dustAddress`: `string`; }> Get the Dust address of the wallet. It is provided in Bech32m format. #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<{ `dustAddress`: `string`; }> #### Implementation of[​](#implementation-of-4 "Direct link to Implementation of") `ConnectedAPI.getDustAddress` *** ### getDustBalance()[​](#getdustbalance "Direct link to getDustBalance()") > **getDustBalance**(): `Promise`<{ `balance`: `bigint`; `cap`: `bigint`; }> Get the balance of Dust of the wallet. It reports both: * the current balance (which may change over time due to generation mechanics) * the cap (the maximum amount of Dust that can be generated from the current Night balance). #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<{ `balance`: `bigint`; `cap`: `bigint`; }> #### Implementation of[​](#implementation-of-5 "Direct link to Implementation of") `ConnectedAPI.getDustBalance` *** ### getProvingProvider()[​](#getprovingprovider "Direct link to getProvingProvider()") > **getProvingProvider**(`keyMaterialProvider`): `Promise`<`ProvingProvider`> Obtain the proving provider from the wallet to delegate proving to the wallet. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### keyMaterialProvider[​](#keymaterialprovider "Direct link to keyMaterialProvider") `KeyMaterialProvider` object resolving prover and verifier keys, as well as the ZKIR representation of the circuit; `KeyMaterialProvider` is almost identical to the one in Midnight.js's `ZKConfigProvider` () #### Returns[​](#returns-7 "Direct link to Returns") `Promise`<`ProvingProvider`> A `ProvingProvider` instance, compatible with Ledger's ProvingProvider () #### Implementation of[​](#implementation-of-6 "Direct link to Implementation of") `ConnectedAPI.getProvingProvider` *** ### getShieldedAddresses()[​](#getshieldedaddresses "Direct link to getShieldedAddresses()") > **getShieldedAddresses**(): `Promise`<{ `shieldedAddress`: `string`; `shieldedCoinPublicKey`: `string`; `shieldedEncryptionPublicKey`: `string`; }> Get the shielded addresses of the wallet. For convenience it also returns the coin public key and encryption public key. All of them are provided in Bech32m format. #### Returns[​](#returns-8 "Direct link to Returns") `Promise`<{ `shieldedAddress`: `string`; `shieldedCoinPublicKey`: `string`; `shieldedEncryptionPublicKey`: `string`; }> #### Implementation of[​](#implementation-of-7 "Direct link to Implementation of") `ConnectedAPI.getShieldedAddresses` *** ### getShieldedBalances()[​](#getshieldedbalances "Direct link to getShieldedBalances()") > **getShieldedBalances**(): `Promise`<`Record`<`string`, `bigint`>> Get the balances of shielded tokens of the wallet. They are represented as a record, whose keys are token types. #### Returns[​](#returns-9 "Direct link to Returns") `Promise`<`Record`<`string`, `bigint`>> #### Implementation of[​](#implementation-of-8 "Direct link to Implementation of") `ConnectedAPI.getShieldedBalances` *** ### getTxHistory()[​](#gettxhistory "Direct link to getTxHistory()") > **getTxHistory**(`_pageNumber`, `_pageSize`): `Promise`<`HistoryEntry`\[]> Get the history of transactions of the wallet. Each history entry is a simplistic record of the fact that a transaction is relevant to the wallet. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### \_pageNumber[​](#_pagenumber "Direct link to _pageNumber") `number` ##### \_pageSize[​](#_pagesize "Direct link to _pageSize") `number` #### Returns[​](#returns-10 "Direct link to Returns") `Promise`<`HistoryEntry`\[]> #### Implementation of[​](#implementation-of-9 "Direct link to Implementation of") `ConnectedAPI.getTxHistory` *** ### getUnshieldedAddress()[​](#getunshieldedaddress "Direct link to getUnshieldedAddress()") > **getUnshieldedAddress**(): `Promise`<{ `unshieldedAddress`: `string`; }> Get the unshielded address of the wallet. It is provided in Bech32m format. #### Returns[​](#returns-11 "Direct link to Returns") `Promise`<{ `unshieldedAddress`: `string`; }> #### Implementation of[​](#implementation-of-10 "Direct link to Implementation of") `ConnectedAPI.getUnshieldedAddress` *** ### getUnshieldedBalances()[​](#getunshieldedbalances "Direct link to getUnshieldedBalances()") > **getUnshieldedBalances**(): `Promise`<`Record`<`string`, `bigint`>> Get the balances of unshielded tokens (potentially including Night) of the wallet. They are represented as a record, whose keys are token types. #### Returns[​](#returns-12 "Direct link to Returns") `Promise`<`Record`<`string`, `bigint`>> #### Implementation of[​](#implementation-of-11 "Direct link to Implementation of") `ConnectedAPI.getUnshieldedBalances` *** ### hintUsage()[​](#hintusage "Direct link to hintUsage()") > **hintUsage**(`_methodNames`): `Promise`<`void`> Hint usage of methods to the wallet. DApps should use this method to hint to the wallet what methods are expected to be used in a certain context (be it a whole session, single view, or a user flow - it is up to DApp). The wallet can use these calls as an opportunity to ask user for permissions and in such case - resolve the promise only after the user has granted the permissions. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### \_methodNames[​](#_methodnames "Direct link to _methodNames") keyof `WalletConnectedAPI`\[] #### Returns[​](#returns-13 "Direct link to Returns") `Promise`<`void`> #### Implementation of[​](#implementation-of-12 "Direct link to Implementation of") `ConnectedAPI.hintUsage` *** ### makeIntent()[​](#makeintent "Direct link to makeIntent()") > **makeIntent**(`_desiredInputs`, `_desiredOutputs`, `_options`): `Promise`<{ `tx`: `string`; }> Initialize a transaction with unbalanced intent containing desired inputs and outputs. Primary use-case for this method is to create a transaction, which inits a swap Options: `intentId` - what id use for created intent: use 1 to ensure no transaction merging will result in actions executed before created intent in the same transaction use specific number within ledger limitations to make the intent have that segment id assigned use "random" to allow wallet to pick one in random (e.g. when creating intent for swap purposes) `payFees` - whether wallet should pay fees for the issued transaction or not #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### \_desiredInputs[​](#_desiredinputs "Direct link to _desiredInputs") `DesiredInput`\[] ##### \_desiredOutputs[​](#_desiredoutputs "Direct link to _desiredOutputs") `DesiredOutput`\[] ##### \_options[​](#_options "Direct link to _options") ###### intentId[​](#intentid "Direct link to intentId") `number` | `"random"` ###### payFees[​](#payfees-2 "Direct link to payFees") `boolean` #### Returns[​](#returns-14 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> #### Implementation of[​](#implementation-of-13 "Direct link to Implementation of") `ConnectedAPI.makeIntent` *** ### makeTransfer()[​](#maketransfer "Direct link to makeTransfer()") > **makeTransfer**(`_desiredOutputs`, `_options?`): `Promise`<{ `tx`: `string`; }> Initialize a transfer transaction with desired outputs Options: `payFees` - whether wallet should pay fees for the issued transaction or not, true by default #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### \_desiredOutputs[​](#_desiredoutputs-1 "Direct link to _desiredOutputs") `DesiredOutput`\[] ##### \_options?[​](#_options-1 "Direct link to _options?") ###### payFees?[​](#payfees-3 "Direct link to payFees?") `boolean` #### Returns[​](#returns-15 "Direct link to Returns") `Promise`<{ `tx`: `string`; }> #### Implementation of[​](#implementation-of-14 "Direct link to Implementation of") `ConnectedAPI.makeTransfer` *** ### signData()[​](#signdata "Direct link to signData()") > **signData**(`data`, `options`): `Promise`<`Signature`> Sign provided data using key and format specified in the options, data to sign will be prepended with right prefix #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### data[​](#data "Direct link to data") `string` ##### options[​](#options-2 "Direct link to options") `SignDataOptions` #### Returns[​](#returns-16 "Direct link to Returns") `Promise`<`Signature`> #### Implementation of[​](#implementation-of-15 "Direct link to Implementation of") `ConnectedAPI.signData` *** ### submitTransaction()[​](#submittransaction "Direct link to submitTransaction()") > **submitTransaction**(`tx`): `Promise`<`void`> Submit a transaction to the network, effectively using wallet as a relayer. The transaction received is expected to be balanced and "sealed" - it means it contains proofs, signatures and cryptographically bound (`Transaction` type from `@midnight-ntwrk/ledger`) #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### tx[​](#tx-2 "Direct link to tx") `string` #### Returns[​](#returns-17 "Direct link to Returns") `Promise`<`void`> #### Implementation of[​](#implementation-of-16 "Direct link to Implementation of") `ConnectedAPI.submitTransaction` --- # DynamicProofServerContainer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** A proof server container that is started and stopped dynamically by the test suite on random port. ## Implements[​](#implements "Direct link to Implements") * [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) ## Properties[​](#properties "Direct link to Properties") ### dockerEnv[​](#dockerenv "Direct link to dockerEnv") > **dockerEnv**: `StartedDockerComposeEnvironment` The Docker Compose environment running the container ## Methods[​](#methods "Direct link to Methods") ### getMappedPort()[​](#getmappedport "Direct link to getMappedPort()") > **getMappedPort**(): `number` Gets the mapped port number for the container. #### Returns[​](#returns "Direct link to Returns") `number` The mapped port number *** ### getUrl()[​](#geturl "Direct link to getUrl()") > **getUrl**(): `string` Gets the URL where the proof server can be accessed. #### Returns[​](#returns-1 "Direct link to Returns") `string` The URL of the proof server #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md).[`getUrl`](/api-reference/testkit-js/interfaces/ProofServerContainer.md#geturl) *** ### stop()[​](#stop "Direct link to stop()") > **stop**(): `Promise`<`void`> Stops the proof server container. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the container is stopped #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md).[`stop`](/api-reference/testkit-js/interfaces/ProofServerContainer.md#stop) *** ### start()[​](#start "Direct link to start()") > `static` **start**(`logger`, `maybeUID?`, `maybeNetworkId?`): `Promise`<`DynamicProofServerContainer`> Starts a new proof server container. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations ##### maybeUID?[​](#maybeuid "Direct link to maybeUID?") `string` Optional unique identifier for the container ##### maybeNetworkId?[​](#maybenetworkid "Direct link to maybeNetworkId?") `string` Optional network ID for the container #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`DynamicProofServerContainer`> A promise that resolves to the new container instance --- # EnvVarRemoteTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Test environment that configures services using environment variables. Allows specifying custom endpoints through environment variables. ## Extends[​](#extends "Direct link to Extends") * [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new EnvVarRemoteTestEnvironment**(`logger`): `EnvVarRemoteTestEnvironment` Creates a new TestEnvironment instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `EnvVarRemoteTestEnvironment` #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`constructor`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#constructor) ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Returns the configuration for environment services based on environment variables. Required environment variables: * MN\_TEST\_NETWORK\_ID: Network identifier (e.g., 'testnet', 'devnet') * MN\_TEST\_INDEXER: GraphQL API endpoint for the indexer * MN\_TEST\_INDEXER\_WS: WebSocket endpoint for the indexer * MN\_TEST\_NODE: RPC endpoint for the blockchain node Optional environment variables: * MN\_TEST\_FAUCET: API endpoint for requesting test tokens #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Object containing service URLs from environment variables #### Throws[​](#throws "Direct link to Throws") If any required environment variable is not set #### Overrides[​](#overrides "Direct link to Overrides") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getEnvironmentConfiguration`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getenvironmentconfiguration) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws-1 "Direct link to Throws") If no wallet could be started #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getMidnightWalletProvider`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getmidnightwalletprovider) *** ### healthCheck()[​](#healthcheck "Direct link to healthCheck()") > **healthCheck**(): `Promise`<`void`> Performs a health check for the environment. Checks the health of the node, indexer, and optionally the faucet services. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the health check is complete. #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`healthCheck`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#healthcheck) *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment by closing all walletProviders and stopping the proof server. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`void`> #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`shutdown`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#shutdown) *** ### start()[​](#start "Direct link to start()") > **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Starts the test environment by initializing the proof server and environment configuration. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) Optional proof server container to use instead of creating a new one #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration #### Inherited from[​](#inherited-from-4 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`start`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#start) *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Creates and starts the specified number of wallet providers. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` = `1` ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] | `undefined` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Array of started wallet providers #### Inherited from[​](#inherited-from-5 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`startMidnightWalletProviders`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#startmidnightwalletproviders) --- # FaucetClient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Client for interacting with the Midnight faucet service. Provides functionality to request test tokens for wallet addresses. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new FaucetClient**(`faucetUrl`, `logger`): `FaucetClient` Creates a new FaucetClient instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### faucetUrl[​](#fauceturl "Direct link to faucetUrl") `string` The URL of the faucet service endpoint ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `FaucetClient` ## Properties[​](#properties "Direct link to Properties") ### faucetUrl[​](#fauceturl-1 "Direct link to faucetUrl") > `readonly` **faucetUrl**: `string` ## Methods[​](#methods "Direct link to Methods") ### health()[​](#health "Direct link to health()") > **health**(): `Promise`<`AxiosResponse`<`any`, `any`, { }>> Checks the health status of the faucet service. Makes a GET request to the health endpoint of the faucet service. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`AxiosResponse`<`any`, `any`, { }>> A promise that resolves to the response of the health check or logs an error if the request fails *** ### requestTokens()[​](#requesttokens "Direct link to requestTokens()") > **requestTokens**(`walletAddress`): `Promise`<`void`> Requests test tokens from the faucet for a specified wallet address. Makes a POST request to the faucet service with the wallet address. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### walletAddress[​](#walletaddress "Direct link to walletAddress") `string` The address to receive the test tokens #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the request is complete #### Throws[​](#throws "Direct link to Throws") Will log but not throw if the request fails --- # FluentWalletBuilder > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Methods[​](#methods "Direct link to Methods") ### build()[​](#build "Direct link to build()") > **build**(): `Promise`<`WalletFacade`> #### Returns[​](#returns "Direct link to Returns") `Promise`<`WalletFacade`> *** ### buildWithoutStarting()[​](#buildwithoutstarting "Direct link to buildWithoutStarting()") > **buildWithoutStarting**(): `Promise`<{ `keystore`: `UnshieldedKeystore`; `seeds`: [`WalletSeeds`](/api-reference/testkit-js/classes/WalletSeeds.md); `wallet`: `WalletFacade`; }> #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<{ `keystore`: `UnshieldedKeystore`; `seeds`: [`WalletSeeds`](/api-reference/testkit-js/classes/WalletSeeds.md); `wallet`: `WalletFacade`; }> *** ### withDustOptions()[​](#withdustoptions "Direct link to withDustOptions()") > **withDustOptions**(`options`): `FluentWalletBuilder` #### Parameters[​](#parameters "Direct link to Parameters") ##### options[​](#options "Direct link to options") [`DustWalletOptions`](/api-reference/testkit-js/interfaces/DustWalletOptions.md) #### Returns[​](#returns-2 "Direct link to Returns") `FluentWalletBuilder` *** ### withMnemonic()[​](#withmnemonic "Direct link to withMnemonic()") > **withMnemonic**(`mnemonic`): `FluentWalletBuilder` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### mnemonic[​](#mnemonic "Direct link to mnemonic") `string` #### Returns[​](#returns-3 "Direct link to Returns") `FluentWalletBuilder` *** ### withRandomSeed()[​](#withrandomseed "Direct link to withRandomSeed()") > **withRandomSeed**(): `FluentWalletBuilder` #### Returns[​](#returns-4 "Direct link to Returns") `FluentWalletBuilder` *** ### withSeed()[​](#withseed "Direct link to withSeed()") > **withSeed**(`seed`): `FluentWalletBuilder` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### seed[​](#seed "Direct link to seed") `string` #### Returns[​](#returns-5 "Direct link to Returns") `FluentWalletBuilder` *** ### withTestWallet()[​](#withtestwallet "Direct link to withTestWallet()") > **withTestWallet**(): `FluentWalletBuilder` #### Returns[​](#returns-6 "Direct link to Returns") `FluentWalletBuilder` *** ### forEnvironment()[​](#forenvironment "Direct link to forEnvironment()") > `static` **forEnvironment**(`envConfig`): `FluentWalletBuilder` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### envConfig[​](#envconfig "Direct link to envConfig") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) #### Returns[​](#returns-7 "Direct link to Returns") `FluentWalletBuilder` --- # GzipFile > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** A class for compressing and decompressing files using gzip. ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new GzipFile**(`inputFile`, `outputFile`): `GzipFile` Creates a new GzipFile instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### inputFile[​](#inputfile "Direct link to inputFile") `string` The path to the input file to compress/decompress ##### outputFile[​](#outputfile "Direct link to outputFile") `string` The path where the compressed file will be saved #### Returns[​](#returns "Direct link to Returns") `GzipFile` ## Properties[​](#properties "Direct link to Properties") ### inputFile[​](#inputfile-1 "Direct link to inputFile") > **inputFile**: `string` The path to the input file *** ### outputFile[​](#outputfile-1 "Direct link to outputFile") > **outputFile**: `string` The path to the output file ## Methods[​](#methods "Direct link to Methods") ### compress()[​](#compress "Direct link to compress()") > **compress**(): `Promise`<`void`> Compresses the input file using gzip compression. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`void`> A promise that resolves when compression is complete #### Throws[​](#throws "Direct link to Throws") If there is an error during compression *** ### decompress()[​](#decompress "Direct link to decompress()") > **decompress**(): `Promise`<`string`> Decompresses the input gzip file and returns its contents as a string. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`string`> A promise that resolves with the decompressed file contents as a string #### Throws[​](#throws-1 "Direct link to Throws") If there is an error during decompression --- # IndexerClient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new IndexerClient**(`indexerUrl`, `logger`): `IndexerClient` Creates an instance of IndexerClient. #### Parameters[​](#parameters "Direct link to Parameters") ##### indexerUrl[​](#indexerurl "Direct link to indexerUrl") `string` The URL of the indexer service. ##### logger[​](#logger "Direct link to logger") `Logger` The logger instance for logging information. #### Returns[​](#returns "Direct link to Returns") `IndexerClient` ## Properties[​](#properties "Direct link to Properties") ### indexerUrl[​](#indexerurl-1 "Direct link to indexerUrl") > `readonly` **indexerUrl**: `string` ## Methods[​](#methods "Direct link to Methods") ### health()[​](#health "Direct link to health()") > **health**(): `Promise`<`AxiosResponse`<`any`, `any`, { }>> Checks the health status of the indexer service. Makes a GET request to the status endpoint of the indexer service. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`AxiosResponse`<`any`, `any`, { }>> A promise that resolves to the response of the health check or logs an error if the request fails. --- # LocalTestConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Configuration class for local test environment implementing EnvironmentConfiguration ## Implements[​](#implements "Direct link to Implements") * [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new LocalTestConfiguration**(`ports`): `LocalTestConfiguration` Creates a new LocalTestConfiguration instance #### Parameters[​](#parameters "Direct link to Parameters") ##### ports[​](#ports "Direct link to ports") [`ComponentPortsConfiguration`](/api-reference/testkit-js/type-aliases/ComponentPortsConfiguration.md) Object containing port numbers for each component #### Returns[​](#returns "Direct link to Returns") `LocalTestConfiguration` ## Properties[​](#properties "Direct link to Properties") ### faucet[​](#faucet "Direct link to faucet") > `readonly` **faucet**: `string` | `undefined` Optional URL for the faucet service to obtain test tokens #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`faucet`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#faucet) *** ### indexer[​](#indexer "Direct link to indexer") > `readonly` **indexer**: `string` URL of the indexer HTTP endpoint #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`indexer`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#indexer) *** ### indexerWS[​](#indexerws "Direct link to indexerWS") > `readonly` **indexerWS**: `string` WebSocket URL for the indexer service #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`indexerWS`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#indexerws) *** ### networkId[​](#networkid "Direct link to networkId") > `readonly` **networkId**: `string` Network identifier #### Implementation of[​](#implementation-of-3 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`networkId`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#networkid) *** ### node[​](#node "Direct link to node") > `readonly` **node**: `string` URL of the blockchain node #### Implementation of[​](#implementation-of-4 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`node`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#node) *** ### nodeWS[​](#nodews "Direct link to nodeWS") > `readonly` **nodeWS**: `string` WebSocket URL for the blockchain node #### Implementation of[​](#implementation-of-5 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`nodeWS`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#nodews) *** ### proofServer[​](#proofserver "Direct link to proofServer") > `readonly` **proofServer**: `string` URL of the proof generation server #### Implementation of[​](#implementation-of-6 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`proofServer`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#proofserver) *** ### walletNetworkId[​](#walletnetworkid "Direct link to walletNetworkId") > `readonly` **walletNetworkId**: `string` Wallet Network identifier #### Implementation of[​](#implementation-of-7 "Direct link to Implementation of") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md).[`walletNetworkId`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md#walletnetworkid) --- # LocalTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Test environment for local development using Docker containers Manages containers for node, indexer and proof server components ## Extends[​](#extends "Direct link to Extends") * [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new LocalTestEnvironment**(`logger`): `LocalTestEnvironment` Creates a new LocalTestEnvironment instance #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `LocalTestEnvironment` #### Overrides[​](#overrides "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`constructor`](/api-reference/testkit-js/classes/TestEnvironment.md#constructor) ## Properties[​](#properties "Direct link to Properties") ### dockerEnv[​](#dockerenv "Direct link to dockerEnv") > **dockerEnv**: `StartedDockerComposeEnvironment` *** ### genesisMintWalletSeed[​](#genesismintwalletseed "Direct link to genesisMintWalletSeed") > `readonly` **genesisMintWalletSeed**: `string`\[] *** ### MAX\_NUMBER\_OF\_WALLETS[​](#max_number_of_wallets "Direct link to MAX_NUMBER_OF_WALLETS") > `readonly` `static` **MAX\_NUMBER\_OF\_WALLETS**: `4` = `4` ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Returns the configuration for the testnet environment services. #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Object containing URLs for testnet services: * indexer: GraphQL API endpoint for the indexer * indexerWS: WebSocket endpoint for the indexer * node: RPC endpoint for the blockchain node * faucet: API endpoint for requesting test tokens * proofServer: URL for the proof generation server #### Overrides[​](#overrides-1 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`getEnvironmentConfiguration`](/api-reference/testkit-js/classes/TestEnvironment.md#getenvironmentconfiguration) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws "Direct link to Throws") If no wallet could be started #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`getMidnightWalletProvider`](/api-reference/testkit-js/classes/TestEnvironment.md#getmidnightwalletprovider) *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment, closing walletProviders and stopping containers #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> #### Overrides[​](#overrides-2 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`shutdown`](/api-reference/testkit-js/classes/TestEnvironment.md#shutdown) *** ### start()[​](#start "Direct link to start()") > **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Starts the test environment by creating and configuring Docker containers #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) Optional proof server container #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration #### Throws[​](#throws-1 "Direct link to Throws") If trying to inject proof server container when starting new environment #### Overrides[​](#overrides-3 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`start`](/api-reference/testkit-js/classes/TestEnvironment.md#start) *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Creates and starts the specified number of wallet providers #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` = `1` ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] | `undefined` #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> A promise that resolves to an array of started wallets #### Throws[​](#throws-2 "Direct link to Throws") If requested amount exceeds maximum supported walletProviders #### Overrides[​](#overrides-4 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`startMidnightWalletProviders`](/api-reference/testkit-js/classes/TestEnvironment.md#startmidnightwalletproviders) *** ### startWithInjectedEnvironment()[​](#startwithinjectedenvironment "Direct link to startWithInjectedEnvironment()") > **startWithInjectedEnvironment**(`dockerEnv`, `ports`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Instead of starting the test environment by building the docker containers from the default configuration files in this package, start the test environment by passing an existing StartedDockerComposeEnvironment along with the ports for the containers in the environment. #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### dockerEnv[​](#dockerenv-1 "Direct link to dockerEnv") `StartedDockerComposeEnvironment` A started docker compose environment ##### ports[​](#ports "Direct link to ports") [`ComponentPortsConfiguration`](/api-reference/testkit-js/type-aliases/ComponentPortsConfiguration.md) The ports of the containers in the given environment #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration --- # MidnightWalletProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Provider class that implements wallet functionality for the Midnight network. Handles transaction balancing, submission, and wallet state management. ## Implements[​](#implements "Direct link to Implements") * `MidnightProvider` * `WalletProvider` ## Properties[​](#properties "Direct link to Properties") ### dustSecretKey[​](#dustsecretkey "Direct link to dustSecretKey") > `readonly` **dustSecretKey**: `DustSecretKey` *** ### env[​](#env "Direct link to env") > `readonly` **env**: [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) *** ### logger[​](#logger "Direct link to logger") > **logger**: `Logger` *** ### unshieldedKeystore[​](#unshieldedkeystore "Direct link to unshieldedKeystore") > `readonly` **unshieldedKeystore**: `UnshieldedKeystore` *** ### wallet[​](#wallet "Direct link to wallet") > `readonly` **wallet**: `WalletFacade` *** ### zswapSecretKeys[​](#zswapsecretkeys "Direct link to zswapSecretKeys") > `readonly` **zswapSecretKeys**: `ZswapSecretKeys` ## Methods[​](#methods "Direct link to Methods") ### balanceTx()[​](#balancetx "Direct link to balanceTx()") > **balanceTx**(`tx`, `ttl?`): `Promise`<`FinalizedTransaction`> Balances a transaction #### Parameters[​](#parameters "Direct link to Parameters") ##### tx[​](#tx "Direct link to tx") `UnboundTransaction` The transaction to balance. ##### ttl?[​](#ttl "Direct link to ttl?") `Date` = `...` #### Returns[​](#returns "Direct link to Returns") `Promise`<`FinalizedTransaction`> #### Implementation of[​](#implementation-of "Direct link to Implementation of") `WalletProvider.balanceTx` *** ### getCoinPublicKey()[​](#getcoinpublickey "Direct link to getCoinPublicKey()") > **getCoinPublicKey**(): `string` #### Returns[​](#returns-1 "Direct link to Returns") `string` #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") `WalletProvider.getCoinPublicKey` *** ### getEncryptionPublicKey()[​](#getencryptionpublickey "Direct link to getEncryptionPublicKey()") > **getEncryptionPublicKey**(): `string` #### Returns[​](#returns-2 "Direct link to Returns") `string` #### Implementation of[​](#implementation-of-2 "Direct link to Implementation of") `WalletProvider.getEncryptionPublicKey` *** ### start()[​](#start "Direct link to start()") > **start**(`waitForFundsInWallet?`, `tokenType?`): `Promise`<`void`> #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### waitForFundsInWallet?[​](#waitforfundsinwallet "Direct link to waitForFundsInWallet?") `boolean` = `true` ##### tokenType?[​](#tokentype "Direct link to tokenType?") `TokenType` = `...` #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> *** ### stop()[​](#stop "Direct link to stop()") > **stop**(): `Promise`<`void`> #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`void`> *** ### submitTx()[​](#submittx "Direct link to submitTx()") > **submitTx**(`tx`): `Promise`<`string`> Submit a transaction to the network to be consensed upon. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### tx[​](#tx-1 "Direct link to tx") `FinalizedTransaction` The finalized transaction to submit. #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<`string`> The transaction identifier of the submitted transaction. #### Implementation of[​](#implementation-of-3 "Direct link to Implementation of") `MidnightProvider.submitTx` *** ### build()[​](#build "Direct link to build()") > `static` **build**(`logger`, `env`, `seed?`): `Promise`<`MidnightWalletProvider`> #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### logger[​](#logger-1 "Direct link to logger") `Logger` ##### env[​](#env-1 "Direct link to env") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) ##### seed?[​](#seed "Direct link to seed?") `string` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<`MidnightWalletProvider`> *** ### withWallet()[​](#withwallet "Direct link to withWallet()") > `static` **withWallet**(`logger`, `env`, `wallet`, `zswapSecretKeys`, `dustSecretKey`, `unshieldedKeystore`): `Promise`<`MidnightWalletProvider`> #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### logger[​](#logger-2 "Direct link to logger") `Logger` ##### env[​](#env-2 "Direct link to env") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) ##### wallet[​](#wallet-1 "Direct link to wallet") `WalletFacade` ##### zswapSecretKeys[​](#zswapsecretkeys-1 "Direct link to zswapSecretKeys") `ZswapSecretKeys` ##### dustSecretKey[​](#dustsecretkey-1 "Direct link to dustSecretKey") `DustSecretKey` ##### unshieldedKeystore[​](#unshieldedkeystore-1 "Direct link to unshieldedKeystore") `UnshieldedKeystore` #### Returns[​](#returns-7 "Direct link to Returns") `Promise`<`MidnightWalletProvider`> --- # NodeClient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Client for interacting with a Midnight node's JSON-RPC API ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new NodeClient**(`nodeURL`, `logger`): `NodeClient` Creates a new NodeClient instance #### Parameters[​](#parameters "Direct link to Parameters") ##### nodeURL[​](#nodeurl "Direct link to nodeURL") `string` URL of the Midnight node ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `NodeClient` ## Properties[​](#properties "Direct link to Properties") ### nodeURL[​](#nodeurl-1 "Direct link to nodeURL") > `readonly` **nodeURL**: `string` ## Methods[​](#methods "Direct link to Methods") ### contractState()[​](#contractstate "Direct link to contractState()") > **contractState**(`contractAddress`): `Promise`<`ContractState` | `null`> Fetches the state of a contract #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### contractAddress[​](#contractaddress "Direct link to contractAddress") `string` Address of the contract #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`ContractState` | `null`> Contract state or null if not found *** ### health()[​](#health "Direct link to health()") > **health**(): `Promise`<`AxiosResponse`<`any`, `any`, { }>> Checks the health status of the node. Makes a GET request to the health endpoint of the node. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`AxiosResponse`<`any`, `any`, { }>> A promise that resolves to the response of the health check or logs an error if the request fails. *** ### ledgerState()[​](#ledgerstate "Direct link to ledgerState()") > **ledgerState**(`blockHash`): `Promise`<`LedgerState`> Fetches the ledger state at a given block #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### blockHash[​](#blockhash "Direct link to blockHash") `string` Hash of the block #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`LedgerState`> Ledger state *** ### ledgerStateBlob()[​](#ledgerstateblob "Direct link to ledgerStateBlob()") > **ledgerStateBlob**(`blockHash`): `Promise`<`Uint8Array`<`ArrayBufferLike`>> Fetches the raw ledger state blob at a given block #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### blockHash[​](#blockhash-1 "Direct link to blockHash") `string` Hash of the block #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`Uint8Array`<`ArrayBufferLike`>> Raw ledger state data #### Throws[​](#throws "Direct link to Throws") If no ledger state is found *** ### ledgerVersion()[​](#ledgerversion "Direct link to ledgerVersion()") > **ledgerVersion**(`blockHash`): `Promise`<`string`> Fetches the ledger version at a given block #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### blockHash[​](#blockhash-2 "Direct link to blockHash") `string` Hash of the block #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<`string`> Ledger version #### Throws[​](#throws-1 "Direct link to Throws") If no ledger version is found --- # PreprodTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Test environment configuration for the Midnight preprod network. Provides URLs and endpoints for preprod network services. ## Extends[​](#extends "Direct link to Extends") * [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new PreprodTestEnvironment**(`logger`): `PreprodTestEnvironment` Creates a new TestEnvironment instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `PreprodTestEnvironment` #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`constructor`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#constructor) ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Returns the configuration for the preprod environment services. #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Object containing URLs for preprod services: * indexer: GraphQL API endpoint for the indexer * indexerWS: WebSocket endpoint for the indexer * node: RPC endpoint for the blockchain node * faucet: API endpoint for requesting test tokens * proofServer: URL for the proof generation server #### Overrides[​](#overrides "Direct link to Overrides") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getEnvironmentConfiguration`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getenvironmentconfiguration) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws "Direct link to Throws") If no wallet could be started #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getMidnightWalletProvider`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getmidnightwalletprovider) *** ### healthCheck()[​](#healthcheck "Direct link to healthCheck()") > **healthCheck**(): `Promise`<`void`> Performs a health check for the environment. Checks the health of the node, indexer, and optionally the faucet services. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the health check is complete. #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`healthCheck`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#healthcheck) *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment by closing all walletProviders and stopping the proof server. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`void`> #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`shutdown`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#shutdown) *** ### start()[​](#start "Direct link to start()") > **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Starts the test environment by initializing the proof server and environment configuration. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) Optional proof server container to use instead of creating a new one #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration #### Inherited from[​](#inherited-from-4 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`start`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#start) *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Creates and starts the specified number of wallet providers. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` = `1` ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] | `undefined` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Array of started wallet providers #### Inherited from[​](#inherited-from-5 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`startMidnightWalletProviders`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#startmidnightwalletproviders) --- # PreviewTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Test environment configuration for the Midnight preview network. Provides URLs and endpoints for preview network services. ## Extends[​](#extends "Direct link to Extends") * [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new PreviewTestEnvironment**(`logger`): `PreviewTestEnvironment` Creates a new TestEnvironment instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `PreviewTestEnvironment` #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`constructor`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#constructor) ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Returns the configuration for the preview environment services. #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Object containing URLs for preview services: * indexer: GraphQL API endpoint for the indexer * indexerWS: WebSocket endpoint for the indexer * node: RPC endpoint for the blockchain node * faucet: API endpoint for requesting test tokens * proofServer: URL for the proof generation server #### Overrides[​](#overrides "Direct link to Overrides") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getEnvironmentConfiguration`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getenvironmentconfiguration) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws "Direct link to Throws") If no wallet could be started #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getMidnightWalletProvider`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getmidnightwalletprovider) *** ### healthCheck()[​](#healthcheck "Direct link to healthCheck()") > **healthCheck**(): `Promise`<`void`> Performs a health check for the environment. Checks the health of the node, indexer, and optionally the faucet services. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the health check is complete. #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`healthCheck`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#healthcheck) *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment by closing all walletProviders and stopping the proof server. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`void`> #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`shutdown`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#shutdown) *** ### start()[​](#start "Direct link to start()") > **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Starts the test environment by initializing the proof server and environment configuration. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) Optional proof server container to use instead of creating a new one #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration #### Inherited from[​](#inherited-from-4 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`start`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#start) *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Creates and starts the specified number of wallet providers. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` = `1` ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] | `undefined` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Array of started wallet providers #### Inherited from[​](#inherited-from-5 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`startMidnightWalletProviders`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#startmidnightwalletproviders) --- # ProofServerClient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new ProofServerClient**(`proofServer`, `logger`): `ProofServerClient` Creates an instance of ProofServerClient. #### Parameters[​](#parameters "Direct link to Parameters") ##### proofServer[​](#proofserver "Direct link to proofServer") `string` The URL of the proof server service. ##### logger[​](#logger "Direct link to logger") `Logger` The logger instance for logging information. #### Returns[​](#returns "Direct link to Returns") `ProofServerClient` ## Properties[​](#properties "Direct link to Properties") ### proofServer[​](#proofserver-1 "Direct link to proofServer") > `readonly` **proofServer**: `string` ## Methods[​](#methods "Direct link to Methods") ### health()[​](#health "Direct link to health()") > **health**(): `Promise`<`AxiosResponse`<`any`, `any`, { }>> Checks the health status of the indexer service. Makes a GET request to the status endpoint of the indexer service. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`AxiosResponse`<`any`, `any`, { }>> A promise that resolves to the response of the health check or logs an error if the request fails. *** ### proveTx()[​](#provetx "Direct link to proveTx()") > **proveTx**(`data?`, `config?`): `Promise`<`AxiosResponse`<`any`, `any`, { }>> Proves a transaction by sending a POST request to the proof server. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### data?[​](#data "Direct link to data?") `ArrayBuffer` serialized transaction data ##### config?[​](#config "Direct link to config?") `AxiosRequestConfig` = `...` Axios request configuration #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`AxiosResponse`<`any`, `any`, { }>> --- # QanetTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Test environment configuration for the Midnight QA network. Provides URLs and endpoints for QA network services. ## Extends[​](#extends "Direct link to Extends") * [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new QanetTestEnvironment**(`logger`): `QanetTestEnvironment` Creates a new TestEnvironment instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `QanetTestEnvironment` #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`constructor`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#constructor) ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Returns the configuration for the QA network environment services. #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Object containing URLs for QA network services: * indexer: GraphQL API endpoint for the indexer * indexerWS: WebSocket endpoint for the indexer * node: RPC endpoint for the blockchain node * faucet: API endpoint for requesting test tokens * proofServer: URL for the proof generation server #### Overrides[​](#overrides "Direct link to Overrides") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getEnvironmentConfiguration`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getenvironmentconfiguration) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws "Direct link to Throws") If no wallet could be started #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`getMidnightWalletProvider`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#getmidnightwalletprovider) *** ### healthCheck()[​](#healthcheck "Direct link to healthCheck()") > **healthCheck**(): `Promise`<`void`> Performs a health check for the environment. Checks the health of the node, indexer, and optionally the faucet services. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the health check is complete. #### Inherited from[​](#inherited-from-2 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`healthCheck`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#healthcheck) *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment by closing all walletProviders and stopping the proof server. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`void`> #### Inherited from[​](#inherited-from-3 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`shutdown`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#shutdown) *** ### start()[​](#start "Direct link to start()") > **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Starts the test environment by initializing the proof server and environment configuration. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) Optional proof server container to use instead of creating a new one #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration #### Inherited from[​](#inherited-from-4 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`start`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#start) *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Creates and starts the specified number of wallet providers. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` = `1` ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] | `undefined` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Array of started wallet providers #### Inherited from[​](#inherited-from-5 "Direct link to Inherited from") [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md).[`startMidnightWalletProviders`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md#startmidnightwalletproviders) --- # RemoteTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Base class for remote test environments that connect to external network services. Provides functionality for managing walletProviders and a proof server container. ## Extends[​](#extends "Direct link to Extends") * [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md) ## Extended by[​](#extended-by "Direct link to Extended by") * [`EnvVarRemoteTestEnvironment`](/api-reference/testkit-js/classes/EnvVarRemoteTestEnvironment.md) * [`PreprodTestEnvironment`](/api-reference/testkit-js/classes/PreprodTestEnvironment.md) * [`PreviewTestEnvironment`](/api-reference/testkit-js/classes/PreviewTestEnvironment.md) * [`QanetTestEnvironment`](/api-reference/testkit-js/classes/QanetTestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new RemoteTestEnvironment**(`logger`): `RemoteTestEnvironment` Creates a new TestEnvironment instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `RemoteTestEnvironment` #### Inherited from[​](#inherited-from "Direct link to Inherited from") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`constructor`](/api-reference/testkit-js/classes/TestEnvironment.md#constructor) ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > `abstract` **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Abstract method that must be implemented by subclasses to provide environment configuration. #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Configuration object containing service URLs and endpoints #### Overrides[​](#overrides "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`getEnvironmentConfiguration`](/api-reference/testkit-js/classes/TestEnvironment.md#getenvironmentconfiguration) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws "Direct link to Throws") If no wallet could be started #### Inherited from[​](#inherited-from-1 "Direct link to Inherited from") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`getMidnightWalletProvider`](/api-reference/testkit-js/classes/TestEnvironment.md#getmidnightwalletprovider) *** ### healthCheck()[​](#healthcheck "Direct link to healthCheck()") > **healthCheck**(): `Promise`<`void`> Performs a health check for the environment. Checks the health of the node, indexer, and optionally the faucet services. #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the health check is complete. *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment by closing all walletProviders and stopping the proof server. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`void`> #### Overrides[​](#overrides-1 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`shutdown`](/api-reference/testkit-js/classes/TestEnvironment.md#shutdown) *** ### start()[​](#start "Direct link to start()") > **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Starts the test environment by initializing the proof server and environment configuration. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) Optional proof server container to use instead of creating a new one #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> The environment configuration #### Overrides[​](#overrides-2 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`start`](/api-reference/testkit-js/classes/TestEnvironment.md#start) *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Creates and starts the specified number of wallet providers. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` = `1` ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] | `undefined` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Array of started wallet providers #### Overrides[​](#overrides-3 "Direct link to Overrides") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md).[`startMidnightWalletProviders`](/api-reference/testkit-js/classes/TestEnvironment.md#startmidnightwalletproviders) --- # StaticProofServerContainer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** A proof server that is currently running on a specific port. Used for connecting to an existing proof server instance. ## Implements[​](#implements "Direct link to Implements") * [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new StaticProofServerContainer**(`port?`): `StaticProofServerContainer` Creates a new StaticProofServerContainer instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### port?[​](#port "Direct link to port?") `number` = `6300` The port number where the proof server is running (default: 6300) #### Returns[​](#returns "Direct link to Returns") `StaticProofServerContainer` ## Properties[​](#properties "Direct link to Properties") ### port[​](#port-1 "Direct link to port") > **port**: `number` The port number where the proof server is running ## Methods[​](#methods "Direct link to Methods") ### getUrl()[​](#geturl "Direct link to getUrl()") > **getUrl**(): `string` Gets the URL where the proof server can be accessed. #### Returns[​](#returns-1 "Direct link to Returns") `string` The URL of the proof server #### Implementation of[​](#implementation-of "Direct link to Implementation of") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md).[`getUrl`](/api-reference/testkit-js/interfaces/ProofServerContainer.md#geturl) *** ### stop()[​](#stop "Direct link to stop()") > **stop**(): `Promise`<`void`> No-op stop method since this represents an external proof server. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`void`> A resolved promise #### Implementation of[​](#implementation-of-1 "Direct link to Implementation of") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md).[`stop`](/api-reference/testkit-js/interfaces/ProofServerContainer.md#stop) --- # TestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Abstract base class for test environments. Provides common functionality for managing test wallets and environments. ## Extended by[​](#extended-by "Direct link to Extended by") * [`LocalTestEnvironment`](/api-reference/testkit-js/classes/LocalTestEnvironment.md) * [`RemoteTestEnvironment`](/api-reference/testkit-js/classes/RemoteTestEnvironment.md) ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new TestEnvironment**(`logger`): `TestEnvironment` Creates a new TestEnvironment instance. #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations #### Returns[​](#returns "Direct link to Returns") `TestEnvironment` ## Methods[​](#methods "Direct link to Methods") ### getEnvironmentConfiguration()[​](#getenvironmentconfiguration "Direct link to getEnvironmentConfiguration()") > `abstract` **getEnvironmentConfiguration**(): [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) #### Returns[​](#returns-1 "Direct link to Returns") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) *** ### getMidnightWalletProvider()[​](#getmidnightwalletprovider "Direct link to getMidnightWalletProvider()") > **getMidnightWalletProvider**(): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> Starts a single wallet instance. #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)> A promise that resolves to the started wallet #### Throws[​](#throws "Direct link to Throws") If no wallet could be started *** ### shutdown()[​](#shutdown "Direct link to shutdown()") > `abstract` **shutdown**(`saveWalletState?`): `Promise`<`void`> Shuts down the test environment and cleans up resources. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### saveWalletState?[​](#savewalletstate "Direct link to saveWalletState?") `boolean` Optional flag to save the wallet state before shutdown #### Returns[​](#returns-3 "Direct link to Returns") `Promise`<`void`> A promise that resolves when shutdown is complete *** ### start()[​](#start "Direct link to start()") > `abstract` **start**(`maybeProofServerContainer?`): `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> Start the test environment. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### maybeProofServerContainer?[​](#maybeproofservercontainer "Direct link to maybeProofServerContainer?") [`ProofServerContainer`](/api-reference/testkit-js/interfaces/ProofServerContainer.md) If defined, a container representing an already running proof server. If undefined, a proof server will be started automatically. #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<[`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md)> A promise that resolves to the environment configuration *** ### startMidnightWalletProviders()[​](#startmidnightwalletproviders "Direct link to startMidnightWalletProviders()") > `abstract` **startMidnightWalletProviders**(`amount?`, `seeds?`): `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> Starts multiple wallet instances. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### amount?[​](#amount "Direct link to amount?") `number` Optional number of wallet instances to start ##### seeds?[​](#seeds "Direct link to seeds?") `string`\[] Optional array of seeds for the wallets #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<[`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md)\[]> A promise that resolves to an array of started wallets --- # WalletFactory > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new WalletFactory**(): `WalletFactory` #### Returns[​](#returns "Direct link to Returns") `WalletFactory` ## Methods[​](#methods "Direct link to Methods") ### createDustWallet()[​](#createdustwallet "Direct link to createDustWallet()") > `static` **createDustWallet**(`config`, `seed`, `dustOptions?`): `DustWalletAPI` #### Parameters[​](#parameters "Direct link to Parameters") ##### config[​](#config "Direct link to config") `DefaultV1Configuration` ##### seed[​](#seed "Direct link to seed") `Uint8Array` ##### dustOptions?[​](#dustoptions "Direct link to dustOptions?") [`DustWalletOptions`](/api-reference/testkit-js/interfaces/DustWalletOptions.md) = `DEFAULT_DUST_OPTIONS` #### Returns[​](#returns-1 "Direct link to Returns") `DustWalletAPI` *** ### createShieldedWallet()[​](#createshieldedwallet "Direct link to createShieldedWallet()") > `static` **createShieldedWallet**(`config`, `seed`): `ShieldedWalletAPI` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### config[​](#config-1 "Direct link to config") `DefaultV1Configuration` ##### seed[​](#seed-1 "Direct link to seed") `Uint8Array` #### Returns[​](#returns-2 "Direct link to Returns") `ShieldedWalletAPI` *** ### createUnshieldedWallet()[​](#createunshieldedwallet "Direct link to createUnshieldedWallet()") > `static` **createUnshieldedWallet**(`config`, `unshieldedKeystore`): `UnshieldedWalletAPI` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### config[​](#config-2 "Direct link to config") `DefaultV1Configuration` ##### unshieldedKeystore[​](#unshieldedkeystore "Direct link to unshieldedKeystore") `UnshieldedKeystore` #### Returns[​](#returns-3 "Direct link to Returns") `UnshieldedWalletAPI` *** ### createWalletFacade()[​](#createwalletfacade "Direct link to createWalletFacade()") > `static` **createWalletFacade**(`config`, `shieldedWallet`, `unshieldedWallet`, `dustWallet`): `Promise`<`WalletFacade`> #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### config[​](#config-3 "Direct link to config") `DefaultConfiguration` ##### shieldedWallet[​](#shieldedwallet "Direct link to shieldedWallet") `ShieldedWalletAPI` ##### unshieldedWallet[​](#unshieldedwallet "Direct link to unshieldedWallet") `UnshieldedWalletAPI` ##### dustWallet[​](#dustwallet "Direct link to dustWallet") `DustWalletAPI` #### Returns[​](#returns-4 "Direct link to Returns") `Promise`<`WalletFacade`> *** ### restoreShieldedWallet()[​](#restoreshieldedwallet "Direct link to restoreShieldedWallet()") > `static` **restoreShieldedWallet**(`config`, `serializedState`): `Promise`<`ShieldedWallet`> #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### config[​](#config-4 "Direct link to config") `DefaultV1Configuration` ##### serializedState[​](#serializedstate "Direct link to serializedState") `string` #### Returns[​](#returns-5 "Direct link to Returns") `Promise`<`ShieldedWallet`> *** ### startWalletFacade()[​](#startwalletfacade "Direct link to startWalletFacade()") > `static` **startWalletFacade**(`wallet`, `shieldedSeed`, `dustSeed`): `Promise`<`WalletFacade`> #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### wallet[​](#wallet "Direct link to wallet") `WalletFacade` ##### shieldedSeed[​](#shieldedseed "Direct link to shieldedSeed") `Uint8Array` ##### dustSeed[​](#dustseed "Direct link to dustSeed") `Uint8Array` #### Returns[​](#returns-6 "Direct link to Returns") `Promise`<`WalletFacade`> --- # WalletSaveStateProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Provider class for saving and loading wallet state to/from compressed files ## Constructors[​](#constructors "Direct link to Constructors") ### Constructor[​](#constructor "Direct link to Constructor") > **new WalletSaveStateProvider**(`logger`, `seed`, `directoryPath?`, `filename?`): `WalletSaveStateProvider` Creates a new WalletSaveStateProvider instance #### Parameters[​](#parameters "Direct link to Parameters") ##### logger[​](#logger "Direct link to logger") `Logger` Logger instance for recording operations ##### seed[​](#seed "Direct link to seed") `string` ##### directoryPath?[​](#directorypath "Direct link to directoryPath?") `string` = `DEFAULT_WALLET_STATE_DIRECTORY` Directory path for wallet state files ##### filename?[​](#filename "Direct link to filename?") `string` = `...` Filename for the wallet state file #### Returns[​](#returns "Direct link to Returns") `WalletSaveStateProvider` ## Properties[​](#properties "Direct link to Properties") ### directoryPath[​](#directorypath-1 "Direct link to directoryPath") > **directoryPath**: `string` Absolute path to the directory containing wallet state files *** ### filePath[​](#filepath "Direct link to filePath") > **filePath**: `string` Full path including filename for the wallet state file *** ### logger[​](#logger-1 "Direct link to logger") > **logger**: `Logger` Logger instance for recording operations ## Methods[​](#methods "Direct link to Methods") ### load()[​](#load "Direct link to load()") > **load**(): `Promise`<`string`> Loads and decompresses the wallet state from a file #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`string`> A promise that resolves with the decompressed wallet state as a string #### Throws[​](#throws "Direct link to Throws") If there is an error reading or decompressing the file *** ### save()[​](#save "Direct link to save()") > **save**(`wallet`): `Promise`<`void`> Saves the wallet state to a compressed file #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### wallet[​](#wallet "Direct link to wallet") `ShieldedWalletAPI` | `UnshieldedWalletAPI` The wallet instance to save state from #### Returns[​](#returns-2 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the save is complete --- # WalletSeeds > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Properties[​](#properties "Direct link to Properties") ### dust[​](#dust "Direct link to dust") > `readonly` **dust**: `Uint8Array` *** ### masterSeed[​](#masterseed "Direct link to masterSeed") > `readonly` **masterSeed**: `string` *** ### shielded[​](#shielded "Direct link to shielded") > `readonly` **shielded**: `Uint8Array` *** ### unshielded[​](#unshielded "Direct link to unshielded") > `readonly` **unshielded**: `Uint8Array` ## Methods[​](#methods "Direct link to Methods") ### fromMasterSeed()[​](#frommasterseed "Direct link to fromMasterSeed()") > `static` **fromMasterSeed**(`seed`): `WalletSeeds` #### Parameters[​](#parameters "Direct link to Parameters") ##### seed[​](#seed "Direct link to seed") `string` #### Returns[​](#returns "Direct link to Returns") `WalletSeeds` *** ### fromMnemonic()[​](#frommnemonic "Direct link to fromMnemonic()") > `static` **fromMnemonic**(`mnemonic`): `WalletSeeds` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### mnemonic[​](#mnemonic "Direct link to mnemonic") `string` #### Returns[​](#returns-1 "Direct link to Returns") `WalletSeeds` *** ### generateRandom()[​](#generaterandom "Direct link to generateRandom()") > `static` **generateRandom**(): `WalletSeeds` #### Returns[​](#returns-2 "Direct link to Returns") `WalletSeeds` *** ### testWallet()[​](#testwallet "Direct link to testWallet()") > `static` **testWallet**(): `WalletSeeds` #### Returns[​](#returns-3 "Direct link to Returns") `WalletSeeds` --- # buildUrlWithPath > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **buildUrlWithPath**(`baseUrl`, `urlPath`): `string` ## Parameters[​](#parameters "Direct link to Parameters") ### baseUrl[​](#baseurl "Direct link to baseUrl") `string` ### urlPath[​](#urlpath "Direct link to urlPath") `string` ## Returns[​](#returns "Direct link to Returns") `string` --- # createDefaultTestLogger > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **createDefaultTestLogger**(): `Logger`<`never`, `boolean`> ## Returns[​](#returns "Direct link to Returns") `Logger`<`never`, `boolean`> --- # createLogger > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **createLogger**(`fileName`, `dir?`): `Logger`<`never`, `boolean`> ## Parameters[​](#parameters "Direct link to Parameters") ### fileName[​](#filename "Direct link to fileName") `string` ### dir?[​](#dir "Direct link to dir?") `string` = `...` ## Returns[​](#returns "Direct link to Returns") `Logger`<`never`, `boolean`> --- # delay > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **delay**(`ms`): `Promise`<`unknown`> Creates a Promise that resolves after a specified delay. ## Parameters[​](#parameters "Direct link to Parameters") ### ms[​](#ms "Direct link to ms") `number` The delay duration in milliseconds. ## Returns[​](#returns "Direct link to Returns") `Promise`<`unknown`> A Promise that resolves after the specified delay. ## Example[​](#example "Direct link to Example") ``` // Wait for 1 second await delay(1000); ``` --- # expectFoundAndDeployedStatesEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectFoundAndDeployedStatesEqual**<`C`>(`providers`, `deployTxData`, `foundDeployTxData`, `privateStateId?`, `initialPrivateState?`): `Promise`<`void`> ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") `MidnightProviders`<`ProvableCircuitId`<`C`>, `string`, `unknown`> ### deployTxData[​](#deploytxdata "Direct link to deployTxData") `FinalizedDeployTxData`<`C`> ### foundDeployTxData[​](#founddeploytxdata "Direct link to foundDeployTxData") `FinalizedDeployTxDataBase`<`C`> ### privateStateId?[​](#privatestateid "Direct link to privateStateId?") `string` ### initialPrivateState?[​](#initialprivatestate "Direct link to initialPrivateState?") `PrivateState`<`C`> ## Returns[​](#returns "Direct link to Returns") `Promise`<`void`> --- # expectFoundAndDeployedTxDataEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectFoundAndDeployedTxDataEqual**<`C`>(`deployTxData`, `foundDeployTxData`): `void` ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### deployTxData[​](#deploytxdata "Direct link to deployTxData") `FinalizedDeployTxData`<`C`> ### foundDeployTxData[​](#founddeploytxdata "Direct link to foundDeployTxData") `FinalizedDeployTxDataBase`<`C`> ## Returns[​](#returns "Direct link to Returns") `void` --- # expectFoundAndDeployedTxPrivateDataEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectFoundAndDeployedTxPrivateDataEqual**<`C`>(`deployTxData`, `foundDeployTxData`): `void` ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### deployTxData[​](#deploytxdata "Direct link to deployTxData") `FinalizedDeployTxData`<`C`> ### foundDeployTxData[​](#founddeploytxdata "Direct link to foundDeployTxData") `FinalizedDeployTxDataBase`<`C`> ## Returns[​](#returns "Direct link to Returns") `void` --- # expectFoundAndDeployedTxPublicDataEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectFoundAndDeployedTxPublicDataEqual**<`C`>(`deployTxData`, `foundDeployTxData`): `void` ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### deployTxData[​](#deploytxdata "Direct link to deployTxData") `FinalizedDeployTxData`<`C`> ### foundDeployTxData[​](#founddeploytxdata "Direct link to foundDeployTxData") `FinalizedDeployTxDataBase`<`C`> ## Returns[​](#returns "Direct link to Returns") `void` --- # expectSuccessfulCallTx > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectSuccessfulCallTx**<`C`, `PCK`>(`providers`, `callTxData`, `callTxOptions?`, `nextPrivateState?`): `Promise`<`void`> ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") `MidnightProviders`<`ProvableCircuitId`<`C`>, `string`, `unknown`> ### callTxData[​](#calltxdata "Direct link to callTxData") `FinalizedCallTxData`<`C`, `PCK`> ### callTxOptions?[​](#calltxoptions "Direct link to callTxOptions?") `CallTxOptions`<`C`, `PCK`> ### nextPrivateState?[​](#nextprivatestate "Direct link to nextPrivateState?") `PrivateState`<`C`> ## Returns[​](#returns "Direct link to Returns") `Promise`<`void`> --- # expectSuccessfulDeployTx > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectSuccessfulDeployTx**<`C`>(`providers`, `deployTxData`, `deployTxOptions?`): `Promise`<`void`> ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### C[​](#c "Direct link to C") `C` *extends* `Any` ## Parameters[​](#parameters "Direct link to Parameters") ### providers[​](#providers "Direct link to providers") `MidnightProviders`<`ProvableCircuitId`<`C`>, `string`, `unknown`> ### deployTxData[​](#deploytxdata "Direct link to deployTxData") `FinalizedDeployTxData`<`C`> ### deployTxOptions?[​](#deploytxoptions "Direct link to deployTxOptions?") `DeployContractOptions`<`C`> | `DeployTxOptions`<`C`> ## Returns[​](#returns "Direct link to Returns") `Promise`<`void`> --- # expectSuccessfulTxData > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **expectSuccessfulTxData**(`finalizedTxData`): `void` ## Parameters[​](#parameters "Direct link to Parameters") ### finalizedTxData[​](#finalizedtxdata "Direct link to finalizedTxData") `FinalizedTxData` ## Returns[​](#returns "Direct link to Returns") `void` --- # getContainersConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getContainersConfiguration**(): [`ContainersConfiguration`](/api-reference/testkit-js/interfaces/ContainersConfiguration.md) ## Returns[​](#returns "Direct link to Returns") [`ContainersConfiguration`](/api-reference/testkit-js/interfaces/ContainersConfiguration.md) --- # getDustSeed > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getDustSeed**(`seed`): `Uint8Array` ## Parameters[​](#parameters "Direct link to Parameters") ### seed[​](#seed "Direct link to seed") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # getInitialShieldedState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getInitialShieldedState**(`wallet`): `Promise`<`ShieldedWalletState`<`string`, `FinalizedTransaction`>> ## Parameters[​](#parameters "Direct link to Parameters") ### wallet[​](#wallet "Direct link to wallet") `ShieldedWalletAPI` ## Returns[​](#returns "Direct link to Returns") `Promise`<`ShieldedWalletState`<`string`, `FinalizedTransaction`>> --- # getInitialState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getInitialState**(`wallet`): `Promise`<`ShieldedWalletState`<`string`, `FinalizedTransaction`> | `UnshieldedWalletState`<`string`>> ## Parameters[​](#parameters "Direct link to Parameters") ### wallet[​](#wallet "Direct link to wallet") `ShieldedWalletAPI` | `UnshieldedWalletAPI` ## Returns[​](#returns "Direct link to Returns") `Promise`<`ShieldedWalletState`<`string`, `FinalizedTransaction`> | `UnshieldedWalletState`<`string`>> --- # getInitialUnshieldedState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getInitialUnshieldedState**(`wallet`): `Promise`<`UnshieldedWalletState`<`string`>> ## Parameters[​](#parameters "Direct link to Parameters") ### wallet[​](#wallet "Direct link to wallet") `UnshieldedWalletAPI` ## Returns[​](#returns "Direct link to Returns") `Promise`<`UnshieldedWalletState`<`string`>> --- # getShieldedSeed > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getShieldedSeed**(`seed`): `Uint8Array` ## Parameters[​](#parameters "Direct link to Parameters") ### seed[​](#seed "Direct link to seed") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # getTestEnvironment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getTestEnvironment**(`logger`): [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md) Returns the appropriate test environment based on the MN\_TEST\_ENVIRONMENT variable. ## Parameters[​](#parameters "Direct link to Parameters") ### logger[​](#logger "Direct link to logger") `Logger` The logger instance to be used by the test environment. ## Returns[​](#returns "Direct link to Returns") [`TestEnvironment`](/api-reference/testkit-js/classes/TestEnvironment.md) The selected test environment instance. --- # getUnshieldedSeed > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getUnshieldedSeed**(`seed`): `Uint8Array` ## Parameters[​](#parameters "Direct link to Parameters") ### seed[​](#seed "Direct link to seed") `string` ## Returns[​](#returns "Direct link to Returns") `Uint8Array` --- # getWalletStateFilename > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **getWalletStateFilename**(`seed`): `string` Generates a filename for the wallet state file based on environment and optional seed ## Parameters[​](#parameters "Direct link to Parameters") ### seed[​](#seed "Direct link to seed") `string` | `undefined` ## Returns[​](#returns "Direct link to Returns") `string` Generated filename for the wallet state --- # initializeMidnightProviders > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **initializeMidnightProviders**<`PCK`, `PS`>(`midnightWalletProvider`, `environmentConfiguration`, `contractConfiguration`): `MidnightProviders`<`PCK`, `string`, `PS`> Configures and returns the required providers for a Midnight contract. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PCK[​](#pck "Direct link to PCK") `PCK` *extends* `string` Type parameter for the input circuit key string ### PS[​](#ps "Direct link to PS") `PS` Type parameter for the private state ## Parameters[​](#parameters "Direct link to Parameters") ### midnightWalletProvider[​](#midnightwalletprovider "Direct link to midnightWalletProvider") [`MidnightWalletProvider`](/api-reference/testkit-js/classes/MidnightWalletProvider.md) The midnightWalletProvider provider instance to use for transactions ### environmentConfiguration[​](#environmentconfiguration "Direct link to environmentConfiguration") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) Configuration for the environment including indexer and proof server details ### contractConfiguration[​](#contractconfiguration "Direct link to contractConfiguration") [`ContractConfiguration`](/api-reference/testkit-js/interfaces/ContractConfiguration.md) Configuration specific to the contract including storage names and ZK config path ## Returns[​](#returns "Direct link to Returns") `MidnightProviders`<`PCK`, `string`, `PS`> An object containing all configured providers: * privateStateProvider: For managing private contract state * publicDataProvider: For accessing public blockchain data * zkConfigProvider: For zero-knowledge proof configurations * proofProvider: For generating and verifying proofs * walletProvider: For midnightWalletProvider operations * midnightProvider: For Midnight-specific operations --- # inMemoryPrivateStateProvider > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **inMemoryPrivateStateProvider**<`PSI`, `PS`>(): `PrivateStateProvider`<`PSI`, `PS`> A simple in-memory implementation of private state provider. Makes it easy to capture and rewrite private state from deploy. Note: Unlike `levelPrivateStateProvider`, this provider has no storage password configured. Therefore, export/import operations always require an explicit password in the options. ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### PSI[​](#psi "Direct link to PSI") `PSI` *extends* `string` Type of the private state identifier. ### PS[​](#ps "Direct link to PS") `PS` *extends* `unknown` Type of the private state. ## Returns[​](#returns "Direct link to Returns") `PrivateStateProvider`<`PSI`, `PS`> An in-memory private state provider. --- # setContainersConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **setContainersConfiguration**(`containersConfig`): `void` ## Parameters[​](#parameters "Direct link to Parameters") ### containersConfig[​](#containersconfig "Direct link to containersConfig") [`ContainersConfiguration`](/api-reference/testkit-js/interfaces/ContainersConfiguration.md) ## Returns[​](#returns "Direct link to Returns") `void` --- # stateValueEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **stateValueEqual**(`a`, `b`): `boolean` ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") `StateValue` ### b[​](#b "Direct link to b") `StateValue` ## Returns[​](#returns "Direct link to Returns") `boolean` --- # syncWallet > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **syncWallet**(`wallet`, `throttleTime?`, `timeout?`): `Promise`<`FacadeState`> ## Parameters[​](#parameters "Direct link to Parameters") ### wallet[​](#wallet "Direct link to wallet") `WalletFacade` ### throttleTime?[​](#throttletime "Direct link to throttleTime?") `number` = `2_000` ### timeout?[​](#timeout "Direct link to timeout?") `number` = `90_000` ## Returns[​](#returns "Direct link to Returns") `Promise`<`FacadeState`> --- # txsEqual > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **txsEqual**<`S`, `P`, `B`>(`a`, `b`): `boolean` ## Type Parameters[​](#type-parameters "Direct link to Type Parameters") ### S[​](#s "Direct link to S") `S` *extends* `Signaturish` ### P[​](#p "Direct link to P") `P` *extends* `Proofish` ### B[​](#b "Direct link to B") `B` *extends* `Bindingish` ## Parameters[​](#parameters "Direct link to Parameters") ### a[​](#a "Direct link to a") `Transaction`<`S`, `P`, `B`> ### b[​](#b-1 "Direct link to b") `Transaction`<`S`, `P`, `B`> ## Returns[​](#returns "Direct link to Returns") `boolean` --- # waitForFunds > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **waitForFunds**(`wallet`, `env`, `tokenType?`, `fundFromFaucet?`): `Promise`<`bigint`> ## Parameters[​](#parameters "Direct link to Parameters") ### wallet[​](#wallet "Direct link to wallet") `WalletFacade` ### env[​](#env "Direct link to env") [`EnvironmentConfiguration`](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) ### tokenType?[​](#tokentype "Direct link to tokenType?") `TokenType` = `...` ### fundFromFaucet?[​](#fundfromfaucet "Direct link to fundFromFaucet?") `boolean` = `false` ## Returns[​](#returns "Direct link to Returns") `Promise`<`bigint`> --- # globals > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Classes[​](#classes "Direct link to Classes") * [DAppConnectorInitialAPI](/api-reference/testkit-js/classes/DAppConnectorInitialAPI.md) * [DAppConnectorWalletAdapter](/api-reference/testkit-js/classes/DAppConnectorWalletAdapter.md) * [DynamicProofServerContainer](/api-reference/testkit-js/classes/DynamicProofServerContainer.md) * [EnvVarRemoteTestEnvironment](/api-reference/testkit-js/classes/EnvVarRemoteTestEnvironment.md) * [FaucetClient](/api-reference/testkit-js/classes/FaucetClient.md) * [FluentWalletBuilder](/api-reference/testkit-js/classes/FluentWalletBuilder.md) * [GzipFile](/api-reference/testkit-js/classes/GzipFile.md) * [IndexerClient](/api-reference/testkit-js/classes/IndexerClient.md) * [LocalTestConfiguration](/api-reference/testkit-js/classes/LocalTestConfiguration.md) * [LocalTestEnvironment](/api-reference/testkit-js/classes/LocalTestEnvironment.md) * [MidnightWalletProvider](/api-reference/testkit-js/classes/MidnightWalletProvider.md) * [NodeClient](/api-reference/testkit-js/classes/NodeClient.md) * [PreprodTestEnvironment](/api-reference/testkit-js/classes/PreprodTestEnvironment.md) * [PreviewTestEnvironment](/api-reference/testkit-js/classes/PreviewTestEnvironment.md) * [ProofServerClient](/api-reference/testkit-js/classes/ProofServerClient.md) * [QanetTestEnvironment](/api-reference/testkit-js/classes/QanetTestEnvironment.md) * [RemoteTestEnvironment](/api-reference/testkit-js/classes/RemoteTestEnvironment.md) * [StaticProofServerContainer](/api-reference/testkit-js/classes/StaticProofServerContainer.md) * [TestEnvironment](/api-reference/testkit-js/classes/TestEnvironment.md) * [WalletFactory](/api-reference/testkit-js/classes/WalletFactory.md) * [WalletSaveStateProvider](/api-reference/testkit-js/classes/WalletSaveStateProvider.md) * [WalletSeeds](/api-reference/testkit-js/classes/WalletSeeds.md) ## Interfaces[​](#interfaces "Direct link to Interfaces") * [ContainerEndpoints](/api-reference/testkit-js/interfaces/ContainerEndpoints.md) * [ContainersConfiguration](/api-reference/testkit-js/interfaces/ContainersConfiguration.md) * [ContractConfiguration](/api-reference/testkit-js/interfaces/ContractConfiguration.md) * [DustWalletOptions](/api-reference/testkit-js/interfaces/DustWalletOptions.md) * [EnvironmentConfiguration](/api-reference/testkit-js/interfaces/EnvironmentConfiguration.md) * [LogConfiguration](/api-reference/testkit-js/interfaces/LogConfiguration.md) * [ProofServerContainer](/api-reference/testkit-js/interfaces/ProofServerContainer.md) * [ProofServerContainerConfiguration](/api-reference/testkit-js/interfaces/ProofServerContainerConfiguration.md) * [StandaloneContainerNames](/api-reference/testkit-js/interfaces/StandaloneContainerNames.md) * [StandaloneContainersConfiguration](/api-reference/testkit-js/interfaces/StandaloneContainersConfiguration.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [ComponentPortsConfiguration](/api-reference/testkit-js/type-aliases/ComponentPortsConfiguration.md) ## Variables[​](#variables "Direct link to Variables") * [DEFAULT\_DUST\_OPTIONS](/api-reference/testkit-js/variables/DEFAULT_DUST_OPTIONS.md) * [DEFAULT\_WALLET\_STATE\_DIRECTORY](/api-reference/testkit-js/variables/DEFAULT_WALLET_STATE_DIRECTORY.md) * [defaultContainersConfiguration](/api-reference/testkit-js/variables/defaultContainersConfiguration.md) * [latestContainersConfiguration](/api-reference/testkit-js/variables/latestContainersConfiguration.md) * [logger](/api-reference/testkit-js/variables/logger.md) * [MINUTE](/api-reference/testkit-js/variables/MINUTE.md) * [TEST\_MNEMONIC](/api-reference/testkit-js/variables/TEST_MNEMONIC.md) ## Functions[​](#functions "Direct link to Functions") * [buildUrlWithPath](/api-reference/testkit-js/functions/buildUrlWithPath.md) * [createDefaultTestLogger](/api-reference/testkit-js/functions/createDefaultTestLogger.md) * [createLogger](/api-reference/testkit-js/functions/createLogger.md) * [delay](/api-reference/testkit-js/functions/delay.md) * [expectFoundAndDeployedStatesEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedStatesEqual.md) * [expectFoundAndDeployedTxDataEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedTxDataEqual.md) * [expectFoundAndDeployedTxPrivateDataEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedTxPrivateDataEqual.md) * [expectFoundAndDeployedTxPublicDataEqual](/api-reference/testkit-js/functions/expectFoundAndDeployedTxPublicDataEqual.md) * [expectSuccessfulCallTx](/api-reference/testkit-js/functions/expectSuccessfulCallTx.md) * [expectSuccessfulDeployTx](/api-reference/testkit-js/functions/expectSuccessfulDeployTx.md) * [expectSuccessfulTxData](/api-reference/testkit-js/functions/expectSuccessfulTxData.md) * [getContainersConfiguration](/api-reference/testkit-js/functions/getContainersConfiguration.md) * [getDustSeed](/api-reference/testkit-js/functions/getDustSeed.md) * [getInitialShieldedState](/api-reference/testkit-js/functions/getInitialShieldedState.md) * [getInitialState](/api-reference/testkit-js/functions/getInitialState.md) * [getInitialUnshieldedState](/api-reference/testkit-js/functions/getInitialUnshieldedState.md) * [getShieldedSeed](/api-reference/testkit-js/functions/getShieldedSeed.md) * [getTestEnvironment](/api-reference/testkit-js/functions/getTestEnvironment.md) * [getUnshieldedSeed](/api-reference/testkit-js/functions/getUnshieldedSeed.md) * [getWalletStateFilename](/api-reference/testkit-js/functions/getWalletStateFilename.md) * [initializeMidnightProviders](/api-reference/testkit-js/functions/initializeMidnightProviders.md) * [inMemoryPrivateStateProvider](/api-reference/testkit-js/functions/inMemoryPrivateStateProvider.md) * [setContainersConfiguration](/api-reference/testkit-js/functions/setContainersConfiguration.md) * [stateValueEqual](/api-reference/testkit-js/functions/stateValueEqual.md) * [syncWallet](/api-reference/testkit-js/functions/syncWallet.md) * [txsEqual](/api-reference/testkit-js/functions/txsEqual.md) * [waitForFunds](/api-reference/testkit-js/functions/waitForFunds.md) --- # ContainerEndpoints > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Network endpoint configuration for a container ## Properties[​](#properties "Direct link to Properties") ### name[​](#name "Direct link to name") > **name**: `string` Name of the container *** ### port[​](#port "Direct link to port") > **port**: `number` Port number the container listens on *** ### waitStrategy[​](#waitstrategy "Direct link to waitStrategy") > **waitStrategy**: `WaitStrategy` TestContainers WaitStrategy to use for container start --- # ContainersConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Top-level configuration for all test containers ## Properties[​](#properties "Direct link to Properties") ### log[​](#log "Direct link to log") > **log**: [`LogConfiguration`](/api-reference/testkit-js/interfaces/LogConfiguration.md) Logging configuration *** ### proofServer[​](#proofserver "Direct link to proofServer") > **proofServer**: [`ProofServerContainerConfiguration`](/api-reference/testkit-js/interfaces/ProofServerContainerConfiguration.md) Proof server container configuration *** ### standalone[​](#standalone "Direct link to standalone") > **standalone**: [`StandaloneContainersConfiguration`](/api-reference/testkit-js/interfaces/StandaloneContainersConfiguration.md) Standalone mode containers configuration --- # ContractConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Configuration interface for Midnight contracts. ## Properties[​](#properties "Direct link to Properties") ### privateStateStoreName[​](#privatestatestorename "Direct link to privateStateStoreName") > `readonly` **privateStateStoreName**: `string` Name of the store used for persisting private state data. This is used as a base name - a signing key store will also be created with "-signing-keys" appended. *** ### zkConfigPath[​](#zkconfigpath "Direct link to zkConfigPath") > `readonly` **zkConfigPath**: `string` File system path to the zero-knowledge proof configuration files. This should point to the directory containing the circuit verification keys and other ZK artifacts. --- # DustWalletOptions > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** ## Properties[​](#properties "Direct link to Properties") ### additionalFeeOverhead[​](#additionalfeeoverhead "Direct link to additionalFeeOverhead") > **additionalFeeOverhead**: `bigint` *** ### feeBlocksMargin[​](#feeblocksmargin "Direct link to feeBlocksMargin") > **feeBlocksMargin**: `number` *** ### ledgerParams[​](#ledgerparams "Direct link to ledgerParams") > **ledgerParams**: `LedgerParameters` --- # EnvironmentConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Configuration interface for the test environment services ## Properties[​](#properties "Direct link to Properties") ### faucet[​](#faucet "Direct link to faucet") > `readonly` **faucet**: `string` | `undefined` Optional URL for the faucet service to obtain test tokens *** ### indexer[​](#indexer "Direct link to indexer") > `readonly` **indexer**: `string` URL of the indexer HTTP endpoint *** ### indexerWS[​](#indexerws "Direct link to indexerWS") > `readonly` **indexerWS**: `string` WebSocket URL for the indexer service *** ### networkId[​](#networkid "Direct link to networkId") > `readonly` **networkId**: `string` Network identifier *** ### node[​](#node "Direct link to node") > `readonly` **node**: `string` URL of the blockchain node *** ### nodeWS[​](#nodews "Direct link to nodeWS") > `readonly` **nodeWS**: `string` WebSocket URL for the blockchain node *** ### proofServer[​](#proofserver "Direct link to proofServer") > `readonly` **proofServer**: `string` URL of the proof generation server *** ### walletNetworkId[​](#walletnetworkid "Direct link to walletNetworkId") > `readonly` **walletNetworkId**: `string` Wallet Network identifier --- # LogConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Configuration for test logging ## Properties[​](#properties "Direct link to Properties") ### fileName[​](#filename "Direct link to fileName") > **fileName**: `string` Name of the log file *** ### level[​](#level "Direct link to level") > **level**: `string` Log level (e.g. 'info', 'debug', etc) *** ### path[​](#path "Direct link to path") > **path**: `string` Directory path where log files will be written --- # ProofServerContainer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Interface representing a proof server container that can be started and stopped. ## Methods[​](#methods "Direct link to Methods") ### getUrl()[​](#geturl "Direct link to getUrl()") > **getUrl**(): `string` Gets the URL where the proof server can be accessed. #### Returns[​](#returns "Direct link to Returns") `string` The URL of the proof server *** ### stop()[​](#stop "Direct link to stop()") > **stop**(): `Promise`<`void`> Stops the proof server container. #### Returns[​](#returns-1 "Direct link to Returns") `Promise`<`void`> A promise that resolves when the container is stopped --- # ProofServerContainerConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Configuration for a proof server container instance ## Properties[​](#properties "Direct link to Properties") ### container[​](#container "Direct link to container") > **container**: [`ContainerEndpoints`](/api-reference/testkit-js/interfaces/ContainerEndpoints.md) Network endpoint configuration for the container *** ### fileName[​](#filename "Direct link to fileName") > **fileName**: `string` Name of the container configuration file *** ### path[​](#path "Direct link to path") > **path**: `string` Directory path where container configuration is located --- # StandaloneContainerNames > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Container endpoint configurations for standalone mode services ## Properties[​](#properties "Direct link to Properties") ### indexer[​](#indexer "Direct link to indexer") > **indexer**: [`ContainerEndpoints`](/api-reference/testkit-js/interfaces/ContainerEndpoints.md) Indexer service container configuration *** ### node[​](#node "Direct link to node") > **node**: [`ContainerEndpoints`](/api-reference/testkit-js/interfaces/ContainerEndpoints.md) Blockchain node container configuration *** ### proofServer[​](#proofserver "Direct link to proofServer") > **proofServer**: [`ContainerEndpoints`](/api-reference/testkit-js/interfaces/ContainerEndpoints.md) Proof server container configuration --- # StandaloneContainersConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** Configuration for standalone mode containers ## Properties[​](#properties "Direct link to Properties") ### container[​](#container "Direct link to container") > **container**: [`StandaloneContainerNames`](/api-reference/testkit-js/interfaces/StandaloneContainerNames.md) Container endpoint configurations *** ### fileName[​](#filename "Direct link to fileName") > **fileName**: `string` Name of the container configuration file *** ### path[​](#path "Direct link to path") > **path**: `string` Directory path where container configuration is located --- # ComponentPortsConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > **ComponentPortsConfiguration** = `object` Configuration for component ports in the local test environment ## Properties[​](#properties "Direct link to Properties") ### indexer[​](#indexer "Direct link to indexer") > **indexer**: `number` *** ### node[​](#node "Direct link to node") > **node**: `number` *** ### proofServer[​](#proofserver "Direct link to proofServer") > **proofServer**: `number` --- # DEFAULT\_DUST\_OPTIONS > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **DEFAULT\_DUST\_OPTIONS**: [`DustWalletOptions`](/api-reference/testkit-js/interfaces/DustWalletOptions.md) --- # DEFAULT\_WALLET\_STATE\_DIRECTORY > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **DEFAULT\_WALLET\_STATE\_DIRECTORY**: `"./.states"` Default directory path for storing wallet state files --- # defaultContainersConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **defaultContainersConfiguration**: [`ContainersConfiguration`](/api-reference/testkit-js/interfaces/ContainersConfiguration.md) --- # latestContainersConfiguration > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **latestContainersConfiguration**: [`ContainersConfiguration`](/api-reference/testkit-js/interfaces/ContainersConfiguration.md) --- # logger > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **logger**: `Logger`<`never`, `boolean`> --- # MINUTE > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **MINUTE**: `60000` = `60_000` --- # TEST\_MNEMONIC > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight-ntwrk/testkit-js v4.0.4**](/api-reference/testkit-js.md) *** > `const` **TEST\_MNEMONIC**: `"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon diesel"` = `'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon diesel'` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Wallet SDK API Reference The Midnight Wallet SDK provides a comprehensive TypeScript library for managing wallets on the Midnight Network. It supports the three-token system that powers Midnight: unshielded tokens (NIGHT), shielded tokens with zero-knowledge proofs, and DUST for transaction fees. For a detailed developer guide with setup instructions and walkthroughs, see the [Wallet SDK Developer Guide](/sdks/official/wallet-developer-guide.md). ## Architecture[​](#architecture "Direct link to Architecture") The Wallet SDK uses a modular package architecture with a three-wallet model that maps to Midnight's token types. ``` wallet-sdk-facade Unified entry point ├── wallet-sdk-unshielded-wallet NIGHT and unshielded token operations ├── wallet-sdk-shielded Shielded token operations with ZK proofs ├── wallet-sdk-dust-wallet DUST management for transaction fees ├── wallet-sdk-hd HD key derivation (BIP 32 / BIP 44 / CIP 1852) ├── wallet-sdk-address-format Bech32m address encoding and decoding ├── wallet-sdk-node-client Node communication ├── wallet-sdk-indexer-client Indexer queries └── wallet-sdk-prover-client Proof server interface ``` ## Packages[​](#packages "Direct link to Packages") | Package | Purpose | | ---------------------------------------------- | ----------------------------------------- | | `@midnight-ntwrk/wallet-sdk-facade` | Unified API for all wallet operations | | `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | Manages NIGHT and unshielded tokens | | `@midnight-ntwrk/wallet-sdk-shielded` | Manages shielded tokens with ZK proofs | | `@midnight-ntwrk/wallet-sdk-dust-wallet` | Manages DUST for transaction fees | | `@midnight-ntwrk/wallet-sdk-hd` | Hierarchical deterministic key derivation | | `@midnight-ntwrk/wallet-sdk-address-format` | Bech32m address encoding and decoding | | `@midnight-ntwrk/wallet-sdk-node-client` | Communicates with Midnight nodes | | `@midnight-ntwrk/wallet-sdk-indexer-client` | Queries the Midnight indexer | | `@midnight-ntwrk/wallet-sdk-prover-client` | Interfaces with the proving server | ## Wallet Facade[​](#wallet-facade "Direct link to Wallet Facade") The facade coordinates all three wallet types and provides a unified interface for balance queries, transfers, state management, and transaction execution. ### Initialize[​](#initialize "Direct link to Initialize") ``` import { type DefaultConfiguration } from '@midnight-ntwrk/wallet-sdk-facade'; import { InMemoryTransactionHistoryStorage } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet'; const configuration: DefaultConfiguration = { networkId: 'preprod', costParameters: { feeBlocksMargin: 5, }, relayURL: new URL('wss://rpc.preprod.midnight.network'), provingServerUrl: new URL('http://localhost:6300'), indexerClientConnection: { indexerHttpUrl: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWsUrl: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', }, txHistoryStorage: new InMemoryTransactionHistoryStorage(), }; const wallet = await WalletFacade.init({ configuration, shielded: (config) => ShieldedWallet(config).startWithSecretKeys(shieldedKeys), unshielded: (config) => UnshieldedWallet(config).startWithPublicKey(publicKey), dust: (config) => DustWallet(config).startWithSecretKey(dustKey, dustParams), }); ``` ### State[​](#state "Direct link to State") Access the wallet state by waiting for initial sync or subscribing to updates. ``` // Wait for initial sync const syncedState = await wallet.waitForSyncedState(); console.log('Shielded balance:', syncedState.shielded.balances); console.log('Unshielded balance:', syncedState.unshielded.balances); console.log('DUST balance:', syncedState.dust.totalCoins); // Subscribe to state changes over time wallet.state().subscribe((state) => { if (state.isSynced) { console.log('Shielded coins:', state.shielded.availableCoins.length); console.log('Unshielded UTxOs:', state.unshielded.availableCoins.length); } }); ``` ### Transfers[​](#transfers "Direct link to Transfers") Unshielded transfers use UTxO-based transactions with Schnorr signatures. Shielded transfers use zero-knowledge proofs and do not require signature operations. ``` import * as ledger from '@midnight-ntwrk/ledger-v8'; // Unshielded transfer await wallet .transferTransaction( [ { type: 'unshielded', outputs: [ { amount: 1_000_000n, receiverAddress: await receiverWallet.unshielded.getAddress(), type: ledger.unshieldedToken().raw, }, ], }, ], { shieldedSecretKeys, dustSecretKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000) } ) .then((recipe) => wallet.signRecipe(recipe, (payload) => keystore.signData(payload))) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); // Shielded transfer (no signature required) await wallet .transferTransaction( [ { type: 'shielded', outputs: [ { amount: 1_000_000n, receiverAddress: await receiverWallet.shielded.getAddress(), type: ledger.shieldedToken().raw, }, ], }, ], { shieldedSecretKeys, dustSecretKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000) } ) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` ### Lifecycle[​](#lifecycle "Direct link to Lifecycle") ``` await wallet.start(shieldedSecretKeys, dustSecretKey); await wallet.stop(); ``` ### Terms and Conditions[​](#terms-and-conditions "Direct link to Terms and Conditions") ``` const terms = await WalletFacade.fetchTermsAndConditions(networkId); await wallet.acceptTermsAndConditions(terms); ``` ## HD Wallet[​](#hd-wallet "Direct link to HD Wallet") Derives all three key types from a single seed using BIP 32 / BIP 44 / CIP 1852 derivation. ``` import * as ledger from '@midnight-ntwrk/ledger-v8'; import { HDWallet, Roles } from '@midnight-ntwrk/wallet-sdk-hd'; function deriveRoleKey(accountKey, role, addressIndex = 0) { const result = accountKey.selectRole(role).deriveKeyAt(addressIndex); if (result.type === 'keyDerived') { return Buffer.from(result.key); } return deriveRoleKey(accountKey, role, addressIndex + 1); } const hdWallet = HDWallet.fromSeed(seed); const account = hdWallet.hdWallet.selectAccount(0); const shieldedSeed = deriveRoleKey(account, Roles.Zswap); const dustSeed = deriveRoleKey(account, Roles.Dust); const unshieldedKey = deriveRoleKey(account, Roles.NightExternal); hdWallet.hdWallet.clear(); ``` ## Address Format[​](#address-format "Direct link to Address Format") Midnight uses Bech32m format for addresses with network-specific prefixes. ``` import { MidnightBech32m, UnshieldedAddress, ShieldedAddress, DustAddress, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey, } from '@midnight-ntwrk/wallet-sdk-address-format'; import * as ledger from '@midnight-ntwrk/ledger-v8'; const networkId = 'preprod'; // Encode unshielded address const verifyingKey = ledger.signatureVerifyingKey(unshieldedSecretKey.toString('hex')); const unshieldedAddress = new UnshieldedAddress( Buffer.from(ledger.addressFromKey(verifyingKey), 'hex') ); const unshieldedBech32m = MidnightBech32m.encode(networkId, unshieldedAddress).toString(); // Encode shielded address const shieldedAddress = new ShieldedAddress( new ShieldedCoinPublicKey(Buffer.from(shieldedKeys.coinPublicKey, 'hex')), new ShieldedEncryptionPublicKey(Buffer.from(shieldedKeys.encryptionPublicKey, 'hex')) ); const shieldedBech32m = MidnightBech32m.encode(networkId, shieldedAddress).toString(); // Encode DUST address const dustAddress = new DustAddress(dustSecretKey.publicKey); const dustBech32m = MidnightBech32m.encode(networkId, dustAddress).toString(); // Decode addresses const parsed = MidnightBech32m.parse(unshieldedBech32m); const decoded = parsed.decode(UnshieldedAddress, networkId); ``` ## DUST Management[​](#dust-management "Direct link to DUST Management") Register NIGHT coins to generate DUST for transaction fees. ``` const { unshielded } = await wallet.waitForSyncedState(); // Register NIGHT to start generating DUST await wallet .registerNightUtxosForDustGeneration( unshielded.availableCoins, unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signData(payload) ) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` ## DUST Sponsorship[​](#dust-sponsorship "Direct link to DUST Sponsorship") A sponsor can pay transaction fees on behalf of users. ``` // User prepares transaction without DUST balancing const userRecipe = await userWallet.balanceUnboundTransaction( transaction, { shieldedSecretKeys, dustSecretKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['shielded', 'unshielded'], } ); // Sponsor adds DUST and submits const finalized = await userWallet.finalizeRecipe( await userWallet.signRecipe(userRecipe, (payload) => keystore.signData(payload)) ); await sponsorWallet .balanceFinalizedTransaction( finalized, { shieldedSecretKeys: sponsorKeys, dustSecretKey: sponsorDust }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['dust'], } ) .then((recipe) => sponsorWallet.finalizeRecipe(recipe)) .then((tx) => sponsorWallet.submitTransaction(tx)); ``` ## Atomic Swaps[​](#atomic-swaps "Direct link to Atomic Swaps") Trustless token exchanges between parties using a single atomic transaction. ``` // Alice initiates swap offering token1 for token2 const aliceSwapTx = await aliceWallet .initSwap( { shielded: { [token1]: 1_000_000n } }, [ { type: 'shielded', outputs: [{ type: token2, amount: 1_000_000n, receiverAddress: aliceShieldedAddress, }], }, ], { shieldedSecretKeys: aliceKeys, dustSecretKey: aliceDust }, { ttl: new Date(Date.now() + 30 * 60 * 1000) } ) .then((recipe) => aliceWallet.finalizeRecipe(recipe)); // Bob completes the swap await bobWallet .balanceFinalizedTransaction( aliceSwapTx, { shieldedSecretKeys: bobKeys, dustSecretKey: bobDust }, { ttl: new Date(Date.now() + 30 * 60 * 1000) } ) .then((recipe) => bobWallet.finalizeRecipe(recipe)) .then((tx) => bobWallet.submitTransaction(tx)); ``` ## Alternative Proving[​](#alternative-proving "Direct link to Alternative Proving") Use WASM-based proving when HTTP access to a proving server is not available. ``` import { makeWasmProvingService } from '@midnight-ntwrk/wallet-sdk-capabilities'; const wallet = await WalletFacade.init({ configuration, shielded: (config) => ShieldedWallet(config).startWithSecretKeys(shieldedKeys), unshielded: (config) => UnshieldedWallet(config).startWithPublicKey(publicKey), dust: (config) => DustWallet(config).startWithSecretKey(dustKey, dustParams), provingService: () => makeWasmProvingService(), }); ``` ## Release History[​](#release-history "Direct link to Release History") See the [Wallet SDK release notes](/relnotes/wallet.md) for version history and changelog. --- > For the complete documentation index, see [llms.txt](/llms.txt) # ZSwap API **@midnight/zswap v4.0.0-rc** *** # Zswap TypeScript API This document outlines the usage of the Zswap TS API ## Network ID[​](#network-id "Direct link to Network ID") Prior to any interaction, setNetworkId should be used to set the [NetworkId](/api-reference/zswap/enumerations/NetworkId.md) to target the correct network. ## Proof stages[​](#proof-stages "Direct link to Proof stages") Most transaction components will be in one of three stages: `X`, `UnprovenX`, or `ProofErasedX`. The `UnprovenX` stage is *always* the first one. It is possible to transition to the `X` stage by proving an `UnprovenTransaction` through the proof server. For testing, and where proofs aren't necessary, the `ProofErasedX` stage is used, which can be reached via `eraseProof[s]` from the other two stages. ## Transaction structure[​](#transaction-structure "Direct link to Transaction structure") A [Transaction](/api-reference/zswap/classes/Transaction.md) runs in two phases: a *guaranteed* phase, handling fee payments and fast-to-verify operations, and a *fallible* phase, handling operations which may fail atomically, separately from the guaranteed phase. It therefore contains: * A "guaranteed" [Offer](/api-reference/zswap/classes/Offer.md) * Optionally, a "fallible" [Offer](/api-reference/zswap/classes/Offer.md) * Contract call information not accessible to this API It also contains additional cryptographic glue that will be omitted in this document. ### Zswap[​](#zswap "Direct link to Zswap") A Zswap [Offer](/api-reference/zswap/classes/Offer.md) consists of: * A set of [Input](/api-reference/zswap/classes/Input.md)s, burning coins. * A set of [Output](/api-reference/zswap/classes/Output.md)s, creating coins. * A set of [Transient](/api-reference/zswap/classes/Transient.md)s, indicating a coin that is created and burnt in the same transaction. * A mapping from [TokenType](/api-reference/zswap/type-aliases/TokenType.md)s to offer balance, positive when there are more inputs than outputs and vice versa. [Input](/api-reference/zswap/classes/Input.md)s can be created either from a [QualifiedCoinInfo](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) and a contract address, if the coin is contract-owned, or from a [QualifiedCoinInfo](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) and a ZswapLocalState, if it is user-owned. Similarly, [Output](/api-reference/zswap/classes/Output.md)s can be created from a [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md) and a contract address for contract-owned coins, or from a [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md) and a user's public key(s), if it is user-owned. A [Transient](/api-reference/zswap/classes/Transient.md) is created similarly to a [Input](/api-reference/zswap/classes/Input.md), but directly converts an existing [Output](/api-reference/zswap/classes/Output.md). A [QualifiedCoinInfo](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) is a [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md) with an index into the Merkle tree of coin commitments that can be used to find the relevant coin to spend, while a [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md) consists of a coins [TokenType](/api-reference/zswap/type-aliases/TokenType.md), value, and a nonce. ## State Structure[​](#state-structure "Direct link to State Structure") [ZswapChainState](/api-reference/zswap/classes/ZswapChainState.md) holds the on-chain state of Zswap, while ZswaplocalState contains the local, wallet state. --- # AuthorizedMint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / AuthorizedMint # Class: AuthorizedMint A request to mint a coin, authorized by the mint's recipient ## Properties[​](#properties "Direct link to Properties") ### coin[​](#coin "Direct link to coin") ``` readonly coin: CoinInfo; ``` The coin to be minted *** ### recipient[​](#recipient "Direct link to recipient") ``` readonly recipient: string; ``` The recipient of this mint ## Methods[​](#methods "Direct link to Methods") ### erase\_proof()[​](#erase_proof "Direct link to erase_proof()") ``` erase_proof(): ProofErasedAuthorizedMint ``` #### Returns[​](#returns "Direct link to Returns") [`ProofErasedAuthorizedMint`](/api-reference/zswap/classes/ProofErasedAuthorizedMint.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): AuthorizedMint ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-3 "Direct link to Returns") [`AuthorizedMint`](/api-reference/zswap/classes/AuthorizedMint.md) --- # CoinSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / CoinSecretKey # Class: CoinSecretKey A user secret key capable of spending Zswap coins ## Methods[​](#methods "Direct link to Methods") ### yesIKnowTheSecurityImplicationsOfThis\_serialize()[​](#yesiknowthesecurityimplicationsofthis_serialize "Direct link to yesIKnowTheSecurityImplicationsOfThis_serialize()") ``` yesIKnowTheSecurityImplicationsOfThis_serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> --- # EncryptionSecretKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / EncryptionSecretKey # Class: EncryptionSecretKey Holds the encryption secret key of a user, which may be used to determine if a given offer contains outputs addressed to this user ## Methods[​](#methods "Direct link to Methods") ### test()[​](#test "Direct link to test()") ``` test(offer): boolean ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### offer[​](#offer "Direct link to offer") [`Offer`](/api-reference/zswap/classes/Offer.md) #### Returns[​](#returns "Direct link to Returns") `boolean` *** ### yesIKnowTheSecurityImplicationsOfThis\_serialize()[​](#yesiknowthesecurityimplicationsofthis_serialize "Direct link to yesIKnowTheSecurityImplicationsOfThis_serialize()") ``` yesIKnowTheSecurityImplicationsOfThis_serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): EncryptionSecretKey ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`EncryptionSecretKey`](/api-reference/zswap/classes/EncryptionSecretKey.md) --- # Input > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Input # Class: Input A shielded transaction input ## Properties[​](#properties "Direct link to Properties") ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the input, if the sender is a contract *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the input ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): Input ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`Input`](/api-reference/zswap/classes/Input.md) --- # LedgerParameters > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / LedgerParameters # Class: LedgerParameters Parameters used by the Midnight ledger, including transaction fees and bounds ## Properties[​](#properties "Direct link to Properties") ### transactionCostModel[​](#transactioncostmodel "Direct link to transactionCostModel") ``` readonly transactionCostModel: TransactionCostModel; ``` The cost model used for transaction fees contained in these parameters ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): LedgerParameters ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`LedgerParameters`](/api-reference/zswap/classes/LedgerParameters.md) *** ### dummyParameters()[​](#dummyparameters "Direct link to dummyParameters()") ``` static dummyParameters(): LedgerParameters ``` A dummy set of testing parameters #### Returns[​](#returns-3 "Direct link to Returns") [`LedgerParameters`](/api-reference/zswap/classes/LedgerParameters.md) --- # LocalState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / LocalState # Class: LocalState The local state of a user/wallet, consisting of a set of unspent coins It also keeps track of coins that are in-flight, either expecting to spend or expecting to receive, and a local copy of the global coin commitment Merkle tree to generate proofs against. ## Constructors[​](#constructors "Direct link to Constructors") ### new LocalState()[​](#new-localstate "Direct link to new LocalState()") ``` new LocalState(): LocalState ``` Creates a new, empty state #### Returns[​](#returns "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) ## Properties[​](#properties "Direct link to Properties") ### coins[​](#coins "Direct link to coins") ``` readonly coins: Set; ``` The set of *spendable* coins of this wallet *** ### firstFree[​](#firstfree "Direct link to firstFree") ``` readonly firstFree: bigint; ``` The first free index in the internal coin commitments Merkle tree. This may be used to identify which merkle tree updates are necessary. *** ### pendingOutputs[​](#pendingoutputs "Direct link to pendingOutputs") ``` readonly pendingOutputs: Map; ``` The outputs that this wallet is expecting to receive in the future *** ### pendingSpends[​](#pendingspends "Direct link to pendingSpends") ``` readonly pendingSpends: Map; ``` The spends that this wallet is expecting to be finalized on-chain in the future ## Methods[​](#methods "Direct link to Methods") ### apply()[​](#apply "Direct link to apply()") ``` apply(secretKeys, offer): LocalState ``` Locally applies an offer to the current state, returning the updated state #### Parameters[​](#parameters "Direct link to Parameters") ##### secretKeys[​](#secretkeys "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### offer[​](#offer "Direct link to offer") [`Offer`](/api-reference/zswap/classes/Offer.md) #### Returns[​](#returns-1 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applyCollapsedUpdate()[​](#applycollapsedupdate "Direct link to applyCollapsedUpdate()") ``` applyCollapsedUpdate(update): LocalState ``` Applies a collapsed Merkle tree update to the current local state, fast forwarding through the indices included in it, if it is a correct update. The general flow for usage if Alice is in state A, and wants to ask Bob how to reach the new state B, is: * Find where she left off – what's her firstFree? * Find out where she's going – ask for Bob's firstFree. * Find what contents she does care about – ask Bob for the filtered entries she want to include proper in her tree. * In order, of Merkle tree indices: * Insert (with `apply` offers Alice cares about). * Skip (with this method) sections Alice does not care about, obtaining the collapsed update covering the gap from Bob. Note that `firstFree` is not included in the tree itself, and both ends of updates *are* included. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### update[​](#update "Direct link to update") [`MerkleTreeCollapsedUpdate`](/api-reference/zswap/classes/MerkleTreeCollapsedUpdate.md) #### Returns[​](#returns-2 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applyFailed()[​](#applyfailed "Direct link to applyFailed()") ``` applyFailed(offer): LocalState ``` Locally marks an offer as failed, allowing inputs used in it to be spendable once more. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### offer[​](#offer-1 "Direct link to offer") [`Offer`](/api-reference/zswap/classes/Offer.md) #### Returns[​](#returns-3 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applyFailedProofErased()[​](#applyfailedprooferased "Direct link to applyFailedProofErased()") ``` applyFailedProofErased(offer): LocalState ``` Locally marks an proof-erased offer as failed, allowing inputs used in it to be spendable once more. #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### offer[​](#offer-2 "Direct link to offer") [`ProofErasedOffer`](/api-reference/zswap/classes/ProofErasedOffer.md) #### Returns[​](#returns-4 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applyProofErased()[​](#applyprooferased "Direct link to applyProofErased()") ``` applyProofErased(secretKeys, offer): LocalState ``` Locally applies a proof-erased offer to the current state, returning the updated state #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-1 "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### offer[​](#offer-3 "Direct link to offer") [`ProofErasedOffer`](/api-reference/zswap/classes/ProofErasedOffer.md) #### Returns[​](#returns-5 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applyProofErasedTx()[​](#applyprooferasedtx "Direct link to applyProofErasedTx()") ``` applyProofErasedTx( secretKeys, tx, res): LocalState ``` Locally applies a proof-erased transaction to the current state, returning the updated state #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-2 "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### tx[​](#tx "Direct link to tx") [`ProofErasedTransaction`](/api-reference/zswap/classes/ProofErasedTransaction.md) ##### res[​](#res "Direct link to res") The result type of applying this transaction against the ledger state `"success"` | `"partialSuccess"` | `"failure"` #### Returns[​](#returns-6 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applySystemTx()[​](#applysystemtx "Direct link to applySystemTx()") ``` applySystemTx(secretKeys, tx): LocalState ``` Locally applies a system transaction to the current state, returning the updated state #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-3 "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### tx[​](#tx-1 "Direct link to tx") [`SystemTransaction`](/api-reference/zswap/classes/SystemTransaction.md) #### Returns[​](#returns-7 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### applyTx()[​](#applytx "Direct link to applyTx()") ``` applyTx( secretKeys, tx, res): LocalState ``` Locally applies a transaction to the current state, returning the updated state #### Parameters[​](#parameters-7 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-4 "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### tx[​](#tx-2 "Direct link to tx") [`Transaction`](/api-reference/zswap/classes/Transaction.md) ##### res[​](#res-1 "Direct link to res") The result type of applying this transaction against the ledger state `"success"` | `"partialSuccess"` | `"failure"` #### Returns[​](#returns-8 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-8 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-9 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### spend()[​](#spend "Direct link to spend()") ``` spend( secretKeys, coin, segment): [LocalState, UnprovenInput] ``` Initiates a new spend of a specific coin, outputting the corresponding [UnprovenInput](/api-reference/zswap/classes/UnprovenInput.md), and the updated state marking this coin as in-flight. #### Parameters[​](#parameters-9 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-5 "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### coin[​](#coin "Direct link to coin") [`QualifiedCoinInfo`](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `number` #### Returns[​](#returns-10 "Direct link to Returns") \[[`LocalState`](/api-reference/zswap/classes/LocalState.md), [`UnprovenInput`](/api-reference/zswap/classes/UnprovenInput.md)] *** ### spendFromOutput()[​](#spendfromoutput "Direct link to spendFromOutput()") ``` spendFromOutput( secretKeys, coin, segment, output): [LocalState, UnprovenTransient] ``` Initiates a new spend of a new-yet-received output, outputting the corresponding [UnprovenTransient](/api-reference/zswap/classes/UnprovenTransient.md), and the updated state marking this coin as in-flight. #### Parameters[​](#parameters-10 "Direct link to Parameters") ##### secretKeys[​](#secretkeys-6 "Direct link to secretKeys") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) ##### coin[​](#coin-1 "Direct link to coin") [`QualifiedCoinInfo`](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) ##### segment[​](#segment-1 "Direct link to segment") `number` ##### output[​](#output "Direct link to output") [`UnprovenOutput`](/api-reference/zswap/classes/UnprovenOutput.md) #### Returns[​](#returns-11 "Direct link to Returns") \[[`LocalState`](/api-reference/zswap/classes/LocalState.md), [`UnprovenTransient`](/api-reference/zswap/classes/UnprovenTransient.md)] *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-11 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-12 "Direct link to Returns") `string` *** ### watchFor()[​](#watchfor "Direct link to watchFor()") ``` watchFor(coinPublicKey, coin): LocalState ``` Adds a coin to the list of coins that are expected to be received This should be used if an output is creating a coin for this wallet, which does not contain a ciphertext to detect it. In this case, the wallet must know the commitment ahead of time to notice the receipt. #### Parameters[​](#parameters-12 "Direct link to Parameters") ##### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") `string` ##### coin[​](#coin-2 "Direct link to coin") [`CoinInfo`](/api-reference/zswap/type-aliases/CoinInfo.md) #### Returns[​](#returns-13 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): LocalState ``` #### Parameters[​](#parameters-13 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-14 "Direct link to Returns") [`LocalState`](/api-reference/zswap/classes/LocalState.md) --- # MerkleTreeCollapsedUpdate > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / MerkleTreeCollapsedUpdate # Class: MerkleTreeCollapsedUpdate A compact delta on the coin commitments Merkle tree, used to keep local spending trees in sync with the global state without requiring receiving all transactions. ## Constructors[​](#constructors "Direct link to Constructors") ### new MerkleTreeCollapsedUpdate()[​](#new-merkletreecollapsedupdate "Direct link to new MerkleTreeCollapsedUpdate()") ``` new MerkleTreeCollapsedUpdate( state, start, end): MerkleTreeCollapsedUpdate ``` Create a new compact update from a non-compact state, and inclusive `start` and `end` indices #### Parameters[​](#parameters "Direct link to Parameters") ##### state[​](#state "Direct link to state") [`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md) ##### start[​](#start "Direct link to start") `bigint` ##### end[​](#end "Direct link to end") `bigint` #### Returns[​](#returns "Direct link to Returns") [`MerkleTreeCollapsedUpdate`](/api-reference/zswap/classes/MerkleTreeCollapsedUpdate.md) #### Throws[​](#throws "Direct link to Throws") If the indices are out-of-bounds for the state, or `end < start` ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): MerkleTreeCollapsedUpdate ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-3 "Direct link to Returns") [`MerkleTreeCollapsedUpdate`](/api-reference/zswap/classes/MerkleTreeCollapsedUpdate.md) --- # Offer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Offer # Class: Offer A full Zswap offer; the zswap part of a transaction Consists of sets of [Input](/api-reference/zswap/classes/Input.md)s, [Output](/api-reference/zswap/classes/Output.md)s, and [Transient](/api-reference/zswap/classes/Transient.md)s, as well as a [deltas](/api-reference/zswap/classes/Offer.md#deltas) vector of the transaction value ## Properties[​](#properties "Direct link to Properties") ### deltas[​](#deltas "Direct link to deltas") ``` readonly deltas: Map; ``` The value of this offer for each token type; note that this may be negative This is input coin values - output coin values, for value vectors *** ### inputs[​](#inputs "Direct link to inputs") ``` readonly inputs: Input[]; ``` The inputs this offer is composed of *** ### outputs[​](#outputs "Direct link to outputs") ``` readonly outputs: Output[]; ``` The outputs this offer is composed of *** ### transient[​](#transient "Direct link to transient") ``` readonly transient: Transient[]; ``` The transients this offer is composed of ## Methods[​](#methods "Direct link to Methods") ### merge()[​](#merge "Direct link to merge()") ``` merge(other): Offer ``` Combine this offer with another #### Parameters[​](#parameters "Direct link to Parameters") ##### other[​](#other "Direct link to other") [`Offer`](/api-reference/zswap/classes/Offer.md) #### Returns[​](#returns "Direct link to Returns") [`Offer`](/api-reference/zswap/classes/Offer.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): Offer ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-3 "Direct link to Returns") [`Offer`](/api-reference/zswap/classes/Offer.md) --- # Output > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Output # Class: Output A shielded transaction output ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the output *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the output, if the recipient is a contract ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): Output ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`Output`](/api-reference/zswap/classes/Output.md) --- # ProofErasedAuthorizedMint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ProofErasedAuthorizedMint # Class: ProofErasedAuthorizedMint A request to mint a coin, authorized by the mint's recipient, with the authorizing proof having been erased ## Properties[​](#properties "Direct link to Properties") ### coin[​](#coin "Direct link to coin") ``` readonly coin: CoinInfo; ``` The coin to be minted *** ### recipient[​](#recipient "Direct link to recipient") ``` readonly recipient: string; ``` The recipient of this mint ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ProofErasedAuthorizedMint ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`ProofErasedAuthorizedMint`](/api-reference/zswap/classes/ProofErasedAuthorizedMint.md) --- # ProofErasedInput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ProofErasedInput # Class: ProofErasedInput A [Input](/api-reference/zswap/classes/Input.md), with all proof information erased Primarily for use in testing, or handling data known to be correct from external information ## Properties[​](#properties "Direct link to Properties") ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the input, if the sender is a contract *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the input ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ProofErasedInput ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`ProofErasedInput`](/api-reference/zswap/classes/ProofErasedInput.md) --- # ProofErasedOffer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ProofErasedOffer # Class: ProofErasedOffer An [Offer](/api-reference/zswap/classes/Offer.md), with all proof information erased Primarily for use in testing, or handling data known to be correct from external information ## Properties[​](#properties "Direct link to Properties") ### deltas[​](#deltas "Direct link to deltas") ``` readonly deltas: Map; ``` The value of this offer for each token type; note that this may be negative This is input coin values - output coin values, for value vectors *** ### inputs[​](#inputs "Direct link to inputs") ``` readonly inputs: ProofErasedInput[]; ``` The inputs this offer is composed of *** ### outputs[​](#outputs "Direct link to outputs") ``` readonly outputs: ProofErasedOutput[]; ``` The outputs this offer is composed of *** ### transient[​](#transient "Direct link to transient") ``` readonly transient: ProofErasedTransient[]; ``` The transients this offer is composed of ## Methods[​](#methods "Direct link to Methods") ### merge()[​](#merge "Direct link to merge()") ``` merge(other): ProofErasedOffer ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### other[​](#other "Direct link to other") [`ProofErasedOffer`](/api-reference/zswap/classes/ProofErasedOffer.md) #### Returns[​](#returns "Direct link to Returns") [`ProofErasedOffer`](/api-reference/zswap/classes/ProofErasedOffer.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ProofErasedOffer ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-3 "Direct link to Returns") [`ProofErasedOffer`](/api-reference/zswap/classes/ProofErasedOffer.md) --- # ProofErasedOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ProofErasedOutput # Class: ProofErasedOutput An [Output](/api-reference/zswap/classes/Output.md) with all proof information erased Primarily for use in testing, or handling data known to be correct from external information ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the output *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the output, if the recipient is a contract ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ProofErasedOutput ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`ProofErasedOutput`](/api-reference/zswap/classes/ProofErasedOutput.md) --- # ProofErasedTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ProofErasedTransaction # Class: ProofErasedTransaction [Transaction](/api-reference/zswap/classes/Transaction.md), with all proof information erased Primarily for use in testing, or handling data known to be correct from external information ## Properties[​](#properties "Direct link to Properties") ### fallibleCoins[​](#falliblecoins "Direct link to fallibleCoins") ``` readonly fallibleCoins: undefined | ProofErasedOffer; ``` The fallible Zswap offer *** ### guaranteedCoins[​](#guaranteedcoins "Direct link to guaranteedCoins") ``` readonly guaranteedCoins: undefined | ProofErasedOffer; ``` The guaranteed Zswap offer *** ### mint[​](#mint "Direct link to mint") ``` readonly mint: undefined | ProofErasedAuthorizedMint; ``` The mint this transaction represents, if applicable ## Methods[​](#methods "Direct link to Methods") ### fees()[​](#fees "Direct link to fees()") ``` fees(params): bigint ``` The cost of this transaction, in the atomic unit of the base token #### Parameters[​](#parameters "Direct link to Parameters") ##### params[​](#params "Direct link to params") [`LedgerParameters`](/api-reference/zswap/classes/LedgerParameters.md) #### Returns[​](#returns "Direct link to Returns") `bigint` *** ### identifiers()[​](#identifiers "Direct link to identifiers()") ``` identifiers(): string[] ``` Returns the set of identifiers contained within this transaction. Any of these *may* be used to watch for a specific transaction. #### Returns[​](#returns-1 "Direct link to Returns") `string`\[] *** ### imbalances()[​](#imbalances "Direct link to imbalances()") ``` imbalances(guaranteed, fees?): Map ``` For given fees, and a given section (guaranteed/fallible), what the surplus or deficit of this transaction in any token type is. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### guaranteed[​](#guaranteed "Direct link to guaranteed") `boolean` ##### fees?[​](#fees-1 "Direct link to fees?") `bigint` #### Returns[​](#returns-2 "Direct link to Returns") `Map`<`string`, `bigint`> *** ### merge()[​](#merge "Direct link to merge()") ``` merge(other): ProofErasedTransaction ``` Merges this transaction with another #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### other[​](#other "Direct link to other") [`ProofErasedTransaction`](/api-reference/zswap/classes/ProofErasedTransaction.md) #### Returns[​](#returns-3 "Direct link to Returns") [`ProofErasedTransaction`](/api-reference/zswap/classes/ProofErasedTransaction.md) #### Throws[​](#throws "Direct link to Throws") If both transactions have contract interactions, or they spend the same coins *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-4 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ProofErasedTransaction ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-6 "Direct link to Returns") [`ProofErasedTransaction`](/api-reference/zswap/classes/ProofErasedTransaction.md) --- # ProofErasedTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ProofErasedTransient # Class: ProofErasedTransient A [Transient](/api-reference/zswap/classes/Transient.md), with all proof information erased Primarily for use in testing, or handling data known to be correct from external information ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the transient *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address creating the transient, if applicable *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the transient ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ProofErasedTransient ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`ProofErasedTransient`](/api-reference/zswap/classes/ProofErasedTransient.md) --- # SecretKeys > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / SecretKeys # Class: SecretKeys ## Properties[​](#properties "Direct link to Properties") ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") ``` readonly coinPublicKey: string; ``` *** ### coinSecretKey[​](#coinsecretkey "Direct link to coinSecretKey") ``` readonly coinSecretKey: CoinSecretKey; ``` *** ### encryptionPublicKey[​](#encryptionpublickey "Direct link to encryptionPublicKey") ``` readonly encryptionPublicKey: string; ``` *** ### encryptionSecretKey[​](#encryptionsecretkey "Direct link to encryptionSecretKey") ``` readonly encryptionSecretKey: EncryptionSecretKey; ``` ## Methods[​](#methods "Direct link to Methods") ### fromSeed()[​](#fromseed "Direct link to fromSeed()") ``` static fromSeed(seed): SecretKeys ``` Derives secret keys from a 32-byte seed #### Parameters[​](#parameters "Direct link to Parameters") ##### seed[​](#seed "Direct link to seed") `Uint8Array`<`ArrayBufferLike`> #### Returns[​](#returns "Direct link to Returns") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) *** ### fromSeedRng()[​](#fromseedrng "Direct link to fromSeedRng()") ``` static fromSeedRng(seed): SecretKeys ``` Derives secret keys from a 32-byte seed using deprecated implementation. Use only for compatibility purposes #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### seed[​](#seed-1 "Direct link to seed") `Uint8Array`<`ArrayBufferLike`> #### Returns[​](#returns-1 "Direct link to Returns") [`SecretKeys`](/api-reference/zswap/classes/SecretKeys.md) --- # SystemTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / SystemTransaction # Class: SystemTransaction A priviledged transaction issued by the system. ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): Transaction ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`Transaction`](/api-reference/zswap/classes/Transaction.md) --- # Transaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Transaction # Class: Transaction A Midnight transaction, consisting a guaranteed and fallible [Offer](/api-reference/zswap/classes/Offer.md), and contract call information hidden from this API. The guaranteed section are run first, and fee payment is taken during this part. If it succeeds, the fallible section is also run, and atomically rolled back if it fails. ## Properties[​](#properties "Direct link to Properties") ### fallibleCoins[​](#falliblecoins "Direct link to fallibleCoins") ``` readonly fallibleCoins: undefined | Offer; ``` The fallible Zswap offer *** ### guaranteedCoins[​](#guaranteedcoins "Direct link to guaranteedCoins") ``` readonly guaranteedCoins: undefined | Offer; ``` The guaranteed Zswap offer *** ### mint[​](#mint "Direct link to mint") ``` readonly mint: undefined | AuthorizedMint; ``` The mint this transaction represents, if applicable ## Methods[​](#methods "Direct link to Methods") ### eraseProofs()[​](#eraseproofs "Direct link to eraseProofs()") ``` eraseProofs(): ProofErasedTransaction ``` Erases the proofs contained in this transaction #### Returns[​](#returns "Direct link to Returns") [`ProofErasedTransaction`](/api-reference/zswap/classes/ProofErasedTransaction.md) *** ### fees()[​](#fees "Direct link to fees()") ``` fees(params): bigint ``` The cost of this transaction, in the atomic unit of the base token #### Parameters[​](#parameters "Direct link to Parameters") ##### params[​](#params "Direct link to params") [`LedgerParameters`](/api-reference/zswap/classes/LedgerParameters.md) #### Returns[​](#returns-1 "Direct link to Returns") `bigint` *** ### identifiers()[​](#identifiers "Direct link to identifiers()") ``` identifiers(): string[] ``` Returns the set of identifiers contained within this transaction. Any of these *may* be used to watch for a specific transaction. #### Returns[​](#returns-2 "Direct link to Returns") `string`\[] *** ### imbalances()[​](#imbalances "Direct link to imbalances()") ``` imbalances(guaranteed, fees?): Map ``` For given fees, and a given section (guaranteed/fallible), what the surplus or deficit of this transaction in any token type is. #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### guaranteed[​](#guaranteed "Direct link to guaranteed") `boolean` ##### fees?[​](#fees-1 "Direct link to fees?") `bigint` #### Returns[​](#returns-3 "Direct link to Returns") `Map`<`string`, `bigint`> *** ### merge()[​](#merge "Direct link to merge()") ``` merge(other): Transaction ``` Merges this transaction with another #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### other[​](#other "Direct link to other") [`Transaction`](/api-reference/zswap/classes/Transaction.md) #### Returns[​](#returns-4 "Direct link to Returns") [`Transaction`](/api-reference/zswap/classes/Transaction.md) #### Throws[​](#throws "Direct link to Throws") If both transactions have contract interactions, or they spend the same coins *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-5 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-6 "Direct link to Returns") `string` *** ### transactionHash()[​](#transactionhash "Direct link to transactionHash()") ``` transactionHash(): string ``` Returns the hash associated with this transaction. Due to the ability to merge transactions, this should not be used to watch for a specific transaction. #### Returns[​](#returns-7 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): Transaction ``` #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-8 "Direct link to Returns") [`Transaction`](/api-reference/zswap/classes/Transaction.md) *** ### fromUnproven()[​](#fromunproven "Direct link to fromUnproven()") ``` static fromUnproven(prove, unproven): Promise ``` Type hint that you should use an external proving function, for instance via the proof server. #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### prove[​](#prove "Direct link to prove") (`unproven`) => `Promise`<[`Transaction`](/api-reference/zswap/classes/Transaction.md)> ##### unproven[​](#unproven "Direct link to unproven") [`UnprovenTransaction`](/api-reference/zswap/classes/UnprovenTransaction.md) #### Returns[​](#returns-9 "Direct link to Returns") `Promise`<[`Transaction`](/api-reference/zswap/classes/Transaction.md)> --- # TransactionCostModel > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / TransactionCostModel # Class: TransactionCostModel ## Properties[​](#properties "Direct link to Properties") ### inputFeeOverhead[​](#inputfeeoverhead "Direct link to inputFeeOverhead") ``` readonly inputFeeOverhead: bigint; ``` The increase in fees to expect from adding a new input to a transaction *** ### outputFeeOverhead[​](#outputfeeoverhead "Direct link to outputFeeOverhead") ``` readonly outputFeeOverhead: bigint; ``` The increase in fees to expect from adding a new output to a transaction ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): TransactionCostModel ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`TransactionCostModel`](/api-reference/zswap/classes/TransactionCostModel.md) *** ### dummyTransactionCostModel()[​](#dummytransactioncostmodel "Direct link to dummyTransactionCostModel()") ``` static dummyTransactionCostModel(): TransactionCostModel ``` A dummy cost model, for use in testing #### Returns[​](#returns-3 "Direct link to Returns") [`TransactionCostModel`](/api-reference/zswap/classes/TransactionCostModel.md) --- # Transient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Transient # Class: Transient A shielded "transient"; an output that is immediately spent within the same transaction ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the transient *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address creating the transient, if applicable *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the transient ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): Transient ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`Transient`](/api-reference/zswap/classes/Transient.md) --- # UnprovenAuthorizedMint > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / UnprovenAuthorizedMint # Class: UnprovenAuthorizedMint A request to mint a coin, authorized by the mint's recipient, without the proof for the authorization being generated ## Properties[​](#properties "Direct link to Properties") ### coin[​](#coin "Direct link to coin") ``` readonly coin: CoinInfo; ``` The coin to be minted *** ### recipient[​](#recipient "Direct link to recipient") ``` readonly recipient: string; ``` The recipient of this mint ## Methods[​](#methods "Direct link to Methods") ### erase\_proof()[​](#erase_proof "Direct link to erase_proof()") ``` erase_proof(): ProofErasedAuthorizedMint ``` #### Returns[​](#returns "Direct link to Returns") [`ProofErasedAuthorizedMint`](/api-reference/zswap/classes/ProofErasedAuthorizedMint.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): UnprovenAuthorizedMint ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenAuthorizedMint`](/api-reference/zswap/classes/UnprovenAuthorizedMint.md) --- # UnprovenInput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / UnprovenInput # Class: UnprovenInput A [Input](/api-reference/zswap/classes/Input.md), before being proven All "shielded" information in the input can still be extracted at this stage! ## Properties[​](#properties "Direct link to Properties") ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the input, if the sender is a contract *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the input ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): UnprovenInput ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`UnprovenInput`](/api-reference/zswap/classes/UnprovenInput.md) *** ### newContractOwned()[​](#newcontractowned "Direct link to newContractOwned()") ``` static newContractOwned( coin, segment, contract, state): UnprovenInput ``` Creates a new input, spending a specific coin from a smart contract, against a state which contains this coin. Note that inputs created in this way *also* need to be authorized by the contract #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`QualifiedCoinInfo`](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `number` ##### contract[​](#contract "Direct link to contract") `string` ##### state[​](#state "Direct link to state") [`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md) #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenInput`](/api-reference/zswap/classes/UnprovenInput.md) --- # UnprovenOffer > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / UnprovenOffer # Class: UnprovenOffer A [Offer](/api-reference/zswap/classes/Offer.md), prior to being proven All "shielded" information in the offer can still be extracted at this stage! ## Constructors[​](#constructors "Direct link to Constructors") ### new UnprovenOffer()[​](#new-unprovenoffer "Direct link to new UnprovenOffer()") ``` new UnprovenOffer(): UnprovenOffer ``` #### Returns[​](#returns "Direct link to Returns") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) ## Properties[​](#properties "Direct link to Properties") ### deltas[​](#deltas "Direct link to deltas") ``` readonly deltas: Map; ``` The value of this offer for each token type; note that this may be negative This is input coin values - output coin values, for value vectors *** ### inputs[​](#inputs "Direct link to inputs") ``` readonly inputs: UnprovenInput[]; ``` The inputs this offer is composed of *** ### outputs[​](#outputs "Direct link to outputs") ``` readonly outputs: UnprovenOutput[]; ``` The outputs this offer is composed of *** ### transient[​](#transient "Direct link to transient") ``` readonly transient: UnprovenTransient[]; ``` The transients this offer is composed of ## Methods[​](#methods "Direct link to Methods") ### merge()[​](#merge "Direct link to merge()") ``` merge(other): UnprovenOffer ``` Combine this offer with another #### Parameters[​](#parameters "Direct link to Parameters") ##### other[​](#other "Direct link to other") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) #### Returns[​](#returns-1 "Direct link to Returns") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-3 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): UnprovenOffer ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-4 "Direct link to Returns") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) *** ### fromInput()[​](#frominput "Direct link to fromInput()") ``` static fromInput( input, type_, value): UnprovenOffer ``` Creates a singleton offer, from an [UnprovenInput](/api-reference/zswap/classes/UnprovenInput.md) and its value vector #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### input[​](#input "Direct link to input") [`UnprovenInput`](/api-reference/zswap/classes/UnprovenInput.md) ##### type\_[​](#type_ "Direct link to type_") `string` ##### value[​](#value "Direct link to value") `bigint` #### Returns[​](#returns-5 "Direct link to Returns") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) *** ### fromOutput()[​](#fromoutput "Direct link to fromOutput()") ``` static fromOutput( output, type_, value): UnprovenOffer ``` Creates a singleton offer, from an [UnprovenOutput](/api-reference/zswap/classes/UnprovenOutput.md) and its value vector #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### output[​](#output "Direct link to output") [`UnprovenOutput`](/api-reference/zswap/classes/UnprovenOutput.md) ##### type\_[​](#type_-1 "Direct link to type_") `string` ##### value[​](#value-1 "Direct link to value") `bigint` #### Returns[​](#returns-6 "Direct link to Returns") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) *** ### fromTransient()[​](#fromtransient "Direct link to fromTransient()") ``` static fromTransient(transient): UnprovenOffer ``` Creates a singleton offer, from an [UnprovenTransient](/api-reference/zswap/classes/UnprovenTransient.md) #### Parameters[​](#parameters-6 "Direct link to Parameters") ##### transient[​](#transient-1 "Direct link to transient") [`UnprovenTransient`](/api-reference/zswap/classes/UnprovenTransient.md) #### Returns[​](#returns-7 "Direct link to Returns") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) --- # UnprovenOutput > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / UnprovenOutput # Class: UnprovenOutput An [Output](/api-reference/zswap/classes/Output.md) before being proven All "shielded" information in the output can still be extracted at this stage! ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the output *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address receiving the output, if the recipient is a contract ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): UnprovenOutput ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`UnprovenOutput`](/api-reference/zswap/classes/UnprovenOutput.md) *** ### new()[​](#new "Direct link to new()") ``` static new( coin, segment, target_cpk, target_epk): UnprovenOutput ``` Creates a new output, targeted to a user's coin public key. Optionally the output contains a ciphertext encrypted to the user's encryption public key, which may be omitted *only* if the [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md) is transferred to the recipient another way #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`CoinInfo`](/api-reference/zswap/type-aliases/CoinInfo.md) ##### segment[​](#segment "Direct link to segment") `number` ##### target\_cpk[​](#target_cpk "Direct link to target_cpk") `string` ##### target\_epk[​](#target_epk "Direct link to target_epk") `string` #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenOutput`](/api-reference/zswap/classes/UnprovenOutput.md) *** ### newContractOwned()[​](#newcontractowned "Direct link to newContractOwned()") ``` static newContractOwned( coin, segment, contract): UnprovenOutput ``` Creates a new output, targeted to a smart contract A contract must *also* explicitly receive a coin created in this way for the output to be valid #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### coin[​](#coin-1 "Direct link to coin") [`CoinInfo`](/api-reference/zswap/type-aliases/CoinInfo.md) ##### segment[​](#segment-1 "Direct link to segment") `number` ##### contract[​](#contract "Direct link to contract") `string` #### Returns[​](#returns-4 "Direct link to Returns") [`UnprovenOutput`](/api-reference/zswap/classes/UnprovenOutput.md) --- # UnprovenTransaction > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / UnprovenTransaction # Class: UnprovenTransaction [Transaction](/api-reference/zswap/classes/Transaction.md), prior to being proven All "shielded" information in the transaction can still be extracted at this stage! ## Constructors[​](#constructors "Direct link to Constructors") ### new UnprovenTransaction()[​](#new-unproventransaction "Direct link to new UnprovenTransaction()") ``` new UnprovenTransaction(guaranteed, fallible?): UnprovenTransaction ``` Creates the transaction from guaranteed/fallible [UnprovenOffer](/api-reference/zswap/classes/UnprovenOffer.md)s #### Parameters[​](#parameters "Direct link to Parameters") ##### guaranteed[​](#guaranteed "Direct link to guaranteed") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) ##### fallible?[​](#fallible "Direct link to fallible?") [`UnprovenOffer`](/api-reference/zswap/classes/UnprovenOffer.md) #### Returns[​](#returns "Direct link to Returns") [`UnprovenTransaction`](/api-reference/zswap/classes/UnprovenTransaction.md) ## Properties[​](#properties "Direct link to Properties") ### fallibleCoins[​](#falliblecoins "Direct link to fallibleCoins") ``` readonly fallibleCoins: undefined | UnprovenOffer; ``` The fallible Zswap offer *** ### guaranteedCoins[​](#guaranteedcoins "Direct link to guaranteedCoins") ``` readonly guaranteedCoins: undefined | UnprovenOffer; ``` The guaranteed Zswap offer *** ### mint[​](#mint "Direct link to mint") ``` readonly mint: undefined | UnprovenAuthorizedMint; ``` The mint this transaction represents, if applicable ## Methods[​](#methods "Direct link to Methods") ### eraseProofs()[​](#eraseproofs "Direct link to eraseProofs()") ``` eraseProofs(): ProofErasedTransaction ``` Erases the proofs contained in this transaction #### Returns[​](#returns-1 "Direct link to Returns") [`ProofErasedTransaction`](/api-reference/zswap/classes/ProofErasedTransaction.md) *** ### identifiers()[​](#identifiers "Direct link to identifiers()") ``` identifiers(): string[] ``` Returns the set of identifiers contained within this transaction. Any of these *may* be used to watch for a specific transaction. #### Returns[​](#returns-2 "Direct link to Returns") `string`\[] *** ### merge()[​](#merge "Direct link to merge()") ``` merge(other): UnprovenTransaction ``` Merges this transaction with another #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### other[​](#other "Direct link to other") [`UnprovenTransaction`](/api-reference/zswap/classes/UnprovenTransaction.md) #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenTransaction`](/api-reference/zswap/classes/UnprovenTransaction.md) #### Throws[​](#throws "Direct link to Throws") If both transactions have contract interactions, or they spend the same coins *** ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-4 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-5 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): UnprovenTransaction ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-6 "Direct link to Returns") [`UnprovenTransaction`](/api-reference/zswap/classes/UnprovenTransaction.md) *** ### fromMint()[​](#frommint "Direct link to fromMint()") ``` static fromMint(mint): UnprovenTransaction ``` Creates a minting claim transaction, the funds claimed must have been legitimately minted previously. #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### mint[​](#mint-1 "Direct link to mint") [`UnprovenAuthorizedMint`](/api-reference/zswap/classes/UnprovenAuthorizedMint.md) #### Returns[​](#returns-7 "Direct link to Returns") [`UnprovenTransaction`](/api-reference/zswap/classes/UnprovenTransaction.md) --- # UnprovenTransient > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / UnprovenTransient # Class: UnprovenTransient A [Transient](/api-reference/zswap/classes/Transient.md), before being proven All "shielded" information in the transient can still be extracted at this stage! ## Properties[​](#properties "Direct link to Properties") ### commitment[​](#commitment "Direct link to commitment") ``` readonly commitment: string; ``` The commitment of the transient *** ### contractAddress[​](#contractaddress "Direct link to contractAddress") ``` readonly contractAddress: undefined | string; ``` The contract address creating the transient, if applicable *** ### nullifier[​](#nullifier "Direct link to nullifier") ``` readonly nullifier: string; ``` The nullifier of the transient ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-1 "Direct link to Returns") `string` *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): UnprovenTransient ``` #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-2 "Direct link to Returns") [`UnprovenTransient`](/api-reference/zswap/classes/UnprovenTransient.md) *** ### newFromContractOwnedOutput()[​](#newfromcontractownedoutput "Direct link to newFromContractOwnedOutput()") ``` static newFromContractOwnedOutput( coin, segment, output): UnprovenTransient ``` Creates a new contract-owned transient, from a given output and its coin. The [QualifiedCoinInfo](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) should have an `mt_index` of `0` #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### coin[​](#coin "Direct link to coin") [`QualifiedCoinInfo`](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) ##### segment[​](#segment "Direct link to segment") `number` ##### output[​](#output "Direct link to output") [`UnprovenOutput`](/api-reference/zswap/classes/UnprovenOutput.md) #### Returns[​](#returns-3 "Direct link to Returns") [`UnprovenTransient`](/api-reference/zswap/classes/UnprovenTransient.md) --- # ZswapChainState > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ZswapChainState # Class: ZswapChainState The on-chain state of Zswap, consisting of a Merkle tree of coin commitments, a set of nullifiers, an index into the Merkle tree, and a set of valid past Merkle tree roots ## Constructors[​](#constructors "Direct link to Constructors") ### new ZswapChainState()[​](#new-zswapchainstate "Direct link to new ZswapChainState()") ``` new ZswapChainState(): ZswapChainState ``` #### Returns[​](#returns "Direct link to Returns") [`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md) ## Properties[​](#properties "Direct link to Properties") ### firstFree[​](#firstfree "Direct link to firstFree") ``` readonly firstFree: bigint; ``` The first free index in the coin commitment tree ## Methods[​](#methods "Direct link to Methods") ### serialize()[​](#serialize "Direct link to serialize()") ``` serialize(netid): Uint8Array ``` #### Parameters[​](#parameters "Direct link to Parameters") ##### netid[​](#netid "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-1 "Direct link to Returns") `Uint8Array`<`ArrayBufferLike`> *** ### toString()[​](#tostring "Direct link to toString()") ``` toString(compact?): string ``` #### Parameters[​](#parameters-1 "Direct link to Parameters") ##### compact?[​](#compact "Direct link to compact?") `boolean` #### Returns[​](#returns-2 "Direct link to Returns") `string` *** ### tryApply()[​](#tryapply "Direct link to tryApply()") ``` tryApply(offer, whitelist?): [ZswapChainState, Map] ``` Try to apply an [Offer](/api-reference/zswap/classes/Offer.md) to the state, returning the updated state and a map on newly inserted coin commitments to their inserted indices. #### Parameters[​](#parameters-2 "Direct link to Parameters") ##### offer[​](#offer "Direct link to offer") [`Offer`](/api-reference/zswap/classes/Offer.md) ##### whitelist?[​](#whitelist "Direct link to whitelist?") `Set`<`string`> A set of contract addresses that are of interest. If set, *only* these addresses are tracked, and all other information is discarded. #### Returns[​](#returns-3 "Direct link to Returns") \[[`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md), `Map`<`string`, `bigint`>] *** ### tryApplyProofErased()[​](#tryapplyprooferased "Direct link to tryApplyProofErased()") ``` tryApplyProofErased(offer, whitelist?): [ZswapChainState, Map] ``` [tryApply](/api-reference/zswap/classes/ZswapChainState.md#tryapply) for [ProofErasedOffer](/api-reference/zswap/classes/ProofErasedOffer.md)s #### Parameters[​](#parameters-3 "Direct link to Parameters") ##### offer[​](#offer-1 "Direct link to offer") [`ProofErasedOffer`](/api-reference/zswap/classes/ProofErasedOffer.md) ##### whitelist?[​](#whitelist-1 "Direct link to whitelist?") `Set`<`string`> #### Returns[​](#returns-4 "Direct link to Returns") \[[`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md), `Map`<`string`, `bigint`>] *** ### deserialize()[​](#deserialize "Direct link to deserialize()") ``` static deserialize(raw, netid): ZswapChainState ``` #### Parameters[​](#parameters-4 "Direct link to Parameters") ##### raw[​](#raw "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-1 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-5 "Direct link to Returns") [`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md) *** ### deserializeFromLedgerState()[​](#deserializefromledgerstate "Direct link to deserializeFromLedgerState()") ``` static deserializeFromLedgerState(raw, netid): ZswapChainState ``` Given a whole ledger serialized state, deserialize only the Zswap portion #### Parameters[​](#parameters-5 "Direct link to Parameters") ##### raw[​](#raw-1 "Direct link to raw") `Uint8Array`<`ArrayBufferLike`> ##### netid[​](#netid-2 "Direct link to netid") [`NetworkId`](/api-reference/zswap/enumerations/NetworkId.md) #### Returns[​](#returns-6 "Direct link to Returns") [`ZswapChainState`](/api-reference/zswap/classes/ZswapChainState.md) --- # NetworkId > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / NetworkId # Enumeration: NetworkId The network currently being targeted ## Enumeration Members[​](#enumeration-members "Direct link to Enumeration Members") ### DevNet[​](#devnet "Direct link to DevNet") ``` DevNet: 1; ``` A developer network, not guaranteed to be persistent *** ### MainNet[​](#mainnet "Direct link to MainNet") ``` MainNet: 3; ``` The Midnight mainnet *** ### TestNet[​](#testnet "Direct link to TestNet") ``` TestNet: 2; ``` A persistent testnet *** ### Undeployed[​](#undeployed "Direct link to Undeployed") ``` Undeployed: 0; ``` A local test network --- # coinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / coinCommitment # Function: coinCommitment() ``` function coinCommitment(coin, coinPublicKey): CoinCommitment ``` Calculate commitment of a coin owned by a user ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`CoinInfo`](/api-reference/zswap/type-aliases/CoinInfo.md) ### coinPublicKey[​](#coinpublickey "Direct link to coinPublicKey") `string` ## Returns[​](#returns "Direct link to Returns") [`CoinCommitment`](/api-reference/zswap/type-aliases/CoinCommitment.md) --- # coinNullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / coinNullifier # Function: coinNullifier() ``` function coinNullifier(coin, coinSecretKey): Nullifier ``` Calculate nullifier of a coin owned by a user ## Parameters[​](#parameters "Direct link to Parameters") ### coin[​](#coin "Direct link to coin") [`CoinInfo`](/api-reference/zswap/type-aliases/CoinInfo.md) ### coinSecretKey[​](#coinsecretkey "Direct link to coinSecretKey") [`CoinSecretKey`](/api-reference/zswap/classes/CoinSecretKey.md) ## Returns[​](#returns "Direct link to Returns") [`Nullifier`](/api-reference/zswap/type-aliases/Nullifier.md) --- # createCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / createCoinInfo # Function: createCoinInfo() ``` function createCoinInfo(type_, value): CoinInfo ``` Creates a new [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md), sampling a uniform nonce ## Parameters[​](#parameters "Direct link to Parameters") ### type\_[​](#type_ "Direct link to type_") `string` ### value[​](#value "Direct link to value") `bigint` ## Returns[​](#returns "Direct link to Returns") [`CoinInfo`](/api-reference/zswap/type-aliases/CoinInfo.md) --- # nativeToken > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / nativeToken # Function: nativeToken() ``` function nativeToken(): TokenType ``` The base/system token type ## Returns[​](#returns "Direct link to Returns") [`TokenType`](/api-reference/zswap/type-aliases/TokenType.md) --- # sampleCoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / sampleCoinPublicKey # Function: sampleCoinPublicKey() ``` function sampleCoinPublicKey(): CoinPublicKey ``` Samples a dummy user coin public key, for use in testing ## Returns[​](#returns "Direct link to Returns") [`CoinPublicKey`](/api-reference/zswap/type-aliases/CoinPublicKey.md) --- # sampleContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / sampleContractAddress # Function: sampleContractAddress() ``` function sampleContractAddress(): ContractAddress ``` Samples a uniform contract address, for use in testing ## Returns[​](#returns "Direct link to Returns") [`ContractAddress`](/api-reference/zswap/type-aliases/ContractAddress.md) --- # sampleEncryptionPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / sampleEncryptionPublicKey # Function: sampleEncryptionPublicKey() ``` function sampleEncryptionPublicKey(): EncPublicKey ``` Samples a dummy user encryption public key, for use in testing ## Returns[​](#returns "Direct link to Returns") [`EncPublicKey`](/api-reference/zswap/type-aliases/EncPublicKey.md) --- # sampleTokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / sampleTokenType # Function: sampleTokenType() ``` function sampleTokenType(): TokenType ``` Samples a uniform token type, for use in testing ## Returns[​](#returns "Direct link to Returns") [`TokenType`](/api-reference/zswap/type-aliases/TokenType.md) --- # globals > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** # @midnight/zswap v4.0.0-rc ## Enumerations[​](#enumerations "Direct link to Enumerations") * [NetworkId](/api-reference/zswap/enumerations/NetworkId.md) ## Classes[​](#classes "Direct link to Classes") * [AuthorizedMint](/api-reference/zswap/classes/AuthorizedMint.md) * [CoinSecretKey](/api-reference/zswap/classes/CoinSecretKey.md) * [EncryptionSecretKey](/api-reference/zswap/classes/EncryptionSecretKey.md) * [Input](/api-reference/zswap/classes/Input.md) * [LedgerParameters](/api-reference/zswap/classes/LedgerParameters.md) * [LocalState](/api-reference/zswap/classes/LocalState.md) * [MerkleTreeCollapsedUpdate](/api-reference/zswap/classes/MerkleTreeCollapsedUpdate.md) * [Offer](/api-reference/zswap/classes/Offer.md) * [Output](/api-reference/zswap/classes/Output.md) * [ProofErasedAuthorizedMint](/api-reference/zswap/classes/ProofErasedAuthorizedMint.md) * [ProofErasedInput](/api-reference/zswap/classes/ProofErasedInput.md) * [ProofErasedOffer](/api-reference/zswap/classes/ProofErasedOffer.md) * [ProofErasedOutput](/api-reference/zswap/classes/ProofErasedOutput.md) * [ProofErasedTransaction](/api-reference/zswap/classes/ProofErasedTransaction.md) * [ProofErasedTransient](/api-reference/zswap/classes/ProofErasedTransient.md) * [SecretKeys](/api-reference/zswap/classes/SecretKeys.md) * [SystemTransaction](/api-reference/zswap/classes/SystemTransaction.md) * [Transaction](/api-reference/zswap/classes/Transaction.md) * [TransactionCostModel](/api-reference/zswap/classes/TransactionCostModel.md) * [Transient](/api-reference/zswap/classes/Transient.md) * [UnprovenAuthorizedMint](/api-reference/zswap/classes/UnprovenAuthorizedMint.md) * [UnprovenInput](/api-reference/zswap/classes/UnprovenInput.md) * [UnprovenOffer](/api-reference/zswap/classes/UnprovenOffer.md) * [UnprovenOutput](/api-reference/zswap/classes/UnprovenOutput.md) * [UnprovenTransaction](/api-reference/zswap/classes/UnprovenTransaction.md) * [UnprovenTransient](/api-reference/zswap/classes/UnprovenTransient.md) * [ZswapChainState](/api-reference/zswap/classes/ZswapChainState.md) ## Type Aliases[​](#type-aliases "Direct link to Type Aliases") * [CoinCommitment](/api-reference/zswap/type-aliases/CoinCommitment.md) * [CoinInfo](/api-reference/zswap/type-aliases/CoinInfo.md) * [CoinPublicKey](/api-reference/zswap/type-aliases/CoinPublicKey.md) * [ContractAddress](/api-reference/zswap/type-aliases/ContractAddress.md) * [EncPublicKey](/api-reference/zswap/type-aliases/EncPublicKey.md) * [Nonce](/api-reference/zswap/type-aliases/Nonce.md) * [Nullifier](/api-reference/zswap/type-aliases/Nullifier.md) * [QualifiedCoinInfo](/api-reference/zswap/type-aliases/QualifiedCoinInfo.md) * [TokenType](/api-reference/zswap/type-aliases/TokenType.md) * [TransactionHash](/api-reference/zswap/type-aliases/TransactionHash.md) * [TransactionId](/api-reference/zswap/type-aliases/TransactionId.md) ## Functions[​](#functions "Direct link to Functions") * [coinCommitment](/api-reference/zswap/functions/coinCommitment.md) * [coinNullifier](/api-reference/zswap/functions/coinNullifier.md) * [createCoinInfo](/api-reference/zswap/functions/createCoinInfo.md) * [nativeToken](/api-reference/zswap/functions/nativeToken.md) * [sampleCoinPublicKey](/api-reference/zswap/functions/sampleCoinPublicKey.md) * [sampleContractAddress](/api-reference/zswap/functions/sampleContractAddress.md) * [sampleEncryptionPublicKey](/api-reference/zswap/functions/sampleEncryptionPublicKey.md) * [sampleTokenType](/api-reference/zswap/functions/sampleTokenType.md) --- # CoinCommitment > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / CoinCommitment # Type Alias: CoinCommitment ``` type CoinCommitment: string; ``` A Zswap coin commitment, as a hex-encoded 256-bit bitstring --- # CoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / CoinInfo # Type Alias: CoinInfo ``` type CoinInfo: { nonce: Nonce; type: TokenType; value: bigint; }; ``` Information required to create a new coin, alongside details about the recipient ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` ### type[​](#type "Direct link to type") ``` type: TokenType; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # CoinPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / CoinPublicKey # Type Alias: CoinPublicKey ``` type CoinPublicKey: string; ``` A user public key capable of receiving Zswap coins, as a hex-encoded 35-byte string --- # ContractAddress > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / ContractAddress # Type Alias: ContractAddress ``` type ContractAddress: string; ``` A contract address, as a hex-encoded 35-byte string --- # EncPublicKey > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / EncPublicKey # Type Alias: EncPublicKey ``` type EncPublicKey: string; ``` An encryption public key, used to inform users of new coins sent to them --- # Nonce > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Nonce # Type Alias: Nonce ``` type Nonce: string; ``` A Zswap nonce, as a hex-encoded 256-bit string --- # Nullifier > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / Nullifier # Type Alias: Nullifier ``` type Nullifier: string; ``` A Zswap nullifier, as a hex-encoded 256-bit bitstring --- # QualifiedCoinInfo > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / QualifiedCoinInfo # Type Alias: QualifiedCoinInfo ``` type QualifiedCoinInfo: { mt_index: bigint; nonce: Nonce; type: TokenType; value: bigint; }; ``` Information required to spend an existing coin, alongside authorization of the owner ## Type declaration[​](#type-declaration "Direct link to Type declaration") ### mt\_index[​](#mt_index "Direct link to mt_index") ``` mt_index: bigint; ``` ### nonce[​](#nonce "Direct link to nonce") ``` nonce: Nonce; ``` ### type[​](#type "Direct link to type") ``` type: TokenType; ``` ### value[​](#value "Direct link to value") ``` value: bigint; ``` --- # TokenType > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / TokenType # Type Alias: TokenType ``` type TokenType: string; ``` A token type (or color), as a hex-encoded 35-byte string --- # TransactionHash > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / TransactionHash # Type Alias: TransactionHash ``` type TransactionHash: string; ``` The hash of a transaction, as a hex-encoded 256-bit bytestring --- # TransactionId > For the complete documentation index, see [llms.txt](/llms.txt) [**@midnight/zswap v4.0.0-rc**](/api-reference/zswap.md) *** [@midnight/zswap](/api-reference/zswap/globals.md) / TransactionId # Type Alias: TransactionId ``` type TransactionId: string; ``` A transaction identifier, used to index merged transactions --- ## 1[​](#1 "Direct link to 1") * [1am1](/sdks/tags/1-am.md) *** --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [OpenZeppelin contracts for Compact](/sdks/community/openzeppelin-compact-contracts.md) A library of token standards, access control, and security primitives for Compact smart contracts, modeled on OpenZeppelin's Solidity contracts. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Midnight agent skills](/sdks/community/ai-tools/midnight-agent-skills.md) midnight\_agent\_skills is a set of four modular agent skills that give AI coding assistants accurate knowledge of Compact syntax, Midnight SDK, network configuration, and common gotchas sourced from the developer community. --- ## [Midnight agent skills](/sdks/community/ai-tools/midnight-agent-skills.md) midnight\_agent\_skills is a set of four modular agent skills that give AI coding assistants accurate knowledge of Compact syntax, Midnight SDK, network configuration, and common gotchas sourced from the developer community. --- ## [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md) Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md) Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Integrate a wallet](/sdks/community/wallets/community-wallets-integration.md) Integrate a community wallet on the Midnight Network with the DApp Connector (CAIP-372): discovery, connect, ZK proving, fees, and portable React code. --- ## [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md) Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. --- ## [Community projects](/sdks/community.md) Third-party libraries and tools built on Midnight by the wider community. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Edda Midnight starter template](/sdks/community/edda-midnight-starter.md) A full-stack starter template for building DApps on Midnight with a React frontend, Compact smart contract, CLI tooling, and educational materials. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [Edda Midnight starter template](/sdks/community/edda-midnight-starter.md) A full-stack starter template for building DApps on Midnight with a React frontend, Compact smart contract, CLI tooling, and educational materials. --- ## [Integrate a wallet](/sdks/community/wallets/community-wallets-integration.md) Integrate a community wallet on the Midnight Network with the DApp Connector (CAIP-372): discovery, connect, ZK proving, fees, and portable React code. --- ## [Midnight Live View](/sdks/community/midnight-live-view.md) A real-time terminal dashboard and persistent block monitor for Midnight validator nodes, inspired by CNTool's gLiveView. --- ## [Nightforge](/sdks/community/nightforge.md) Compile, deploy, and operate Compact contracts from one CLI with Nightforge, a community development environment for Midnight. --- ## [Midnight.js](/sdks/official/midnight-js.md) Comprehensive TypeScript SDK for building DApps on Midnight Network. --- ## [Midnight agent skills](/sdks/community/ai-tools/midnight-agent-skills.md) midnight\_agent\_skills is a set of four modular agent skills that give AI coding assistants accurate knowledge of Compact syntax, Midnight SDK, network configuration, and common gotchas sourced from the developer community. --- ## [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md) Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Integrate a wallet](/sdks/community/wallets/community-wallets-integration.md) Integrate a community wallet on the Midnight Network with the DApp Connector (CAIP-372): discovery, connect, ZK proving, fees, and portable React code. --- ## [Wallet reference](/sdks/community/wallets/community-wallets-reference.md) Reference for Midnight Network community wallets: the functionality matrix, troubleshooting and error codes, a security checklist, ecosystem, and glossary. --- ## [Midnight.js error reference](/sdks/error-reference/midnight-js.md) Error reference for the Midnight.js SDK. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Wallet reference](/sdks/community/wallets/community-wallets-reference.md) Reference for Midnight Network community wallets: the functionality matrix, troubleshooting and error codes, a security checklist, ecosystem, and glossary. --- ## [Wallet reference](/sdks/community/wallets/community-wallets-reference.md) Reference for Midnight Network community wallets: the functionality matrix, troubleshooting and error codes, a security checklist, ecosystem, and glossary. --- ## [Common SDK integration issues](/sdks/troubleshoot.md) Troubleshoot common issues when building on Midnight Network. --- ## [Common SDK integration issues](/sdks/troubleshoot.md) Troubleshoot common issues when building on Midnight Network. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md) Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Midnight.js](/sdks/official/midnight-js.md) Comprehensive TypeScript SDK for building DApps on Midnight Network. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [Midnight Live View](/sdks/community/midnight-live-view.md) A real-time terminal dashboard and persistent block monitor for Midnight validator nodes, inspired by CNTool's gLiveView. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Midnight Live View](/sdks/community/midnight-live-view.md) A real-time terminal dashboard and persistent block monitor for Midnight validator nodes, inspired by CNTool's gLiveView. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [OpenZeppelin contracts for Compact](/sdks/community/openzeppelin-compact-contracts.md) A library of token standards, access control, and security primitives for Compact smart contracts, modeled on OpenZeppelin's Solidity contracts. --- ## [Midnames](/sdks/community/midnames.md) Learn how to use the Midnames Compact playground and name service to register human-readable names for Midnight addresses. --- ## [Nightforge](/sdks/community/nightforge.md) Compile, deploy, and operate Compact contracts from one CLI with Nightforge, a community development environment for Midnight. --- ## [Integrate a wallet](/sdks/community/wallets/community-wallets-integration.md) Integrate a community wallet on the Midnight Network with the DApp Connector (CAIP-372): discovery, connect, ZK proving, fees, and portable React code. --- ## [Edda Midnight starter template](/sdks/community/edda-midnight-starter.md) A full-stack starter template for building DApps on Midnight with a React frontend, Compact smart contract, CLI tooling, and educational materials. --- ## [Nightforge](/sdks/community/nightforge.md) Compile, deploy, and operate Compact contracts from one CLI with Nightforge, a community development environment for Midnight. --- ## [Common SDK integration issues](/sdks/troubleshoot.md) Troubleshoot common issues when building on Midnight Network. --- ## [Wallet reference](/sdks/community/wallets/community-wallets-reference.md) Reference for Midnight Network community wallets: the functionality matrix, troubleshooting and error codes, a security checklist, ecosystem, and glossary. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- ## [Midnight Live View](/sdks/community/midnight-live-view.md) A real-time terminal dashboard and persistent block monitor for Midnight validator nodes, inspired by CNTool's gLiveView. --- ## [Edda Midnight starter template](/sdks/community/edda-midnight-starter.md) A full-stack starter template for building DApps on Midnight with a React frontend, Compact smart contract, CLI tooling, and educational materials. --- ## [Edda Midnight starter template](/sdks/community/edda-midnight-starter.md) A full-stack starter template for building DApps on Midnight with a React frontend, Compact smart contract, CLI tooling, and educational materials. --- ## [Develop with the wallet CLI and MCP](/sdks/community/wallets/community-wallets-cli-mcp.md) Develop and test on the Midnight Network without a browser wallet using the wallet CLI, and drive a self-custody wallet from AI agents over MCP. --- ## [Community projects](/sdks/community.md) Third-party libraries and tools built on Midnight by the wider community. --- ## [OpenZeppelin contracts for Compact](/sdks/community/openzeppelin-compact-contracts.md) A library of token standards, access control, and security primitives for Compact smart contracts, modeled on OpenZeppelin's Solidity contracts. --- ## [Nightforge](/sdks/community/nightforge.md) Compile, deploy, and operate Compact contracts from one CLI with Nightforge, a community development environment for Midnight. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Wallet reference](/sdks/community/wallets/community-wallets-reference.md) Reference for Midnight Network community wallets: the functionality matrix, troubleshooting and error codes, a security checklist, ecosystem, and glossary. --- ## [Midnight Explorer](/sdks/community/midnight-explorer.md) Explore blocks, transactions, addresses, and contracts on the Midnight Network with Midnight Explorer, a community-built web explorer. --- ## [Midnight Live View](/sdks/community/midnight-live-view.md) A real-time terminal dashboard and persistent block monitor for Midnight validator nodes, inspired by CNTool's gLiveView. --- ## [Midnight wallet SDK](/sdks/official/wallet-developer-guide.md) Developer guide for the Midnight Wallet SDK, covering unshielded, shielded, and DUST wallet operations. --- ## [Community wallets](/sdks/community/wallets/community-wallets-overview.md) Choose a community wallet on the Midnight Network using a custody and interface model, with per-wallet profiles for Lace, 1AM, Kuira, and more. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight SDKs Build privacy-preserving decentralized applications with Midnight's comprehensive SDK ecosystem. Whether you're creating smart contracts, wallets, or full-stack DApps, we have the tools you need. *** ## 🚀 Official SDKs[​](#-official-sdks "Direct link to 🚀 Official SDKs") ### Midnight.js Complete TypeScript implementation of the Midnight Network. Includes contract interaction, wallet management, and zero-knowledge proof generation. [Documentation](/sdks/official/midnight-js.md)[GitHub](https://github.com/midnightntwrk/midnight-js) ### Wallet SDK SDK for building custom wallets and managing private keys, transactions, and state. Provides fine-grained control over wallet operations. [Documentation](/sdks/official/wallet-developer-guide.md)[GitHub](https://github.com/midnightntwrk/midnight-wallet) *** ## 🌐 Community[​](#-community "Direct link to 🌐 Community") Libraries and tools built by the Midnight developer community. These projects are not maintained or endorsed by the Midnight Foundation - see the [community section](/sdks/community.md) for eligibility criteria and disclaimers. ### OpenZeppelin Contracts for Compact Token standards, access-control patterns, and security primitives for Compact. Alpha release - not audited. [Documentation](/sdks/community/openzeppelin-compact-contracts.md)[GitHub](https://github.com/OpenZeppelin/compact-contracts) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Community projects Extend your Midnight DApp with tools and libraries built by the wider community. These projects fill gaps that mainstream development hits early, and their respective authors maintain them outside the Midnight Foundation. Community-maintained - not officially supported Their respective authors maintain the projects listed here, not the Midnight Foundation. These projects might not have undergone auditing and may target compiler or runtime versions that differ from the latest Midnight release. Verify compatibility against the [compatibility matrix](/relnotes/support-matrix.md) before integrating. File issues with each project's maintainers directly. *** ## 🌐 Featured projects[​](#-featured-projects "Direct link to 🌐 Featured projects") ### OpenZeppelin Contracts for Compact Token standards, access control, and security primitives written in Compact. Modeled on OpenZeppelin's Solidity library. Currently experimental and unaudited. [Documentation](/sdks/community/openzeppelin-compact-contracts.md)[GitHub](https://github.com/OpenZeppelin/compact-contracts) ### Midnight Live View Real-time terminal dashboard and persistent block monitor for Midnight validator nodes. Displays node health, block production, peers, and system metrics. [Documentation](/sdks/community/midnight-live-view.md)[GitHub](https://github.com/Midnight-Scripts/Midnight-Live-View) ### Midnight Explorer Open-source web explorer for blocks, transactions, addresses, contracts, and pool analytics on Midnight. Maintained by TexLabs, with a hosted Preprod instance. [Documentation](/sdks/community/midnight-explorer.md)[GitHub](https://github.com/Tech-Expansion/midnight-explorer-web) ### Nightforge CLI development environment that compiles, deploys, and operates Compact contracts. Bundles project scaffolding, wallet tools, and proof server orchestration. [Documentation](/sdks/community/nightforge.md)[GitHub](https://github.com/cadalt0/NIGHTFORGE) ### Edda Midnight starter template Full-stack monorepo with a React frontend, Compact smart contract, CLI, and educational materials. Clone, build, and deploy to Vercel. [Documentation](/sdks/community/edda-midnight-starter.md)[GitHub](https://github.com/eddalabs/midnight-starter-template) ### Midnames Name service and Compact playground for Midnight. Register human-readable names for addresses and compile Compact code in the browser. [Documentation](/sdks/community/midnames.md) *** ## Eligibility[​](#eligibility "Direct link to Eligibility") To qualify for listing, a project should be open source under a recognizable license, actively maintained, and have a public issue tracker. It should also target a documented Compact compiler or runtime version range. Audit status is not required, but each project page surfaces it prominently. ## Suggest a project[​](#suggest-a-project "Direct link to Suggest a project") Maintain or use a project that fits? [Open an issue](https://github.com/midnightntwrk/midnight-docs/issues/new?template=new-feature.yml) on the docs repository with the project name, repository link, brief description, and current Compact / runtime compatibility. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight agent skills AI coding assistants like Claude, GitHub Copilot, and Cursor don't have Compact in their training data. When you ask them to write a Compact contract, they generate plausible-looking code that fails to compile. `midnight_agent_skills` is a set of four modular agent skills that fix this. Install them once, and your AI assistant has accurate knowledge of Compact syntax, Midnight SDK, network configuration, and common gotchas sourced from the developer community. ## Install[​](#install "Direct link to Install") Install all skills at once: ``` npx skills add https://github.com/mzf11125/midnight_agent_skills ``` Or install individual skills: ``` npx skills add https://github.com/mzf11125/midnight_agent_skills --skill midnight-compact npx skills add https://github.com/mzf11125/midnight_agent_skills --skill midnight-api ``` ## Available skills[​](#available-skills "Direct link to Available skills") The following four skills can be installed individually or all at once. Each skill targets a specific area of Midnight development. ### midnight-concepts[​](#midnight-concepts "Direct link to midnight-concepts") Foundational knowledge about Midnight's zero-knowledge architecture: the Kachina protocol, DUST/NIGHT tokenomics, the dual-state model (public ledger vs private state), and ZK proof fundamentals. ### midnight-compact[​](#midnight-compact "Direct link to midnight-compact") Complete guide to the Compact language (v0.22+): * Circuit syntax and the constraint model * Ledger operations: `Counter`, `Map`, `Set`, `MerkleTree` * The `disclose()` mechanism and witness protection * Common syntax gotchas (`.read()` not `.value()`, enum access with `.` not `::`, witness functions have no body) * On-chain design patterns from production experience ### midnight-api[​](#midnight-api "Direct link to midnight-api") SDK integration for building DApps: * Wallet connection (Lace, 1AM) via `midnight-wallet-kit` * Contract deployment and interaction * SDK compatibility matrix and known silent failures * Preprod network configuration and troubleshooting ### midnight-network[​](#midnight-network "Direct link to midnight-network") Network infrastructure: * Proof server setup via Docker * Indexer configuration * Node deployment ## What skills cover[​](#what-skills-cover "Direct link to What skills cover") The skills are built from official Midnight documentation plus community articles from the Midnight Aliit Fellowship. They include: ### Mental model corrections for developers coming from EVM[​](#mental-model-corrections-for-developers-coming-from-evm "Direct link to Mental model corrections for developers coming from EVM") * Circuits declare constraints, they don't execute. `assert` is a constraint declaration, not a runtime guard. * `disclose()` is a compile-time annotation, not encryption. The compiler tracks witness data through arithmetic and rejects undeclared disclosures. * Block limits are hard limits, not gas costs. `BlockLimitExceeded` means the transaction cannot execute at all. ### On-chain design patterns[​](#on-chain-design-patterns "Direct link to On-chain design patterns") * Flat maps over struct maps (struct reads pull every field into the circuit) * Off-chain computation with Merkle root verification * Minimal on-chain state ### Common syntax gotchas[​](#common-syntax-gotchas "Direct link to Common syntax gotchas") The following examples show frequently misused syntax and their correct equivalents. ``` // WRONG const val = counter.value(); if (state == GameState::playing) { ... } witness get_key(): Bytes<32> { return local_key(); } // CORRECT const val = counter.read(); if (state == GameState.playing) { ... } witness local_key(): Bytes<32>; ``` ## Source[​](#source "Direct link to Source") * Repository: * Install via npm: `npx skills add https://github.com/mzf11125/midnight_agent_skills` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Edda Midnight starter template [Edda Midnight Starter Template](https://github.com/eddalabs/midnight-starter-template) is a full-stack monorepo for building DApps on the Midnight Network. It ships a working counter application with a Compact smart contract, a React (Vite) frontend, and a CLI - ready to clone, build, and deploy to Vercel. A live demo runs at [counter.nebula.builders](https://counter.nebula.builders). The project includes educational materials with video walkthroughs in English, Spanish, and Portuguese, making it a practical entry point for developers new to Midnight. The Edda Labs maintainers built this as a fork of [MeshJS/midnight-starter-template](https://github.com/MeshJS/midnight-starter-template), adding the Apache-2.0 license, deployment automation, and the educational-material directory. Community-maintained - not audited [Edda Labs](https://github.com/eddalabs) maintains this template, not the Midnight Foundation. It has not been audited. The smart contract is a minimal counter example intended for learning - evaluate any production use independently. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before using the template, ensure that you have: * [Node.js v22+](https://nodejs.org/) installed. * [pnpm v10+](https://pnpm.io/installation) installed. * [Docker](https://docs.docker.com/desktop/) running (for the proof server and standalone network). * [Git Large File Storage (LFS)](https://git-lfs.com/) installed - required for zero-knowledge proof artifacts (`.prover`, `.verifier`, `.bzkir`, `.zkir` files). * The [Compact developer tools](/getting-started/installation.md) installed and updated to `0.30.0`. * The [Lace wallet](https://chromewebstore.google.com/detail/lace/gafhhkghbfjjkeiendhlofajokpaflmk) browser extension configured for the Preview network. ## Compatibility[​](#compatibility "Direct link to Compatibility") This template targets specific Compact compiler, runtime, and tooling versions. Verify these against your local environment before building. | Component | Version | Notes | | ------------------ | ------------------------------------- | -------------------------------------------------------------------------- | | Compact compiler | `0.31.0` | Set via `compact update +0.31.0` | | Compact language | `>= 0.23` | Per `pragma` in the contract source | | Node.js | 22+ | Pinned in `.node-version` and `engines.node` | | pnpm | `10.14.0` | Pinned via `packageManager` in `package.json` | | Build orchestrator | Turborepo | Top-level scripts dispatch through `turbo run` | | Networks | undeployed, Preview, Preprod, Mainnet | Standalone undeployed network runs via Docker | | License | Apache-2.0 | (Upstream Mesh template carries no license; Edda's fork added Apache-2.0.) | ## Monorepo structure[​](#monorepo-structure "Direct link to Monorepo structure") The template organizes code into three workspace packages: | Package | Purpose | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `counter-contract` | Compact smart contract with a single `increment` circuit that advances a public `round` counter. Compiles to TypeScript bindings and ZK proof artifacts. | | `counter-cli` | CLI tool for deploying and interacting with the contract from the terminal. Supports all three networks. | | `frontend-vite-react` | React 19 + Vite frontend with Lace wallet integration, TailwindCSS styling, and TanStack Router. Connects to the deployed contract and displays counter state. | ## Installation[​](#installation "Direct link to Installation") Clone the repository: ``` git clone https://github.com/eddalabs/midnight-starter-template.git cd midnight-starter-template ``` Download the zero-knowledge proof artifacts via Git Large File Storage (LFS): ``` git lfs install git lfs pull ``` Update the Compact Toolchain to the version the template targets: ``` compact update +0.31.0 ``` Install dependencies and build all workspace packages: ``` pnpm install pnpm build ``` Both `counter-cli/` and `frontend-vite-react/` ship a `.env_template` file. Copy each to `.env` and fill in the values before running locally. Git LFS required The repository stores zero-knowledge proof artifacts (prover keys, verifier keys, ZKIR files) via Git LFS. Without `git lfs install` and `git lfs pull`, these files appear as text pointers instead of binary data, and contract deployment fails with "mismatched verifier keys" errors. ## Run locally[​](#run-locally "Direct link to Run locally") Start the frontend against the Preview network: ``` pnpm dev:frontend ``` For a fully local setup with no external network dependency, start the standalone network first: ``` pnpm setup-standalone pnpm dev:frontend ``` The standalone network runs Midnight node, indexer, and proof server containers in Docker. ## Testing[​](#testing "Direct link to Testing") The CLI ships Vitest-based test suites that run the contract end-to-end on each network: ``` pnpm --filter @eddalabs/counter-cli test-undeployed pnpm --filter @eddalabs/counter-cli test-preview pnpm --filter @eddalabs/counter-cli test-preprod ``` These scripts spin up the relevant infrastructure (containers for `undeployed`, faucet calls for `preview` / `preprod`), deploy the contract, and assert on circuit behavior. They serve as a useful reference for setting up your own contract test harness. ## The smart contract[​](#the-smart-contract "Direct link to The smart contract") The contract is a minimal counter with a single exported circuit: ``` pragma language_version >= 0.23; import CompactStandardLibrary; export ledger round: Counter; export circuit increment(): [] { round.increment(1); } ``` The contract is deliberately minimal - the template's value is the full-stack scaffolding around it (wallet connection, provider wiring, deployment pipeline), not the contract logic. Replace it with your own contract and the surrounding infrastructure adapts. ## Deploy to Vercel[​](#deploy-to-vercel "Direct link to Deploy to Vercel") The Edda Labs team documents the full deployment procedure in their [DEPLOYMENT\_PROCEDURE.md](https://github.com/eddalabs/midnight-starter-template/blob/main/DEPLOYMENT_PROCEDURE.md). The key steps: 1. Enable **Git LFS** in your Vercel project settings before the first build. 2. Set the build command to `npm run build-production` (the script is workspace-aware and pulls LFS artifacts before building). 3. Set the output directory to `frontend-vite-react/dist`. 4. Add `VITE_CONTRACT_ADDRESS` as an environment variable with your deployed contract address. Git LFS in Vercel If you deploy without enabling Git LFS in Vercel's settings, then the build completes but the DApp fails at runtime. The proof artifacts are LFS pointers instead of binary files. Enable LFS first, then redeploy without cache. ## Educational materials[​](#educational-materials "Direct link to Educational materials") The repository includes an `educational-material/` directory with structured session guides covering: * zero-knowledge proofs and privacy-enhanced DApps * devnet, Preview, and Testnet environments * Video walkthroughs on the [Edda Labs YouTube channel](https://www.youtube.com/@eddalabs) * Available in English, Spanish, and Portuguese ## Resources[​](#resources "Direct link to Resources") * **[Project repository](https://github.com/eddalabs/midnight-starter-template)**: Source, README, and contributor guide. * **[Live demo](https://counter.nebula.builders)**: The deployed counter DApp running on the Preview environment. * **[Deployment procedure](https://github.com/eddalabs/midnight-starter-template/blob/main/DEPLOYMENT_PROCEDURE.md)**: Step-by-step Vercel deployment, including the Git LFS toggle. * **[Educational material](https://github.com/eddalabs/midnight-starter-template/tree/main/educational-material)**: Session guides for devnet, Preview, and Testnet workflows. * **[Edda Labs](https://www.eddalabs.io)**: The maintainer organization. Sibling repo: [`eddalabs/midnight-contracts`](https://github.com/eddalabs/midnight-contracts). * **[Upstream template (MeshJS)](https://github.com/MeshJS/midnight-starter-template)**: The original starter that Edda's fork builds on. ## Report issues[​](#report-issues "Direct link to Report issues") For issues with the template, file on [Edda Labs' tracker](https://github.com/eddalabs/midnight-starter-template/issues). For issues with this documentation page, file on the [Midnight docs repository](https://github.com/midnightntwrk/midnight-docs/issues). --- # Midnames > For the complete documentation index, see [llms.txt](/llms.txt) Midnames has a suite of tools and services to help you interact with the Midnight Network. This includes a name service that allows you to register human-readable names for Midnight addresses, and a playground where you can write and compile Compact code. ## Compact Playground[​](#compact-playground "Direct link to Compact Playground") You can access the playground at [playground.midnames.com](https://playground.midnames.com/). There, you can write and compile Compact code, and interact with it using the integrated Simulator. You'll find the examples from the [Compact documentation](https://docs.midnight.com/compact) in the "Examples" section of the playground. You can also create your own projects and share them with others. ### Compilation[​](#compilation "Direct link to Compilation") You can compile your Compact code using either a remote or local compiler. The remote compiler sends code to a server. The local compiler uses a WASM-based version that runs in your browser, but has some limitations, such as failing to generate proper error messages. Local compilation The local compiler is slow and may take a while to compile larger contracts. The errors it generates are not helpful. ## Name service[​](#name-service "Direct link to Name service") Midnames also runs a name service at [midnight.domains](https://midnight.domains/). The name service allows you to register human-readable names that resolve to Midnight addresses, making it easier to interact with contracts and addresses on the Midnight Network. You can find a guide on how to buy a domain at [docs.midnight.domains](https://docs.midnight.domains/guides/buy_domain/). ### SDK[​](#sdk "Direct link to SDK") The midnight.domains SDK is available as an npm package. You can install it using: ``` npm install @midnames/sdk ``` The SDK provides functions to interact with the name service, such as registering a name, resolving a name to an address, and adding metadata to your domains. You can find the documentation for the SDK at [docs.midnight.domains](https://docs.midnight.domains/reference/resolve/). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Explorer [Midnight Explorer](https://github.com/Tech-Expansion/midnight-explorer-web) is an open-source blockchain explorer for the Midnight Network. It provides a web interface to search, trace, and analyze on-chain activity, including transactions, blocks, smart contracts, and liquidity pools. [TexLabs](https://texlabs.org) maintains the project under the [Tech-Expansion](https://github.com/Tech-Expansion) GitHub organization and hosts a public instance at [midnightexplorer.com](https://www.midnightexplorer.com). Community-maintained - not audited TexLabs maintains this project, not the Midnight Foundation. It has not been audited. Evaluate it independently before relying on its data for production decisions. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before running the explorer locally, ensure that you have: * Node.js 20 or later. * npm. * Docker, if you plan to use the containerized deployment. ## Compatibility[​](#compatibility "Direct link to Compatibility") | Component | Version | Notes | | ----------------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------- | | Explorer version | `0.1.0` | No formal releases; code accessed from the `main` branch. | | `@midnight-ntwrk/compact-runtime` | `^0.9.0` | Declared in `package.json`. | | `@midnight-ntwrk/midnight-js-types` | `^2.0.2` | Declared in `package.json`. | | `@midnight-ntwrk/zswap` | `^4.0.0` | Declared in `package.json`. | | Networks | Preview, Preprod, Mainnet Lite | Selected from the header network switcher. The public instance serves Preprod by default. | | License | Apache 2.0 | | ## Features[​](#features "Direct link to Features") The explorer provides the following views: * **Universal search**: look up blocks, transactions, addresses, and contracts by hash or ID. * **Block explorer**: browse the latest blocks with full block details and transaction lists. * **Transaction viewer**: inspect transaction data, inputs, outputs, and contract interactions. * **Address explorer**: view address history, balances, and associated contracts. * **Smart contracts**: browse deployed contracts and their on-chain state. * **Pool analytics**: track liquidity pool metrics and activity. * **Network charts**: visualize on-chain statistics and trends over time. * **Live network stats**: monitor the current epoch, slot, total blocks, transactions, and average block time. * **Network switcher**: switch between Midnight environments from the header. ## Run the explorer locally[​](#run-the-explorer-locally "Direct link to Run the explorer locally") Install the dependencies and start the development server: ``` npm install npm run dev ``` The `dev` script starts Next.js on port `8081`. Open `http://localhost:8081` in your browser. The project uses Next.js 15 (App Router), TypeScript, Tailwind CSS v4, Radix UI, TanStack Query, Recharts, and PostgreSQL. ## Deployment[​](#deployment "Direct link to Deployment") The repository ships a `Dockerfile` and an Nginx compose file (`docker-compose.nginx.yml`) for containerized hosting. The README documents HTTPS setup with Let's Encrypt, certificate auto-renewal, and a blue-green strategy for zero-downtime updates. See the [project README](https://github.com/Tech-Expansion/midnight-explorer-web#readme) for the full deployment commands. ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Project repository](https://github.com/Tech-Expansion/midnight-explorer-web): source, README, and deployment guide. * [Public explorer instance](https://www.midnightexplorer.com): hosted by TexLabs and serving Preprod by default. ## Report issues[​](#report-issues "Direct link to Report issues") For issues with the explorer, file on [TexLabs' tracker](https://github.com/Tech-Expansion/midnight-explorer-web/issues). For issues with this documentation page, file on the [Midnight docs repository](https://github.com/midnightntwrk/midnight-docs/issues). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Live View [Midnight Live View](https://github.com/Midnight-Scripts/Midnight-Live-View) is a terminal-based monitoring dashboard for Midnight validator nodes. It displays node health, block production, peer connections, and system resources in real time, refreshing every second. The project consists of two shell scripts: * **`LiveView.sh`**: a real-time dashboard inspired by [CNTool's gLiveView](https://cardano-community.github.io/guild-operators/Scripts/gliveview/) that shows node version, uptime, block data, peer count, and system metrics. * **`simple_block_monitor.sh`**: a background process that tracks blocks persistently by tailing container logs and writing to a local JSON file. Block data survives Docker restarts. Community-maintained, no license [Midnight-Scripts](https://github.com/Midnight-Scripts) maintains this project, not the Midnight Foundation. The repository does not currently specify a license. The tool has not been audited. Evaluate independently before relying on it in any environment. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before using the tool, ensure that you have: * A running Midnight validator node (Docker container named `midnight` by default). * `jq` and `curl` installed (`sudo apt install jq curl` on Ubuntu/Debian, `brew install jq curl` on macOS). * Docker installed and running. * The `partner-chains-public-keys.json` file in the same directory as `LiveView.sh`. ## Compatibility[​](#compatibility "Direct link to Compatibility") | Component | Version | Notes | | ------------------- | ------------ | -------------------------------------------------------------- | | Tool version | `0.2.1` | No formal releases; code accessed from `main` branch. | | Tested node version | `0.12.0` | Tested against builds `cab67f3b` and `29935d2f`. | | Network | Testnet | No Mainnet support documented. | | Platforms | Linux, macOS | Install commands reference Ubuntu/Debian and macOS (Homebrew). | ## Node configuration[​](#node-configuration "Direct link to Node configuration") The dashboard reads data from your node's RPC endpoint. You need to modify the `APPEND_ARGS` variable in your `.envrc` file to expose the RPC interface. Security: unsafe RPC methods The configuration below enables `--unsafe-rpc-external` and `--rpc-methods=Unsafe`, which expose RPC methods that are not safe for public access. On a single-server setup, this is acceptable for local monitoring. On a multi-server setup, restrict RPC access to trusted IPs only. For a single-server setup, add the following to your `APPEND_ARGS`: ``` --unsafe-rpc-external --rpc-methods=Unsafe --rpc-cors all ``` For two-server setups, see the [project README](https://github.com/Midnight-Scripts/Midnight-Live-View#readme) for the full configuration. ## Installation[​](#installation "Direct link to Installation") Download both scripts and make them executable: ``` wget -O ./LiveView.sh https://raw.githubusercontent.com/Midnight-Scripts/Midnight-Live-View/refs/heads/main/LiveView.sh wget -O ./simple_block_monitor.sh https://raw.githubusercontent.com/Midnight-Scripts/Midnight-Live-View/refs/heads/main/simple_block_monitor.sh chmod +x LiveView.sh simple_block_monitor.sh ``` ## Run the dashboard[​](#run-the-dashboard "Direct link to Run the dashboard") For basic dashboard-only monitoring: ``` ./LiveView.sh ``` For persistent block tracking (recommended), start the block monitor first: ``` ./simple_block_monitor.sh start ./LiveView.sh ``` The block monitor runs in the background and writes to `all_blocks.json`. Manage it with `start`, `stop`, `status`, or `run` (interactive mode). ## Dashboard features[​](#dashboard-features "Direct link to Dashboard features") The dashboard displays the following information, refreshed every second: * **Node info**: version, uptime, and container start time. * **Security**: node key (masked), port, and key status. * **Registration**: current registration status. * **Block data**: historic blocks (total since monitoring began), blocks produced (since Docker restart), latest and finalized block numbers, and sync status. * **Network**: peer count with interactive peer details (press `p`). * **System**: CPU, memory, and disk usage. Press `q` to quit, `p` to toggle peer details. ## Configuration[​](#configuration "Direct link to Configuration") You can override defaults with environment variables: | Variable | Default | Purpose | | ---------------- | ---------- | --------------------------------------------- | | `CONTAINER_NAME` | `midnight` | Docker container name for the validator node. | | `PORT` | `9944` | RPC port the dashboard connects to. | | `USE_DOCKER` | `true` | Set to `false` for non-Docker node setups. | ## Files created at runtime[​](#files-created-at-runtime "Direct link to Files created at runtime") The block monitor creates three files in its working directory: | File | Purpose | | -------------------- | ---------------------------------------------------- | | `all_blocks.json` | Persistent block database with duplicate prevention. | | `block_monitor.log` | Monitor activity log. | | `.block_monitor.pid` | Process tracking file. | ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Project repository](https://github.com/Midnight-Scripts/Midnight-Live-View): source, README, and configuration guide. * [CNTool gLiveView](https://cardano-community.github.io/guild-operators/Scripts/gliveview/): the Cardano monitoring tool that inspired this dashboard. ## Report issues[​](#report-issues "Direct link to Report issues") For issues with the tool, file on [Midnight-Scripts' tracker](https://github.com/Midnight-Scripts/Midnight-Live-View/issues). For issues with this documentation page, file on the [Midnight docs repository](https://github.com/midnightntwrk/midnight-docs/issues). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Nightforge [Nightforge](https://github.com/cadalt0/NIGHTFORGE) is a development environment for compiling, deploying, and operating Compact contracts on the Midnight Network. It bundles project scaffolding, wallet lifecycle tools, proof server orchestration, and deployment into a single CLI. [cadalt0](https://github.com/cadalt0) maintains the project and publishes it on npm as [`nightforge`](https://www.npmjs.com/package/nightforge). Community-maintained - not audited [cadalt0](https://github.com/cadalt0) maintains this project, not the Midnight Foundation. It has not been audited. The npm package declares the MIT license, while the repository's `LICENSE` file contains the Apache 2.0 text. Evaluate the tool independently before using it in production workflows. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before using Nightforge, ensure that you have: * Node.js and npm. * The [Compact developer tools](/getting-started/installation.md) installed and available on your `PATH`. The `compile` command invokes the `compact` CLI. * Docker, for running a local proof server with `nightforge proof-server`. * tNIGHT from the [Preprod faucet](https://faucet.preprod.midnight.network/) to fund deployments. ## Compatibility[​](#compatibility "Direct link to Compatibility") | Component | Version | Notes | | ------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | Nightforge | `1.0.0` | Latest npm release; GitHub release `v1.0.0`. | | Compact compiler | Not pinned | Nightforge calls the `compact` CLI installed on your system. | | Proof server image | `midnightntwrk/proof-server:7.0.0` | Default tag; override with `-v `. Check the [compatibility matrix](/relnotes/support-matrix.md) for current releases. | | Networks | Preprod (default), custom endpoints | Set with `--network` or `--remote`. | | License | MIT on npm | The repository `LICENSE` file contains the Apache 2.0 text. | ## Installation[​](#installation "Direct link to Installation") Install the package locally: ``` npm install nightforge ``` Run commands through `npx`: ``` npx nightforge --help ``` ## Quickstart[​](#quickstart "Direct link to Quickstart") ``` # 1) Create a project npx nightforge init my-midnight-app cd my-midnight-app # 2) Compile the contract npx nightforge compile # 3) Start the wallet sync service npx nightforge sync # 4) In another terminal, check the synced balance npx nightforge wallet balance # 5) Deploy using the synced state npx nightforge deploy example --network preprod ``` The `init` command scaffolds `midnight.config.js`, `contracts/example.compact`, a `scripts/` directory, and walletsync configuration files. Pass `-t` to choose a template: `default`, `token`, or `nft`. ## Auto mode[​](#auto-mode "Direct link to Auto mode") `deploy --auto` orchestrates the full flow. It creates a wallet if one is missing, waits for tNIGHT funding, registers for DUST, waits for proof server readiness, and then deploys. ``` npx nightforge deploy --auto --network preprod ``` Point the deployment at a remote proof server instead of a local one: ``` npx nightforge deploy example --auto --remote http://YOUR-PROOF-HOST:6300 ``` ## Commands[​](#commands "Direct link to Commands") | Command | Purpose | | -------------------------------- | ---------------------------------------------------- | | `nightforge init ` | Create a project scaffold. | | `nightforge compile` | Compile Compact contracts into `contracts/managed/`. | | `nightforge sync --init` | Create walletsync configuration files. | | `nightforge sync` | Start the walletsync server (default port `8787`). | | `nightforge wallet create` | Create a wallet. | | `nightforge wallet restore` | Restore a wallet from a seed. | | `nightforge wallet balance` | Check the balance of the active wallet. | | `nightforge wallet dust` | Register tNIGHT for DUST generation. | | `nightforge proof-server` | Start a local proof server (shorthand: `ps`). | | `nightforge deploy ` | Deploy a compiled contract. | | `nightforge clean` | Remove build artifacts. | The [command guides](https://github.com/cadalt0/NIGHTFORGE/tree/main/Docs) in the repository cover every flag in detail. ## Runtime state files[​](#runtime-state-files "Direct link to Runtime state files") Nightforge writes local state files in your project root: | File | Purpose | | -------------------------- | -------------------------------------------- | | `wallet.json` | Persisted wallet seed, address, and network. | | `proof-server-status.json` | Proof server running and readiness state. | | `deployment.json` | Deployment metadata output. | Nightforge stores wallets created with `nightforge wallet` outside the project in `~/.nightforge/wallets/`, one JSON file per wallet with owner-only file permissions. Wallet files contain seeds `wallet.json` and the files under `~/.nightforge/wallets/` hold wallet seeds. Never commit them to version control, and use separate wallets for separate environments. ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Project repository](https://github.com/cadalt0/NIGHTFORGE): source, command guides, and troubleshooting. * [`nightforge` on npm](https://www.npmjs.com/package/nightforge): the published package. * [Project site](https://midnight-forge-pearl.vercel.app/): hosted landing page. * [Changelog](https://github.com/cadalt0/NIGHTFORGE/blob/main/CHANGELOG.md): version history. ## Report issues[​](#report-issues "Direct link to Report issues") For issues with Nightforge, file on [cadalt0's tracker](https://github.com/cadalt0/NIGHTFORGE/issues). For issues with this documentation page, file on the [Midnight docs repository](https://github.com/midnightntwrk/midnight-docs/issues). --- > For the complete documentation index, see [llms.txt](/llms.txt) # OpenZeppelin contracts for Compact [OpenZeppelin Contracts for Compact](https://github.com/OpenZeppelin/compact-contracts) is a library of reusable smart contract building blocks written in Compact for Midnight. It mirrors the structure of OpenZeppelin's Solidity contracts library, providing token standards, access-control patterns, and security primitives that compose into custom contracts. The library is modular: instead of inheriting a base contract, you import individual modules into your own `.compact` source with a prefix and call their circuits as building blocks. Experimental - alpha, not audited The library is currently at version `v0.0.1-alpha.1`. Per the project's own README, it has never been audited or thoroughly reviewed for security vulnerabilities, and the maintainers explicitly state: **DO NOT USE IT IN PRODUCTION.** Use these contracts for prototyping, learning, and Testnet development only. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before using the library, ensure that you have: * The [Compact developer tools](/getting-started/installation.md) installed. * [Node.js](https://nodejs.org/) and [yarn](https://yarnpkg.com/getting-started/install) available. * A working understanding of [Compact module imports](/compact/reference/compact-reference.md) and the `prefix` syntax. ## Compatibility[​](#compatibility "Direct link to Compatibility") The table below lists the Compact compiler and runtime versions the library targets. Verify these against your local toolchain before integrating. | Component | Version | Notes | | ---------------- | ----------------------------- | ------------------------------------------------------------------------------ | | Library version | `v0.0.1-alpha.1` | Alpha; rapid iteration expected. | | Compact compiler | `0.29.0` | Pinned by the library's CI badge. | | Compact language | `>= 0.21.0` | Per `pragma` in every source file. | | Token amounts | `Uint<128>` (not `Uint<256>`) | Midnight encoding limit; `Uint<256>` is not supported by the Compact compiler. | | Midnight Network | Preprod and Preview only | Not for Mainnet. | Compiler version mismatch OpenZeppelin's library currently pins compiler `0.29.0`, while the official Midnight Toolchain has shipped a newer release. The pragma `>= 0.21.0` keeps source-level compatibility, but verify your local `compact compile --version` before reporting issues. ## Modules[​](#modules "Direct link to Modules") The library organizes its modules into four families. Most modules import `Initializable` (one-time init guard) and `Utils` (zero-address and Either helpers) for composition. ### Access control · `src/access/`[​](#access-control--srcaccess "Direct link to access-control--srcaccess") These modules control who can call specific circuits in your contract. They are listed from simplest to most complex: single-owner first, then role-based, then their privacy-preserving variants. | Module | Purpose | OpenZeppelin docs | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Ownable` | Single-owner authorization. Stores the owner as `Either`. Supports ownership transfer, renunciation, and safe/unsafe variants for contract-address owners. | [Guide](https://docs.openzeppelin.com/contracts-compact/ownable) · [API](https://docs.openzeppelin.com/contracts-compact/api/ownable) | | `AccessControl` | Role-based authorization with admin hierarchy. Roles are `Bytes<32>` identifiers. Each role has a configurable admin role that controls grants and revocations. | [Guide](https://docs.openzeppelin.com/contracts-compact/accessControl) · [API](https://docs.openzeppelin.com/contracts-compact/api/accessControl) | | `ShieldedAccessControl` | *Privacy-preserving* role-based access control. Stores role commitments in a `MerkleTree<20>` and revokes via nullifiers, so role membership can be proven in zero knowledge. | *Not yet on OpenZeppelin's docs site - see [source](https://github.com/OpenZeppelin/compact-contracts/blob/main/contracts/src/access/ShieldedAccessControl.compact).* | | `ZOwnablePK` | *Privacy-preserving* single-owner authorization. Stores the owner as a commitment hash instead of a public key, so on-chain data does not reveal who the owner is. | Documented alongside [Ownable](https://docs.openzeppelin.com/contracts-compact/ownable) | ### Security · `src/security/`[​](#security--srcsecurity "Direct link to security--srcsecurity") These modules enforce lifecycle and operational guards on your contract. | Module | Purpose | OpenZeppelin docs | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `Initializable` | One-time initialization guard. Prevents a contract from being initialized more than once. Most other modules depend on this. | [Guide](https://docs.openzeppelin.com/contracts-compact/security) · [API](https://docs.openzeppelin.com/contracts-compact/api/security) | | `Pausable` | Emergency pause switch. Gates circuit execution behind `assertNotPaused()`. Wrap `_pause()` and `_unpause()` in your own authorization logic. | [Guide](https://docs.openzeppelin.com/contracts-compact/security) · [API](https://docs.openzeppelin.com/contracts-compact/api/security) | ### Tokens · `src/token/`[​](#tokens--srctoken "Direct link to tokens--srctoken") These modules implement standard token interfaces adapted for Compact. | Module | Purpose | OpenZeppelin docs | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `FungibleToken` | ERC-20-style fungible token. Supports `transfer`, `approve`, `transferFrom`, `mint`, and `burn`. Balances use `Uint<128>` (not `Uint<256>` - see [Compatibility](#compatibility)). Includes safe and unsafe transfer variants. | [Guide](https://docs.openzeppelin.com/contracts-compact/fungibleToken) · [API](https://docs.openzeppelin.com/contracts-compact/api/fungibleToken) | | `NonFungibleToken` | ERC-721-style non-fungible token. Tracks ownership, approvals, operator approvals, and token URIs. Token IDs use `Uint<128>`. | [Guide](https://docs.openzeppelin.com/contracts-compact/nonFungibleToken) · [API](https://docs.openzeppelin.com/contracts-compact/api/nonFungibleToken) | | `MultiToken` | ERC-1155-style multi-token. Manages multiple token types in a single contract. Does not support batched operations (Compact lacks dynamic arrays). | [Guide](https://docs.openzeppelin.com/contracts-compact/multitoken) · [API](https://docs.openzeppelin.com/contracts-compact/api/multitoken) | ### Utilities · `src/utils/`[​](#utilities--srcutils "Direct link to utilities--srcutils") Helper functions for type safety and input validation. | Module | Purpose | OpenZeppelin docs | | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `Utils` | Pure helpers for working with `Either` values. Includes zero-checks, equality checks, and `canonicalize` which prevents crafted-input attacks. | [Guide](https://docs.openzeppelin.com/contracts-compact/utils) · [API](https://docs.openzeppelin.com/contracts-compact/api/utils) | ## Installation[​](#installation "Direct link to Installation") The library currently ships as a Git submodule. The OpenZeppelin team plans to publish it on npm, as noted in the project's [README](https://github.com/OpenZeppelin/compact-contracts#readme). To add the library to a new project, clone it as a submodule and compile the contracts: ``` mkdir my-project && cd my-project git init git submodule add https://github.com/OpenZeppelin/compact-contracts.git nvm install yarn SKIP_ZK=true yarn compact ``` ## Compose a contract[​](#compose-a-contract "Direct link to Compose a contract") Import individual modules into your `.compact` source with a prefix, then call their circuits as building blocks. Note the `prefix Pausable_;` convention: the prefix itself ends in `_`. Calling the internally underscored `_pause` circuit becomes `Pausable__pause()` - the double underscore is intentional. ``` pragma language_version >= 0.21.0; import CompactStandardLibrary; import "./compact-contracts/node_modules/@openzeppelin/compact-contracts/src/access/Ownable" prefix Ownable_; import "./compact-contracts/node_modules/@openzeppelin/compact-contracts/src/security/Pausable" prefix Pausable_; import "./compact-contracts/node_modules/@openzeppelin/compact-contracts/src/token/FungibleToken" prefix FungibleToken_; constructor( _name: Opaque<"string">, _symbol: Opaque<"string">, _decimals: Uint<8>, _recipient: Either, _amount: Uint<128>, _initOwner: Either, ) { Ownable_initialize(_initOwner); FungibleToken_initialize(_name, _symbol, _decimals); FungibleToken__mint(_recipient, _amount); } export circuit transfer( to: Either, value: Uint<128>, ): Boolean { Pausable_assertNotPaused(); return FungibleToken_transfer(to, value); } export circuit pause(): [] { Ownable_assertOnlyOwner(); Pausable__pause(); } export circuit unpause(): [] { Ownable_assertOnlyOwner(); Pausable__unpause(); } ``` Why import through `node_modules` The OpenZeppelin team recommends importing through `compact-contracts/node_modules/@openzeppelin/compact-contracts/...` rather than the submodule path, to avoid state conflicts between shared dependencies. For details, see the project's [README](https://github.com/OpenZeppelin/compact-contracts#readme). ## Compile[​](#compile "Direct link to Compile") Run the Compact compiler to generate TypeScript bindings and ZK circuit artifacts from your contract: ``` compact compile MyContract.compact artifacts/MyContract ``` A successful compile lists each circuit with its proving-system size: ``` Compiling 3 circuits: circuit "pause" (k=10, rows=125) circuit "transfer"(k=11, rows=1180) circuit "unpause" (k=10, rows=121) Overall progress [====================] 3/3 ``` `k` is the domain size (the circuit is laid out on `2^k` rows), and `rows` is how many of those rows the circuit uses. Smaller circuits prove and verify faster - see OpenZeppelin's [ZK Circuits 101](https://docs.openzeppelin.com/contracts-compact/zkCircuits101) for a longer explanation. ## Patterns to know[​](#patterns-to-know "Direct link to Patterns to know") These patterns apply across the library and affect how you structure your contracts. * **Modular composition by delegation**: OpenZeppelin's [Module/Contract pattern](https://docs.openzeppelin.com/contracts-compact/extensibility) is the formal framing the library expects you to follow. Each module exports two kinds of circuits: *external* ones with no leading underscore (like `transfer`, `approve`) that are safe to expose as-is, and *public* ones with a leading underscore (like `_mint`, `_burn`) that serve as composable building blocks you wrap in your own contract logic. Internal helpers remain unexported. Your contract imports modules with a prefix and wires their circuits together; it should not call `initialize()` outside its constructor or re-export circuits raw. * **Composition through prefixes**: The `import ... prefix X_;` syntax namespaces each module so multiple modules can coexist in a single contract without identifier collisions. Circuits whose names start with `_` show up as `X__name` at the call site. * **Initialization is explicit**: Most modules import `Initializable` and require an explicit `initialize` call from your constructor. `Initializable_assertNotInitialized()` and `Initializable_assertInitialized()` enforce this. Calling other circuits before `initialize` fails at runtime. * **Contract-address recipients are restricted**: Compact does not yet support contract-to-contract calls, so every module's safe path (e.g., `Ownable.transferOwnership`, `AccessControl.grantRole`, `FungibleToken.transfer`) rejects `ContractAddress` recipients. Each module pairs the safe variant with `_unsafe*` circuits explicitly named to make the risk visible. The maintainers plan to deprecate the unsafe variants once Compact supports contract-to-contract calls. * **Caller authorization comes in two flavors**: `Ownable` and `AccessControl` use `ownPublicKey()` directly to check the caller. `ZOwnablePK` and `ShieldedAccessControl` use a witness-derived secret combined with hashing and instance salts to verify the caller via commitments - never exposing the public key on-chain. The privacy-preserving variants are the recommended choice when the contract should not reveal who its owners or role-holders are. * **`Either` is the canonical address type**: The `Utils.canonicalize` helper zeroes out the unused side of an `Either` to prevent crafted-input attacks where both sides carry data. ## Resources[​](#resources "Direct link to Resources") For more information, see the following links. * [Project repository](https://github.com/OpenZeppelin/compact-contracts) - README, source, and contribution guide. * [OpenZeppelin documentation site](https://docs.openzeppelin.com/contracts-compact/) - The project's own reference, organized as Overview, Learn, Modules, and API Reference. * [Module/Contract pattern](https://docs.openzeppelin.com/contracts-compact/extensibility) - Formal terminology for `internal`, `public`, and `external` circuits and the rules for safe composition. * [ZK Circuits 101](https://docs.openzeppelin.com/contracts-compact/zkCircuits101) - Short primer on what the `k=N, rows=N` numbers in the compile output mean and why circuit size matters. * [Building a fungible-token contract with OpenZeppelin and Compact](/blog/funbigle-token-contract-open-zeppelin) - Dev Diaries walkthrough of `FungibleToken`. ## Reporting issues[​](#reporting-issues "Direct link to Reporting issues") For issues with the library code, file on [OpenZeppelin's tracker](https://github.com/OpenZeppelin/compact-contracts/issues). For security disclosures, email `security@openzeppelin.com`. For issues with this documentation page, file on the [Midnight docs repository](https://github.com/midnightntwrk/midnight-docs/issues). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Develop with the wallet CLI and MCP How scripts, CI, and AI agents hold and move funds on Midnight without a browser extension, using the wallet CLI and its MCP server. To choose a wallet first, see the [overview](/sdks/community/wallets/community-wallets-overview.md). For browser DApp integration, see the [integration guide](/sdks/community/wallets/community-wallets-integration.md). ## Develop and test without a wallet[​](#develop-and-test-without-a-wallet "Direct link to Develop and test without a wallet") The wallet CLI exposes the same `ConnectedAPI` over a local WebSocket, so your DApp code paths run unchanged, and users later connect with any browser wallet. The CLI is self-custody (keys in `~/.midnight`, BIP-39/44, Lace-compatible) and network-agnostic, so one seed serves `undeployed`, `preprod`, and `preview`. | Group | Commands | | ------------------ | ---------------------------------------------------------------------------- | | Wallet | `wallet generate/list/use/info/remove`, `info`, `address`, `genesis-address` | | Transactions | `balance`, `transfer`, `airdrop`, `inspect-cost` | | DUST | `dust register`, `dust status` | | Local network | `localnet up/status/stop/down/clean` | | Config / connector | `config get/set/unset`, `cache clear`, `serve` | `midnight localnet up` orchestrates the full stack in Docker (node on `9944`, indexer on `8088`, proof server on `6300`), so you can deploy and transact with no faucet: ``` midnight localnet up # node + indexer + proof server (Docker) midnight wallet generate alice # self-custody key in ~/.midnight midnight config set network undeployed midnight airdrop 1000 # fund the active wallet (undeployed-only) midnight airdrop 1000 mn_addr_undeployed1... # ...or fund ANY address directly (v0.4.1, no seed import) midnight dust register # REQUIRED before transfers; wait ~5 min locally for DUST (else error 138) midnight balance midnight transfer mn_addr_undeployed1... 100 # positional: midnight serve --network preview # headless DApp Connector on ws://localhost:9932 midnight serve --network preview --approve-all # dev only: auto-approve every request ``` \#1 beginner gotcha Run `dust register` before transferring, or the transfer fails with `BalanceCheckOverspend` (138). DUST regenerates in about 5 minutes locally (see [Fees and DUST](/sdks/community/wallets/community-wallets-integration.md#fees-and-dust) and [Troubleshooting](/sdks/community/wallets/community-wallets-reference.md#troubleshooting-and-error-reference)). ``` // A DApp connects to the CLI connector exactly like a browser wallet: import { createWalletClient } from "midnight-wallet-connector"; const wallet = await createWalletClient({ url: "ws://localhost:9932", networkId: "Preview" }); const balances = await wallet.getUnshieldedBalances(); // same ConnectedAPI surface ``` Build and test against `midnight serve` (scriptable, no pop-ups), then deploy and let users connect with Lace or 1AM, with no code changes. Freshness (v0.4.1) `midnight airdrop` can now fund any address directly: paste the recipient's address, with no seed import needed. You no longer have to import a seed to fund browser wallets on a local network. The indexer connection also moved to the v4 API, which fixes connection errors on the test networks. ([repo](https://github.com/nel349/midnight-wallet-cli)) ([CLI README](https://www.npmjs.com/package/midnight-wallet-cli), [connector](https://www.npmjs.com/package/midnight-wallet-connector), [local playground](https://forum.midnight.network/t/local-playground-for-midnight-compact-contracts-run-a-full-node-indexer-and-proof-server-via-docker-fund-your-lace-wallet-and-deploy-without-testnets-or-faucets/1002)) ## AI and agent tooling (the MCP column)[​](#ai-and-agent-tooling-the-mcp-column "Direct link to AI and agent tooling (the MCP column)") The MCP column is agents calling tools, and it comes in two flavors. **Wallet-control MCP.** The midnight-wallet-cli ships an MCP server (`midnight-wallet-mcp`) that exposes the CLI commands as tools, so an AI agent can operate a self-custody wallet: | Group | MCP tools | | --------------- | -------------------------------------------------------------------------------------------------------------------------------- | | Wallet and info | `midnight_wallet_generate`, `_list`, `_use`, `_info`, `_remove`, `midnight_info`, `midnight_address`, `midnight_genesis_address` | | Transactions | `midnight_balance`, `_transfer`, `_airdrop`, `midnight_inspect_cost` | | DUST | `midnight_dust_register`, `_status` | | Local network | `midnight_localnet_up`, `_stop`, `_down`, `_status`, `_clean` | | Config | `midnight_config_get`, `_set`, `_unset`, `midnight_cache_clear` | The newest tools are the consequential ones. Beyond moving tokens, an agent can now drive the full contract lifecycle: deploy, call, and read state. A two-step confirmation tool also shows the human what the agent is about to spend before anything executes. Point any MCP client at the binary, such as Claude Code (`.mcp.json`), Claude Desktop, Cursor, VS Code (Copilot), or Windsurf: ``` { "mcpServers": { "midnight-wallet": { "command": "midnight-wallet-mcp" } } } ``` This is the highest-risk cell. Scope the agent's tools, cap spend, allowlist destinations, and keep a human in the loop (see [Security checklist](/sdks/community/wallets/community-wallets-reference.md#security-checklist)). Walkthrough: "Multi-Language Dev Session #22: midnight-wallet-cli" ([YouTube](https://www.youtube.com/watch?v=zgt27WFzQHk), [CLI README](https://www.npmjs.com/package/midnight-wallet-cli)). **Dev-assistant MCP.** This is tooling that helps you build: write Compact, wire the connector, and verify claims. See the talk "Midnight for Developers: Midnight MCP, The AI Tool That Finally Understands Compact" ([YouTube](https://www.youtube.com/watch?v=oGDSMDejUkE)). Two marketplaces: * **Midnight Expert** has 13 plugins (87 skills, 17 agents) across the dev lifecycle. The most relevant here are `midnight-tooling` (CLI, devnet, proof server), `midnight-dapp-dev` (frontend and connector), `midnight-wallet` (wallet SDK), `midnight-verify` (check SDK and connector claims), and `midnight-status-codes`. Install via `/plugin`, then add `https://midnightntwrk.expert`. ([midnightntwrk.expert](https://midnightntwrk.expert/)) * **Edda Labs** ships the `midnight` plugin: `/midnight-docs`, `/midnight-docs-repos`, `/midnight-examples`, `/midnight-contracts`, and `/midnight-starter` (the same [`eddalabs/midnight-starter-template`](https://github.com/eddalabs/midnight-starter-template) used in the [React pattern](/sdks/community/wallets/community-wallets-integration.md#react-the-production-pattern)). Install with `/plugin marketplace add eddalabs/edda-marketplace`, then `/plugin install midnight`. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Integrate a wallet Connect a community wallet in a browser DApp through the DApp Connector API (CAIP-372). This page covers discovery, connect, ZK proving, fees, and portable React code. To choose a wallet first, see the [overview](/sdks/community/wallets/community-wallets-overview.md). For headless or agent flows with no extension, see the [CLI and MCP workflow](/sdks/community/wallets/community-wallets-cli-mcp.md). | Item | Detail | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | DApp Connector API | `@midnight-ntwrk/dapp-connector-api` v4.0.1 | | Local proof server | `http://localhost:6300` (Lace and local networks); CLI connector on `ws://localhost:9932` | | Networks | `mainnet`, `preview`, `preprod`, `undeployed` (local). Only `'mainnet'` is connector-standard; other ids are wallet-defined (see [Connect and the ConnectedAPI surface](#connect-and-the-connectedapi-surface)) | ## The DApp Connector API (CAIP-372)[​](#the-dapp-connector-api-caip-372 "Direct link to The DApp Connector API (CAIP-372)") A Midnight browser wallet injects an Initial API under the global `window.midnight`, keyed by an identifier. The shape is compatible with the draft [CAIP-372](https://github.com/ChainAgnostic/CAIPs/pull/372/files) (Chain Agnostic Improvement Proposal), so the same DApp code works across wallets. ([npm](https://www.npmjs.com/package/@midnight-ntwrk/dapp-connector-api), [connector repo and spec](https://github.com/midnightntwrk/midnight-dapp-connector-api), [API reference](https://docs.midnight.network/api-reference/dapp-connector)) ``` type InitialAPI = { rdns: string; // reverse-DNS id, stable per product name: string; // display name (sanitize before rendering, XSS) icon: string; // URL or data: URL (render via , not innerHTML) apiVersion: string; // version of @midnight-ntwrk/dapp-connector-api implemented connect: (networkId: string) => Promise; }; ``` Support both discovery paths. Wallets such as Lace and 1AM inject under a fixed, friendly key (`window.midnight.mnLace`, `window.midnight['1am']`). The v4 specification instead installs each wallet under its own key and exposes a stable `rdns` field. Discover wallets by scanning `Object.values(window.midnight)` and matching on `rdns` or `name`. Before using a wallet, check its `apiVersion` against the range your DApp supports. The spec notes event-based discovery, like Ethereum's EIP-6963, as a possible future addition, but the current mechanism is the shared `window.midnight` object. ([React wallet-connect guide](https://docs.midnight.network/guides/react-wallet-connect)) ## Connect and the ConnectedAPI surface[​](#connect-and-the-connectedapi-surface "Direct link to Connect and the ConnectedAPI surface") `connect(networkId)` prompts you to authorize, then resolves to a ConnectedAPI that spans Midnight's three asset kinds (shielded, unshielded, and DUST). Only `'mainnet'` is standardized by the connector spec; every other network id is wallet-defined and they differ. The CLI connector, for example, expects capitalized `'Preview'`, `'PreProd'`, and `'Undeployed'`, which is why the [CLI snippet](/sdks/community/wallets/community-wallets-cli-mcp.md#develop-and-test-without-a-wallet) uses `networkId: "Preview"`. Check your target wallet's docs for the exact strings. | Method | Purpose | | ------------------------------------------------------------------------- | ----------------------------------------------------------- | | `getShieldedAddresses()` / `getUnshieldedAddress()` / `getDustAddress()` | Bech32m addresses per asset kind | | `getShieldedBalances()` / `getUnshieldedBalances()` | Per-token balances | | `getDustBalance()` | `{ balance, cap }`: DUST regenerates toward `cap` | | `makeTransfer(outputs, {payFees})` / `makeIntent(inputs, outputs, {...})` | Build a transfer or an unbalanced intent | | `balanceUnsealedTransaction(tx)` / `balanceSealedTransaction(tx)` | Balance and pay fees for a contract-built transaction | | `signData(data, {encoding, keyType})` | Sign arbitrary data with the unshielded key | | `submitTransaction(tx)` | Broadcast a sealed transaction (the wallet acts as relayer) | | `getProvingProvider(keyMaterialProvider)` | Delegate ZK proving to the wallet | | `getConfiguration()` / `getConnectionStatus()` / `hintUsage(methodNames)` | Config; status (with networkId); pre-request hints | Feature-detect, because coverage varies The connector is a contract, but not every wallet implements every method. Lace does not implement `getProvingProvider()` or `signData()` (see [Lace](/sdks/community/wallets/community-wallets-overview.md#lace)). Always check before calling, for example `typeof api.getProvingProvider === "function"`. The #1 connect gotcha: call connect() synchronously in the click handler Lace opens a real authorization pop-up. The browser silently blocks it if the browser lost transient user activation, for example if you `await`ed something, or used `setTimeout` or an RxJS `interval` first. Page-load auto-reconnect has no user gesture, so poll `window.midnight` until the wallet injects it, then connect. Extensions inject slightly after `DOMContentLoaded`, and users may need to refresh after installing. ## Where ZK proofs come from[​](#where-zk-proofs-come-from "Direct link to Where ZK proofs come from") Every Midnight transaction needs a ZK proof. Who generates that proof is the main difference between wallets, and it maps onto the custody models: * **Local proof server (Lace).** Lace requires a local proof server (Settings, then Midnight, then Local, at `http://localhost:6300`). Witness data stays on your machine, but you must run the server. Lace does not expose `getProvingProvider()`, so a DApp cannot delegate proving to it. * **In-browser WASM (1AM).** 1AM compiles Midnight's prover, a Halo2-based zk-SNARK over the BLS12-381 curve, into a few MB of WASM and proves in the tab. There is no separate process, though proving time still depends on circuit size and the one-time cold-start key load. 1AM implements `getProvingProvider()` and offers a hosted Proof Station. * **Delegated (`getProvingProvider`).** The v4 connector abstracts proving behind this method; the connector deprecates the old `Configuration.proverServerUri`. Obtain a proving provider from the wallet when it is available, and fall back to a configured proof server for Lace. ## Fees and DUST[​](#fees-and-dust "Direct link to Fees and DUST") You pay fees in DUST, which a wallet generates by holding NIGHT and regenerates over time. `getDustBalance()` returns `{ balance, cap }`, and `submitTransaction` uses the wallet as a relayer with a `payFees` option. A wallet can therefore sponsor fees, but sponsorship is a capability the connector allows, not a guarantee that any given wallet ships. On a fresh wallet, DUST takes time to generate: about 12 hours on Lace mainnet or testnet, and about 5 minutes on a local network. Overspending surfaces as `BalanceCheckOverspend` (138) (see [Troubleshooting](/sdks/community/wallets/community-wallets-reference.md#troubleshooting-and-error-reference)). ## The portable integration code[​](#the-portable-integration-code "Direct link to The portable integration code") This works for any standard-connector wallet (Lace, 1AM). The [CLI connector](/sdks/community/wallets/community-wallets-cli-mcp.md#develop-and-test-without-a-wallet) is a no-extension development fallback. ``` import { setNetworkId } from "@midnight-ntwrk/midnight-js-network-id"; import type { InitialAPI, ConnectedAPI } from "@midnight-ntwrk/dapp-connector-api"; // 1. Discover (friendly key first, then the v4 rdns scan) const wallets = Object.values(window.midnight ?? {}) .filter((w): w is InitialAPI => !!w?.name && !!w?.apiVersion); // 2. Connect: MUST be synchronous in the click handler (pop-up blocking) // networkId: only 'mainnet' is standard; others are wallet-defined (CLI uses 'Preview' etc.) async function connect(w: InitialAPI, networkId = "preprod"): Promise { const api = await w.connect(networkId); // user authorizes here const status = await api.getConnectionStatus(); if (status.status !== "connected") throw new Error("wallet disconnected"); setNetworkId(status.networkId); // align the DApp to the wallet's network return api; } // To submit: build the tx (api.makeTransfer or your contract), prove (feature-detect // api.getProvingProvider, else local proof server), then api.submitTransaction(tx). ``` ## Where wallets diverge[​](#where-wallets-diverge "Direct link to Where wallets diverge") Handle these differences between connectors: * **Proving:** feature-detect `getProvingProvider`. 1AM has it; Lace does not, so fall back to the local proof server and do not hard-code the deprecated `proverServerUri`. * **`signData`:** not on Lace, so feature-detect before any signature-based authentication. * **Pop-up:** Lace opens an auth pop-up, so keep `connect()` synchronous. The reconnect path has no gesture, so poll `window.midnight`, then connect. * **Network:** always reconcile the DApp to `getConnectionStatus().networkId`. * **DUST:** read `getDustBalance()`, handle both `{ balance: 0n }` and the `cap`, and do not assume sponsored fees. * **Non-standard tiles:** Ctrl and Gero may not inject a conformant connector, so feature-detect and degrade to Lace or 1AM. ## React: the production pattern[​](#react-the-production-pattern "Direct link to React: the production pattern") The Edda Labs midnight-starter-template (demo at `counter.nebula.builders`) wires Lace and 1AM through a copy-pasteable wallet widget. Use it rather than re-deriving the logic: ``` import { useWallet } from "@/modules/midnight/wallet-widget/hooks/useWallet"; function ConnectButton() { const { connectWallet, disconnect, status, dustBalance } = useWallet(); if (status?.status === "connected") return ; return ; } ``` Key files in the repo, under `frontend-vite-react/src/modules/midnight/`: * `wallet-widget/api/walletController.ts`: discovery, pop-up-safe connect, proof-server check * `wallet-widget/hooks/useWallet.ts` and `contexts/wallet.tsx`: state * `wallet-widget/ui/midnightWallet.tsx`: connect modal * `counter-sdk/`: wiring a connected wallet into a Compact call ([starter template](https://github.com/eddalabs/midnight-starter-template), [React guide](https://docs.midnight.network/guides/react-wallet-connect)) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Community wallets Community-built wallet integrations for the Midnight Network. These projects extend wallet support beyond the official Lace wallet, and their authors maintain them. Community-maintained, not officially supported The Midnight Foundation does not maintain the projects listed here; their authors do. Verify each one against the [compatibility matrix](/relnotes/support-matrix.md) before you integrate, and file issues with the maintainers directly. This guide helps you pick a wallet for a DApp, a backend, an agent, or personal use. It then points you to the code that integrates it. It sorts the landscape on two questions: who controls the keys (custody) and how you reach the wallet (interface). Accurate as of June 2026 The Midnight wallet ecosystem moves fast. Some integrations have launched; others remain announced or not yet publicly documented, and this guide labels them as such. For the current state, see the [ecosystem catalog](https://midnight.network/ecosystem-catalog), the [Midnight forum](https://forum.midnight.network/), and the [sources](/sdks/community/wallets/community-wallets-reference.md#sources). ## Quick answer[​](#quick-answer "Direct link to Quick answer") Nearly every Midnight wallet today is self-custody, so the main choice is how you reach it: * Browser DApp: integrate 1AM and Lace through the [DApp Connector](/sdks/community/wallets/community-wallets-integration.md). * Backend, CI, or AI agents: use the [wallet CLI](/sdks/community/wallets/community-wallets-cli-mcp.md#develop-and-test-without-a-wallet) (`midnight serve` and its MCP server). * Institutional custody of NIGHT: Fireblocks (see [Broader ecosystem](/sdks/community/wallets/community-wallets-reference.md#broader-ecosystem-compatibility)). Then refine by need: * Privacy by default: 1AM (shielded by default, in-browser proving). * Mobile-first or embedded wallet: Kuira (Android SDK, on-device proving; see [Kuira](#kuira)). * One multi-chain wallet: Ctrl (feature-detect its connector). * Future consumer onboarding: Midnight Passport (announced; see [Midnight Passport](#midnight-passport-announced)). urble is a consumer privacy-savings app, not a DApp-integration target. ## The custody and interface model[​](#the-custody-and-interface-model "Direct link to The custody and interface model") Two questions place any wallet: * **Custody:** who controls the keys? Self-custody (the end user), custodial (a provider), smart contract or account abstraction (on-chain code), or MPC/threshold (keys split into shares). * **Interface:** how do you reach it? Browser, mobile, CLI, or MCP (an AI agent calling tools). The two axes are independent, so one wallet can occupy several cells. You can reach a self-custody key, for example, from a browser, a CLI, or an agent. On Midnight today the rows differ mainly by interface, because almost every wallet is self-custody. Custody on Midnight: * **Self-custody:** the key lives on the end user's device, in an extension, mobile secure storage, or hardware, and no third party can sign. Almost every Midnight wallet is here: Lace, 1AM, Kuira, Ctrl, Gero, SubWallet, and NuFi. * **Custodial:** a provider holds the keys and signs. No one has documented a first-party consumer custodial wallet yet; the near-term path is institutional MPC plus exchange or Wallet-IaaS provisioning. * **Smart contract / account abstraction:** the account is on-chain code with programmable authorization (multisig, social recovery, session keys). Midnight has no native account abstraction, so this row is empty. * **MPC / threshold:** an *m*-of-*n* quorum signs without reconstructing the full key. On Midnight this is the institutional path, led by Fireblocks for NIGHT. ### The matrix[​](#the-matrix "Direct link to The matrix") Legend: **Available** is a usable Midnight product, including beta and alpha. **Emerging** labels an announced or institutional product, not yet a shippable self-custody offering. **Not yet** means none on Midnight, with an *italic* industry example for reference. **n/a** does not apply. | Custody / Interface | Browser | Mobile | CLI (SDK / CI) | MCP (AI agents) | | ----------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------- | | **Self-custody** | Available: Lace, 1AM, Ctrl, Gero, SubWallet, NuFi | Available: 1AM (beta), urble, Kuira (Android, alpha) | Available: midnight-wallet-cli (`midnight serve`) | Available: midnight-wallet-cli MCP server | | **Custodial** | Not yet (*CEX web wallets*) | Not yet (*CEX apps*) | Not yet (*exchange custody APIs*) | Not yet (*provider agent tooling*) | | **Smart contract / AA** | Not yet (*Safe, ERC-4337*) | Not yet | Not yet | Not yet | | **MPC / threshold** | Emerging: *Midnight Passport*; institutional console | Emerging: *Midnight Passport* | Emerging: Fireblocks (institutional); Dynamic (Midnight not documented) | Emerging: MPC plus agent custody (*industry*) | The self-custody row is live today across all four interfaces, and most DApps target self-custody browser and mobile wallets. The account-abstraction row is empty, because Midnight has no native smart accounts. The MPC row is mostly institutional, with one consumer entry on the way in Midnight Passport. ## Choose by scenario[​](#choose-by-scenario "Direct link to Choose by scenario") | Your scenario | Reach for | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Consumer privacy DApp on desktop and phone | 1AM and Lace; Kuira for Android; Ctrl for multi-chain | | Mobile app with a built-in wallet (no separate install) | Kuira (Android; iOS and React Native later; see [Kuira](#kuira)) | | One wallet for several chains | Ctrl (feature-detect first) | | Claim or hold NIGHT on the Cardano side | Lace, Gero, Yoroi, Eternl, NuFi, Vespr (see [Broader ecosystem](/sdks/community/wallets/community-wallets-reference.md#broader-ecosystem-compatibility)) | | Consumer privacy savings app | urble | | Backend payouts, airdrops, CI, or end-to-end tests | wallet CLI / `midnight serve` (see [CLI workflow](/sdks/community/wallets/community-wallets-cli-mcp.md#develop-and-test-without-a-wallet)) | | An AI agent that holds or moves funds | wallet-cli MCP server, with guardrails (see [AI and agent tooling](/sdks/community/wallets/community-wallets-cli-mcp.md#ai-and-agent-tooling-the-mcp-column)) | | AI-assisted building | Midnight Expert and Edda dev-assistant tools (see [AI and agent tooling](/sdks/community/wallets/community-wallets-cli-mcp.md#ai-and-agent-tooling-the-mcp-column)) | | Institutional or regulated custody | Fireblocks | | Embedded social or passkey onboarding | Dynamic (confirm Midnight support) or Wallet-IaaS | Two rules cover most cases. For a browser DApp, target 1AM and Lace through the standard connector, and add others only after runtime feature-detection. For automation or agents, use the CLI and MCP column, not a consumer extension. On proving, 1AM proves in-browser and Kuira proves on-device, while Lace needs a local proof server. Feature-detect to support both (see [Where ZK proofs come from](/sdks/community/wallets/community-wallets-integration.md#where-zk-proofs-come-from)). ## The wallets[​](#the-wallets "Direct link to The wallets") Lace, 1AM, and Kuira get full profiles; the rest are shorter. Feature status is in the [functionality matrix](/sdks/community/wallets/community-wallets-reference.md#functionality-matrix), integration differences in [Where wallets diverge](/sdks/community/wallets/community-wallets-integration.md#where-wallets-diverge), and errors in [Troubleshooting](/sdks/community/wallets/community-wallets-reference.md#troubleshooting-and-error-reference). The profiled wallets fall into three categories: * **Midnight-native** (1AM, urble, Kuira): built for Midnight's dual-state, zero-knowledge model and shielded-capable. 1AM has the browser integration story, urble is an end-user app, and [Kuira](#kuira) is Android plus an embeddable SDK. * **Cardano multi-chain plus Midnight** (Lace, Ctrl, Gero): established wallets adding Midnight. Lace is the Input Output reference wallet; Ctrl and Gero are third-party. * **Embedded / Wallet-as-a-Service** (Kuira): an SDK you embed to create wallets. [Kuira](#kuira) is Midnight-native and self-custody. Dynamic, a social and passkey service, has no first-party Midnight support (see [Broader ecosystem](/sdks/community/wallets/community-wallets-reference.md#broader-ecosystem-compatibility)). ### Lace[​](#lace "Direct link to Lace") **Best for:** standard DApps whose users can run a local proof server. **Status:** live, with a partial `ConnectedAPI` (no `getProvingProvider` or `signData` yet). Open source. * **Overview:** Input Output's multi-chain wallet (Cardano, Bitcoin, Midnight). For Midnight it is a Chrome and Edge extension, not the Lace mobile app. ([lace.io/midnight](https://www.lace.io/midnight), [docs](https://docs.midnight.network/guides/lace-wallet), [GitHub](https://github.com/input-output-hk/lace)) * **Supports:** * NIGHT management. * DUST generation through the Dust Generation DApp (about 12 hours to initialize; see [Fees and DUST](/sdks/community/wallets/community-wallets-integration.md#fees-and-dust)). * Shielded and unshielded transactions, with privacy opt-in. * Cardano assets, staking, and hardware wallets on the Cardano side. * The standard connector at `window.midnight.mnLace`. * **Limitations:** no in-browser proving, so you need a local proof server; `getProvingProvider()` and `signData()` are not implemented, so feature-detect and fall back (see [Where wallets diverge](/sdks/community/wallets/community-wallets-integration.md#where-wallets-diverge)). On Brave, disable Shields so the DApp can reach the local proof server. * **Known issues:** the [Midnight forum](https://forum.midnight.network/t/lace-wallet-doesnt-implement-getprovingprovider-expected-behavior-or-version-gap/1213) discusses the missing `getProvingProvider`. "Unable to get wallet address" usually means the extension is not installed or the page needs a refresh ([forum](https://forum.midnight.network/t/unable-to-get-wallet-address-from-lace-wallet/922)). The [Lace issue tracker](https://github.com/input-output-hk/lace/issues) tracks build-specific bugs: an outdated Firefox build, some 2.0 builds blocking shielded transfers, and large-contract deploys failing on Preprod. Maintained by Input Output. ### 1AM[​](#1am "Direct link to 1AM") **Best for:** new Midnight-first DApps, and users who want shielded-by-default plus mobile. **Status:** live, implements `getProvingProvider` (in-browser proving). Open source: no (source not published). * **Overview:** purpose-built for Midnight. Chrome and Firefox extensions are live; iOS and Android are in beta (Android package `com.webisoft.oneam`); the team lists Safari as coming soon. Non-custodial, with mobile keys in device secure storage. ([1am.xyz](https://1am.xyz/), [Chrome](https://chromewebstore.google.com/detail/1am/bphnkdkcnfhompoegfpgnkidcjfbojjp), [Play](https://play.google.com/store/apps/details?id=com.webisoft.oneam\&hl=en_GB), [forum guide](https://forum.midnight.network/t/a-comprehensive-guide-to-the-1am-crypto-wallet-on-the-midnight-network/1173)) * **Supports:** * NIGHT and DUST with real-time regeneration tracking. * Shielded by default, with selective disclosure. * In-browser WASM proving plus a hosted Proof Station (see [Where ZK proofs come from](/sdks/community/wallets/community-wallets-integration.md#where-zk-proofs-come-from)). * `getProvingProvider`, a built-in DApp browser, and a small first-party app ecosystem. * Injects at `window.midnight['1am']` (standard connector v4). * **Not documented:** Cardano or multi-chain support, and hardware support. 1AM's site advertises a "Proof Station SDK" with a code snippet, but 1AM has not published an npm package or docs. Treat it as announced rather than documented, and integrate 1AM through the standard connector. Fee sponsorship 1AM has not documented automatic fee sponsorship, so do not assume a zero-DUST experience. Confirm fee handling on your target network first. ### Kuira[​](#kuira "Direct link to Kuira") **Best for:** mobile-first apps that want a built-in wallet, with no separate install and no seed phrase. **Status:** alpha (`v0.1.0-alpha02`). Open source: partial (source jars on Maven Central; repo private). * **Overview:** a native Android wallet and an embeddable SDK. You drop the wallet inside an Android app so it can hold and move funds on Midnight on its own, with no external wallet. Built by Kuira Labs and distributed on Maven Central (`io.github.kuiralabs:dapp-ui:0.1.0-alpha02`) under a stated Apache-2.0 license. The source repo is private, and only source jars ship. ([Kuira SDK docs](https://kuiralabs.github.io/kuira-sdk-android/)) * **Supports:** * Shielded and unshielded transactions. * On-device ZK proving in seconds, with no proof server to run, unlike Lace's local server or 1AM's in-browser WASM. * An embedded self-custody wallet in the app's own process. * DUST regeneration and indexer sync. * Example apps: a Kuira Starter counter, and BBoard, a shared on-chain bulletin board. * **Identity (the "Sigil"):** your identity is a passkey plus fingerprint instead of a seed phrase, which Kuira calls a Sigil. It is a passkey-derived DID (decentralized identifier) minted by one biometric, so onboarding is seedless. Recovery works on any device signed in to the same Google account. The `SigilIdentityProvider` is swappable, and Kuira names [Midnight Passport](#midnight-passport-announced) as a planned identity backend, so the announced Passport and this mobile cell may converge. * **Limitations:** * Android only today (Kuira plans iOS and React Native for later in 2026), so the SDK path is platform-locked for now. * The browser DApp Connector is not documented: a `connector` module exists, but conformance with the `window.midnight` standard is not publicly stated. * Alpha, with limitations expected to close in later releases. ### Ctrl[​](#ctrl "Direct link to Ctrl") **Best for:** users who want one multi-chain wallet (Bitcoin, EVM, Cardano, Midnight) with hardware support. Self-custody, browser plus mobile; Midnight privacy depth is not documented. * **Overview:** Ctrl (formerly XDEFI) lists Midnight among its supported chains. It offers a Chrome extension plus iOS (`6630386336`) and Android (`xyz.ctrl.wallet`), with Ledger and Trezor support. It has also run Midnight programs, including Scavenger Mine and the Glacier Airdrop. ([ctrl.xyz](https://ctrl.xyz/), [Scavenger Mine](https://ctrl.xyz/news/scavenger-mine-by-ctrl-wallet-claim-your-night-tokens-today/)) * **Connector:** Ctrl appears as `ctrl_wallet` in the catalog and states that its extension connects to Midnight apps. Ctrl confirms standard-connector conformance only at the marketing level. Feature-detect the injected provider at runtime before you list it (see [Where wallets diverge](/sdks/community/wallets/community-wallets-integration.md#where-wallets-diverge)). Ctrl does not document a Midnight-specific SDK. * **Limitations:** Ctrl does not individually document Midnight privacy depth (shielded-by-default, DUST, selective disclosure, proving), so test before you promise it. Not open source. ### urble[​](#urble "Direct link to urble") Self-custody, mobile. A consumer privacy-savings app on Midnight, built by Brick Towers: shielded send and receive plus selective disclosure, with rule-based savings announced. It is not a connector target, so use 1AM for mobile DApp integration. The vendor does not document open-source status. ([Brick Towers](https://bricktowers.io/solutions/urble-the-future-of-personal-savings/)) ### Gero[​](#gero "Direct link to Gero") Self-custody, browser plus mobile; the vendor has announced Midnight integration or has it in progress. A privacy-focused Cardano multi-chain wallet with a "zkFiat" roadmap, and a valid Glacier Drop and NIGHT claim wallet on the Cardano side. Its Midnight page advertises ZK proofs, shielded transactions, selective disclosure, and anonymous staking. However, it does not yet mention NIGHT, DUST, or the Midnight connector, and gives no live date, so treat these as vendor-stated. Use Gero as a NIGHT claim wallet today, not a tested connector. ([Midnight page](https://gerowallet.io/midnight-wallet/), [Glacier Drop](https://www.midnight.gd/news/glacier-drop-wallets-and-address-type-compatibility)) ### Midnight Passport (announced)[​](#midnight-passport-announced "Direct link to Midnight Passport (announced)") MPC/threshold row, browser plus mobile (placed provisionally; the exact key scheme is not yet public). Announced but not yet live, from Input Output and introduced by Charles Hoskinson in 2026. A seedless, QR-onboarded consumer wallet that aims to give a new user a working wallet, name service, and multi-chain access in under 60 seconds. It uses per-device hardware-resident keys with trusted-helper recovery instead of a paper backup, selective disclosure, and chain abstraction (send to `alice.midnight` through the `.night` name service). It sits in the MPC row because it is the first consumer example on Midnight of custody beyond plain self-custody. Input Output has not yet detailed the full key scheme. It is not yet available for integration, and this page includes it as a signal of where consumer onboarding is heading. For updates, follow Midnight's official channels. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Wallet reference Reference material for the community wallets covered in the [overview](/sdks/community/wallets/community-wallets-overview.md): the full functionality matrix, troubleshooting, a security checklist, broader ecosystem compatibility, and a glossary. ## Functionality matrix[​](#functionality-matrix "Direct link to Functionality matrix") These are the granular tie-breakers, for once the [matrix](/sdks/community/wallets/community-wallets-overview.md#the-matrix) and the [per-wallet profiles](/sdks/community/wallets/community-wallets-overview.md#the-wallets) have narrowed your choice. Legend: Yes; No; Partial (caveats below); Not documented (not publicly documented as of June 2026); and n/a. ### Platforms and availability[​](#platforms-and-availability "Direct link to Platforms and availability") | Wallet | Browser extension | Mobile app | Midnight-native | Open source | | ------- | --------------------- | -------------------- | --------------- | ----------------------------------- | | Lace | Yes (Chrome/Edge) | No (Midnight) | No | Yes | | 1AM | Yes (Chrome, Firefox) | Yes (beta) | Yes | No | | Kuira | No | Yes (Android, alpha) | Yes | Partial (source jars; repo private) | | urble | No | Yes | Yes | Not documented | | Dynamic | No (SDK) | Via SDK | No | No | | Ctrl | Yes (Chrome) | Yes | No | No | | Gero | Yes | Yes | No | No | ### Privacy and assets[​](#privacy-and-assets "Direct link to Privacy and assets") | Wallet | NIGHT | DUST | Shielded txns | Unshielded txns | Shielded by default | Selective disclosure | | ------- | -------------- | -------------- | -------------- | --------------- | ------------------- | -------------------- | | Lace | Yes | Yes | Yes | Yes | No | Not documented | | 1AM | Yes | Yes | Yes | Yes | Yes | Yes | | Kuira | Yes | Yes | Yes | Yes | Not documented | Not documented | | urble | Not documented | Not documented | Yes | Not documented | Yes | Yes | | Dynamic | No | No | No | No | No | No | | Ctrl | Yes | Not documented | Not documented | Not documented | No | Not documented | | Gero | Yes | Not documented | Not documented | Not documented | Not documented | Not documented | ### Proving and fees[​](#proving-and-fees "Direct link to Proving and fees") | Wallet | In-browser / on-device proving | Local prover needed | `getProvingProvider` | Gas sponsorship | | ------- | ------------------------------ | ------------------- | -------------------- | ------------------ | | Lace | No | Yes | No | No | | 1AM | Yes (WASM; Halo2/BLS12-381) | No | Yes | Not documented | | Kuira | Yes (on-device, mobile) | No | n/a | Not documented | | urble | Not documented | Not documented | Not documented | Not documented | | Dynamic | No | n/a | Not documented | Yes (non-Midnight) | | Ctrl | Not documented | Not documented | Not documented | Not documented | | Gero | Not documented | Not documented | Not documented | Not documented | ### Developer integration[​](#developer-integration "Direct link to Developer integration") | Wallet | DApp Connector | `signData` | Dedicated SDK | DApp browser | Hardware wallet | Cardano / multi-chain | Staking | | ------- | -------------- | -------------- | -------------------------- | -------------- | ------------------- | --------------------- | -------------- | | Lace | Yes (`mnLace`) | No | No | n/a | Yes (Cardano) | Yes | Yes (Cardano) | | 1AM | Yes (`'1am'`) | Not documented | Announced / Not documented | Yes | Not documented | No | Not documented | | Kuira | Not documented | Not documented | Yes (Android, public docs) | n/a | Not documented | No | Not documented | | urble | No | Not documented | No | No | Not documented | No | No | | Dynamic | No | Not documented | Yes (non-Midnight) | n/a | No | No (other chains) | No | | Ctrl | Partial | Not documented | No | Yes | Yes (Ledger/Trezor) | Yes | Yes | | Gero | Not documented | Not documented | No | Not documented | Not documented | Yes | Not documented | Notes: * Ctrl's DApp Connector is Partial: a connector the vendor states, so feature-detect it at runtime. * Gero's cells are Not documented and vendor-stated, pending public documentation; Gero is a valid Cardano-side NIGHT claim wallet. * Dynamic's cells reflect its lack of documented Midnight support. * 1AM gas sponsorship is not documented (see the note in [1AM](/sdks/community/wallets/community-wallets-overview.md#1am)). * 1AM announced a dedicated SDK but has not documented it. The advertised "Proof Station SDK" has no published package or docs (see [1AM](/sdks/community/wallets/community-wallets-overview.md#1am)), so integrate 1AM through the standard connector. * Kuira's proving is on-device on Android, counted in the proving column above, not browser WASM. * Kuira's dedicated SDK is the one mobile SDK with public docs (see [Kuira](/sdks/community/wallets/community-wallets-overview.md#kuira)). ### Developer experience[​](#developer-experience "Direct link to Developer experience") While building, the daily question is which wallet gives the best development loop. The table below scores four capabilities: * a local network (`undeployed`, a disposable Midnight-in-Docker stack with no faucets); * custom servers; * reproducible test wallets from a known seed; * headless CI runs, with no human clicking approve. | Wallet | Local network (`undeployed`) | Custom servers | Reproducible test wallets | Headless / CI | | ---------- | ---------------------------- | -------------------------- | ---------------------------------- | ------------------------------- | | wallet CLI | Yes (`localnet up`) | Yes (`config set`) | Yes (seed-based `wallet generate`) | Yes (`serve --approve-all`) | | Lace | Partial (local proof server) | Partial (proof-server URL) | No (UI-generated seed) | No (manual pop-up approval) | | 1AM | Not documented | Not documented | No | No (manual approval) | | Kuira | Not documented | Not documented | Partial (`wallet-seed` module) | No (mobile, biometric approval) | For the inner development loop, the wallet CLI covers every column: a local network, reproducible fixtures, and no human in the way (see [Develop and test without a wallet](/sdks/community/wallets/community-wallets-cli-mcp.md#develop-and-test-without-a-wallet)). The browser and mobile wallets are end-user surfaces. Build and test against the CLI, then let users connect with Lace or 1AM, or ship Kuira embedded. ## Troubleshooting and error reference[​](#troubleshooting-and-error-reference "Direct link to Troubleshooting and error reference") Symptom, then cause, then fix. The ledger and connector errors come first, then the CLI JSON error contract (`--json` returns `{error, code, message, exitCode}`). | Symptom / error | Likely cause | Fix | | ------------------------------------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `BalanceCheckOverspend` (138) | Not enough DUST for fees | Wait for DUST (about 12 hours on a fresh Lace; about 5 minutes locally) or designate more NIGHT; read `getDustBalance()` first | | Authorize pop-up never appears, or connect hangs | `connect()` not called synchronously on click | Call `connect()` directly in the click handler; do not `await` or `setTimeout` before it | | `window.midnight` is `undefined` | Extension not installed or enabled, or injected after load | Prompt to install, then refresh; for auto-reconnect, poll before connecting | | `getProvingProvider is not a function` (Lace) | Lace does not implement it | Feature-detect and use a local proof server ([forum](https://forum.midnight.network/t/lace-wallet-doesnt-implement-getprovingprovider-expected-behavior-or-version-gap/1213)) | | `signData` "Method not implemented" (Lace) | Unimplemented on Lace | Avoid signature-based auth on Lace; feature-detect first ([Lace issues](https://github.com/input-output-hk/lace/issues)) | | Proof generation fails, or prover unreachable | Local proof server down, or Brave Shields blocking it | Start it on `localhost:6300`; disable Brave Shields for the origin | | Network mismatch | DApp and wallet on different networks | Reconcile to `getConnectionStatus().networkId` via `setNetworkId(...)` | | 1AM first proof very slow | A few MB of WASM cold-start | Pre-warm, or show a "loading prover" state | | Deploy fails before it starts | Wallet not fully synced | Wait for wallet sync to complete before deploying | | CLI `DUST_REQUIRED` (exit 5) | No DUST | `midnight dust register`, then retry once DUST generates | | CLI `INSUFFICIENT_BALANCE` (exit 5) | Not enough NIGHT | Fund the wallet (faucet on testnets; `airdrop` only on `undeployed`) | | CLI `NETWORK_ERROR` (exit 4) | Connection refused, timeout, or DNS | Check node and indexer endpoints | | CLI `PROOF_TIMEOUT` (exit 6) | ZK proof timed out | Ensure the proof server is healthy; retry; reduce circuit complexity | | CLI `STALE_UTXO` (exit 6) | UTXOs consumed by another transaction | `midnight cache clear`, then rebuild | | CLI `TX_REJECTED` (exit 6) | Node rejected the transaction (TTL or validity) | Inspect the message and rebuild with current state | CLI codes are a documented contract (see the [CLI's JSON-output reference](https://www.npmjs.com/package/midnight-wallet-cli)). For canonical Midnight error and status codes, use the `midnight-status-codes` reference. ## Security checklist[​](#security-checklist "Direct link to Security checklist") The connector hands your page data from an untrusted extension, so treat it accordingly: * **Sanitize the wallet `name`**, and render the `icon` with ``, never `innerHTML` (XSS). * **Validate `networkId`**: reconcile to `getConnectionStatus().networkId` and refuse mismatches. * **Do not trust injected data as authority**: `rdns` and `name` are for display and selection, not security decisions. Match the expected `rdns`, and tell users to install only from official stores. * **Keep witness data local**: prefer in-browser proving (1AM) or a local proof server (Lace). If you ever use a hosted prover, say so. * **Confirm fee sponsorship**: not all wallets sponsor fees, so verify on your target network before you promise a "no DUST needed" experience. * **Guard agent (MCP) access hard**: scope tools, cap spend per action and per day, allowlist destinations, and require human confirmation for anything irreversible. An agent with unbounded signing authority is the highest-risk cell on the grid. ## Broader ecosystem compatibility[​](#broader-ecosystem-compatibility "Direct link to Broader ecosystem compatibility") Beyond the wallets profiled in the [overview](/sdks/community/wallets/community-wallets-overview.md#the-wallets), more Cardano wallets announced Midnight and NIGHT compatibility around the token generation event (TGE) and Glacier Drop. Most target claiming and holding NIGHT rather than deep DApp integration, adding entries to the self-custody browser and mobile cells: * **Announced self-custody (pre-mainnet):** Lace, SubWallet, NuFi, Vespr, Gero, Tokeo, Keystone, Yoroi, and Begin Wallet. These are forward-looking, so treat them as announced. ([Midnight blog](https://midnight.network/blog/looking-ahead-to-midnight-self-custody-wallet-integrations)) * **Glacier Drop claim wallets (Cardano side):** Yoroi, Typhon, Gero, Vespr, Eternl (desktop), and NuFi. ([compatibility](https://www.midnight.gd/news/glacier-drop-wallets-and-address-type-compatibility)) * **Embedded / Wallet-as-a-Service:** Dynamic (social and passkey login, TSS-MPC keys, gas sponsorship) lists EVM, Solana, Bitcoin, and Sui, but does not list Midnight or Cardano. It appears as `dynamic_xyz` in the catalog with no first-party Midnight support as of June 2026. Treat Midnight support as unconfirmed; for passkey onboarding on Midnight, use Wallet-IaaS or Smart Custody. ([dynamic.xyz](https://www.dynamic.xyz/), [TSS-MPC](https://www.dynamic.xyz/blog/introducing-dynamic-embedded-wallets-with-tss-mpc)) * **Institutional / MPC:** Fireblocks for institutional custody of NIGHT, the MPC console and API cell. ([Midnight and Fireblocks](https://midnight.network/blog/midnight-foundation-collaborates-with-fireblocks-to-expand-institutional-access-to-web3)) For the authoritative current list, see the [ecosystem catalog](https://midnight.network/ecosystem-catalog) (use the [`institutional-custody`](https://midnight.network/ecosystem-catalog?tag=institutional-custody) tag for the custody and MPC slice). ## Glossary[​](#glossary "Direct link to Glossary") Wallet-relevant terms. * **Custody model:** who controls the keys; the matrix rows (self-custody, custodial, account abstraction, and MPC). * **Self-custody / custodial:** keys on your device, where no third party can sign, versus a provider that holds the keys and signs. * **Account abstraction (AA):** the account is on-chain code with programmable authorization. Not native to Midnight as of June 2026. * **MPC / threshold (TSS):** the protocol splits the key into shares, and an *m*-of-*n* quorum signs without reconstructing a full key. The basis of institutional custody (Fireblocks for NIGHT). * **Interface:** how you reach the wallet; the matrix columns (browser, mobile, CLI, and MCP). * **MCP (Model Context Protocol):** a standard by which AI agents call tools, either wallet tools (move funds) or developer tools (help you build). * **Midnight Passport:** an announced first-party seedless, QR-onboarded consumer wallet (browser and mobile) from Input Output, with per-device hardware-resident keys and trusted-helper recovery. Input Output has not yet publicly detailed the exact scheme (MPC versus secure-enclave) (see [Midnight Passport](/sdks/community/wallets/community-wallets-overview.md#midnight-passport-announced)). * **Sigil:** [Kuira](/sdks/community/wallets/community-wallets-overview.md#kuira)'s identity primitive, a passkey-derived DID minted by one biometric, with no seed phrase. The SDK exposes it as a swappable `SigilIdentityProvider`, and Kuira names [Midnight Passport](/sdks/community/wallets/community-wallets-overview.md#midnight-passport-announced) as a planned future backend. * **On-device proving:** generating a transaction's ZK proof on your phone (Kuira, Android) in seconds. No local proof server runs, and nothing leaves the device. The mobile counterpart to 1AM's in-browser WASM proving. * **NIGHT / DUST:** the native value token (public, and the source of DUST) versus a shielded, non-transferable, decaying fee resource with a `balance` and a `cap`. * **Shielded vs unshielded:** Midnight's dual ledger, private versus public state. 1AM and urble default to shielded; Lace is opt-in. * **Selective disclosure / viewing key:** reveal specific facts without exposing full data; a read-only key for auditors. * **DApp Connector / CAIP-372:** the standard by which a wallet injects an API under `window.midnight`. * **rdns:** the reverse-DNS wallet id used for discovery (`mnLace`, `'1am'`). * **Intent:** an often unbalanced set of inputs and outputs; the building block for transfers and swaps. * **Sealed vs unsealed tx:** ready-to-submit (proofs plus binding) versus pre-binding. * **Relayer:** submits a transaction and pays its fees on your behalf; the basis of "gas sponsorship". * **Proving provider:** the abstraction (`getProvingProvider`) for delegating ZK proving to the wallet. * **Bech32m:** the address encoding the connector returns. * **Local proof server:** the native binary (`localhost:6300`) that generates ZK proofs for wallets that do not prove in-browser. * **Wallet-IaaS / Smart Custody:** Midnight infrastructure for delegated or embedded wallet provisioning, also called Wallet-as-a-Service (WaaS); the route for social and passkey onboarding. * **DID (decentralized identifier):** a self-owned identifier (for example `did:key:…`) not issued by a central authority. In Kuira, the wallet derives a DID from a passkey to form the Sigil. ## Sources[​](#sources "Direct link to Sources") **DApp Connector and standard** * [DApp Connector API reference](https://docs.midnight.network/api-reference/dapp-connector) * [Connector repo and specification](https://github.com/midnightntwrk/midnight-dapp-connector-api) * [`@midnight-ntwrk/dapp-connector-api` on npm (v4.0.1)](https://www.npmjs.com/package/@midnight-ntwrk/dapp-connector-api) * [React wallet-connect guide](https://docs.midnight.network/guides/react-wallet-connect) * [CAIP-372 draft](https://github.com/ChainAgnostic/CAIPs/pull/372/files) * [Midnight ecosystem catalog](https://midnight.network/ecosystem-catalog) ([institutional-custody tag](https://midnight.network/ecosystem-catalog?tag=institutional-custody)) * [Reference DApp (Lace and 1AM): Edda Labs midnight-starter-template](https://github.com/eddalabs/midnight-starter-template) * [Video: Lace and 1AM with the DApp Connector](https://www.youtube.com/watch?v=m7mU7k5lgqU) **Custody models and institutional** * [Midnight collaborates with Fireblocks](https://midnight.network/blog/midnight-foundation-collaborates-with-fireblocks-to-expand-institutional-access-to-web3) * [Fireblocks: What is MPC](https://www.fireblocks.com/report/what-is-mpc) * [Dynamic embedded wallets (TSS-MPC)](https://www.dynamic.xyz/blog/introducing-dynamic-embedded-wallets-with-tss-mpc) **Midnight Passport:** announced by Input Output; follow Midnight's official channels for updates. **Developer, AI, and agent tooling (MCP)** * [Wallet CLI on npm (commands, `midnight serve`, MCP server)](https://www.npmjs.com/package/midnight-wallet-cli) * [Wallet CLI repo (v0.4.1)](https://github.com/nel349/midnight-wallet-cli) * [CLI connector client on npm](https://www.npmjs.com/package/midnight-wallet-connector) * [Video: Multi-Language Dev Session #22, midnight-wallet-cli](https://www.youtube.com/watch?v=zgt27WFzQHk) * [Video: Midnight for Developers, Midnight MCP](https://www.youtube.com/watch?v=oGDSMDejUkE) * [Midnight Expert marketplace](https://midnightntwrk.expert/) * [Edda Labs marketplace](https://github.com/eddalabs/edda-marketplace) **Lace** * [Lace Midnight page](https://www.lace.io/midnight); [Lace wallet guide](https://docs.midnight.network/guides/lace-wallet) * [Lace GitHub repo and issue tracker](https://github.com/input-output-hk/lace) * [Forum: Lace doesn't implement getProvingProvider](https://forum.midnight.network/t/lace-wallet-doesnt-implement-getprovingprovider-expected-behavior-or-version-gap/1213) * [Forum: Unable to get wallet address from Lace](https://forum.midnight.network/t/unable-to-get-wallet-address-from-lace-wallet/922) **1AM** * [1AM website](https://1am.xyz/); [1AM on the Chrome Web Store](https://chromewebstore.google.com/detail/1am/bphnkdkcnfhompoegfpgnkidcjfbojjp) * [1AM on Google Play](https://play.google.com/store/apps/details?id=com.webisoft.oneam\&hl=en_GB) * [1AM comprehensive guide (forum)](https://forum.midnight.network/t/a-comprehensive-guide-to-the-1am-crypto-wallet-on-the-midnight-network/1173) **Kuira** * [Kuira Android SDK docs](https://kuiralabs.github.io/kuira-sdk-android/) * Maven Central: `io.github.kuiralabs:dapp-ui:0.1.0-alpha02` **urble, Dynamic, Ctrl, Gero** * [urble (Brick Towers)](https://bricktowers.io/solutions/urble-the-future-of-personal-savings/) * [Dynamic website](https://www.dynamic.xyz/); [Dynamic embedded wallets (TSS-MPC)](https://www.dynamic.xyz/blog/introducing-dynamic-embedded-wallets-with-tss-mpc) * [Ctrl website](https://ctrl.xyz/); [Scavenger Mine by Ctrl](https://ctrl.xyz/news/scavenger-mine-by-ctrl-wallet-claim-your-night-tokens-today/) * [Gero Midnight wallet page](https://gerowallet.io/midnight-wallet/) **Broader compatibility and dev workflow** * [Looking ahead to Midnight self-custody wallet integrations](https://midnight.network/blog/looking-ahead-to-midnight-self-custody-wallet-integrations) * [Glacier Drop wallets and address-type compatibility](https://www.midnight.gd/news/glacier-drop-wallets-and-address-type-compatibility) The Edda Labs `midnight-starter-template` (the `wallet-widget` module) implements the connect and discovery patterns from the [integration guide](/sdks/community/wallets/community-wallets-integration.md), wiring Lace and 1AM through `@midnight-ntwrk/dapp-connector-api` v4.0.1. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight.js error reference The Midnight.js API exposes structured error classes so you can classify failures when working with contracts and transactions. This reference highlights the error classes and their properties. ## Quick reference[​](#quick-reference "Direct link to Quick reference") | Class | Kind | Trigger | | ------------------------------------------ | ---------------- | ------------------------------------------------------------------- | | `TxFailedError` | Transaction | Consensus rejected or failed to apply a transaction | | `DeployTxFailedError` | Transaction | Deploy transaction failed | | `CallTxFailedError` | Transaction | Call transaction failed | | `ReplaceMaintenanceAuthorityTxFailedError` | Transaction | Maintenance authority replacement failed | | `RemoveVerifierKeyTxFailedError` | Transaction | Verifier key removal failed | | `InsertVerifierKeyTxFailedError` | Transaction | Verifier key insertion failed | | `ContractTypeError` | Contract | Deployed contract type or verifier keys do not match expectations | | `IncompleteCallTxPrivateStateConfig` | Configuration | `privateStateId` set without `privateStateProvider` on a call | | `IncompleteFindContractPrivateStateConfig` | Configuration | `initialPrivateState` set without `privateStateId` on a find | | `ScopedTransactionIdentityMismatchError` | State / identity | Scoped batch reused cache for a different contract or private state | ## Transaction errors[​](#transaction-errors "Direct link to Transaction errors") These errors occur when a submitted transaction fails during execution or validation. ### Transaction failed (`TxFailedError`)[​](#transaction-failed-txfailederror "Direct link to transaction-failed-txfailederror") An error indicating that a transaction submitted to a consensus node failed. #### Properties[​](#properties "Direct link to Properties") * `finalizedTxData`: Finalization data of the failed transaction * `circuitId` (optional): Circuit(s) used to construct the transaction ### Deploy transaction failed (`DeployTxFailedError`)[​](#deploy-transaction-failed-deploytxfailederror "Direct link to deploy-transaction-failed-deploytxfailederror") An error indicating that a contract deployment transaction failed. #### Properties[​](#properties-1 "Direct link to Properties") `finalizedTxData`: Finalization data of the failed deployment transaction. ### Call transaction failed (`CallTxFailedError`)[​](#call-transaction-failed-calltxfailederror "Direct link to call-transaction-failed-calltxfailederror") An error indicating that a contract call transaction failed. #### Properties[​](#properties-2 "Direct link to Properties") * `finalizedTxData`: Finalization data of the failed call transaction * `circuitId`: Circuit(s) used to build the transaction ### Replace maintenance authority transaction failed (`ReplaceMaintenanceAuthorityTxFailedError`)[​](#replace-maintenance-authority-transaction-failed-replacemaintenanceauthoritytxfailederror "Direct link to replace-maintenance-authority-transaction-failed-replacemaintenanceauthoritytxfailederror") An error indicating that a maintenance authority replacement transaction failed. #### Properties[​](#properties-3 "Direct link to Properties") `finalizedTxData`: Finalization data of the failed maintenance authority replacement transaction. ### Remove verifier key transaction failed (`RemoveVerifierKeyTxFailedError`)[​](#remove-verifier-key-transaction-failed-removeverifierkeytxfailederror "Direct link to remove-verifier-key-transaction-failed-removeverifierkeytxfailederror") An error indicating that a verifier key removal transaction failed. #### Properties[​](#properties-4 "Direct link to Properties") `finalizedTxData`: Finalization data of the failed verifier key removal transaction. ### Insert verifier key transaction failed (`InsertVerifierKeyTxFailedError`)[​](#insert-verifier-key-transaction-failed-insertverifierkeytxfailederror "Direct link to insert-verifier-key-transaction-failed-insertverifierkeytxfailederror") An error indicating that a verifier key insertion transaction failed. #### Properties[​](#properties-5 "Direct link to Properties") `finalizedTxData`: Finalization data of the failed verifier key insertion transaction. ## Contract errors[​](#contract-errors "Direct link to Contract errors") These errors occur when interacting with deployed contracts. ### Contract type error (`ContractTypeError`)[​](#contract-type-error-contracttypeerror "Direct link to contract-type-error-contracttypeerror") An error indicating that the expected contract type does not match the deployed contract state. #### Properties[​](#properties-6 "Direct link to Properties") * `contractState`: The deployed contract state * `circuitIds`: Undefined circuits or circuits with mismatched verifier keys ## Configuration errors[​](#configuration-errors "Direct link to Configuration errors") These errors indicate invalid or incomplete configuration when building transactions or querying contracts. ### Incomplete call transaction private state config (`IncompleteCallTxPrivateStateConfig`)[​](#incomplete-call-transaction-private-state-config-incompletecalltxprivatestateconfig "Direct link to incomplete-call-transaction-private-state-config-incompletecalltxprivatestateconfig") An error indicating that a call transaction specifies a `privateStateId` but does not provide a `privateStateProvider`. #### Properties[​](#properties-7 "Direct link to Properties") * `privateStateId`: The private state ID specified in the call transaction * `privateStateProvider`: The private state provider specified in the call transaction ### Incomplete find contract private state config (`IncompleteFindContractPrivateStateConfig`)[​](#incomplete-find-contract-private-state-config-incompletefindcontractprivatestateconfig "Direct link to incomplete-find-contract-private-state-config-incompletefindcontractprivatestateconfig") An error indicating that a contract lookup specifies an `initialPrivateState` but does not include a `privateStateId`. #### Properties[​](#properties-8 "Direct link to Properties") * `initialPrivateState`: The initial private state specified in the contract lookup * `privateStateId`: The private state ID specified in the contract lookup #### Message[​](#message "Direct link to Message") Here is the exact runtime message the client throws when this error occurs: ``` 'initialPrivateState' was defined for contract find while 'privateStateId' was undefined ``` ## State and identity errors[​](#state-and-identity-errors "Direct link to State and identity errors") These errors help prevent subtle bugs related to contract identity and cached state. ### Scoped transaction identity mismatch (`ScopedTransactionIdentityMismatchError`)[​](#scoped-transaction-identity-mismatch-scopedtransactionidentitymismatcherror "Direct link to scoped-transaction-identity-mismatch-scopedtransactionidentitymismatcherror") An error indicating that a scoped transaction attempts to reuse cached state with a different contract address or private state ID. #### Properties[​](#properties-9 "Direct link to Properties") * `cached`: The cached contract address and private state ID * `requested`: The requested contract address and private state ID ## Error handling[​](#error-handling "Direct link to Error handling") Use JavaScript's `try/catch` syntax and the `instanceof` operator to handle errors: ``` import { CallTxFailedError } from '@midnight-ntwrk/midnight-js-contracts'; try { await client.call(/* ... */); } catch (error) { if (error instanceof CallTxFailedError) { console.error('Transaction failed:', error.message); } else { console.error('Unexpected error:', error); } } ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Wallet SDK error reference All errors in the Midnight wallet SDK are Effect `Data.TaggedError` instances unless noted otherwise. To catch errors, use `Effect.catchTag` with the `_tag` field shown for each error. For union types, use `Effect.catchTags`. This reference highlights the error classes with details on how to catch and fix them. ## Node client (`@midnight-ntwrk/wallet-sdk-node-client`)[​](#node-client-midnight-ntwrkwallet-sdk-node-client "Direct link to node-client-midnight-ntwrkwallet-sdk-node-client") These seven errors form the `NodeClientError` union type. ### `SubmissionError`[​](#submissionerror "Direct link to submissionerror") An error indicating that transaction submission to the node failed. | Field | Value | | ------ | ------------------------------------------------------- | | `_tag` | `'SubmissionError'` | | Fields | `message: string`, `txData: unknown`, `cause?: unknown` | **Fix**: Inspect `message` and `cause` for the underlying reason. Check node connectivity and that the transaction format is correct. ``` Effect.catchTag('SubmissionError', (e) => ...) ``` ### `ConnectionError`[​](#connectionerror "Direct link to connectionerror") An error indicating a failed node connection through a WebSocket. | Field | Value | | ------ | ------------------- | | `_tag` | `'ConnectionError'` | **Known messages**: * `"Could not connect within specified time range (5s)"`: Node is unreachable or slow to respond * `"Failed to retrieve genesis transactions"`: Connected but genesis data unavailable **Fix**: Verify the node WebSocket URL is correct and the node is running. Increase connection timeout if the node is on a slow network. ``` Effect.catchTag('ConnectionError', (e) => ...) ``` ### `TransactionProgressError`[​](#transactionprogresserror "Direct link to transactionprogresserror") An error indicating that a submitted transaction did not reach the desired lifecycle stage within the expected time. | Field | Value | | ------ | ---------------------------- | | `_tag` | `'TransactionProgressError'` | **Known messages**: `"Transaction did not reach finality within expected time"` **Fix**: Check network congestion and node health. The transaction may still be in the mempool — query its status before resubmitting. ``` Effect.catchTag('TransactionProgressError', (e) => ...) ``` ### `ParseError`[​](#parseerror "Direct link to parseerror") An error indicating that the SDK could not parse a result returned by the node. | Field | Value | | ------ | -------------- | | `_tag` | `'ParseError'` | **Fix**: Usually indicates a protocol version mismatch between the SDK and the node. Check that SDK and node versions are compatible. ``` Effect.catchTag('ParseError', (e) => ...) ``` ### `TransactionUsurpedError`[​](#transactionusurpederror "Direct link to transactionusurpederror") An error indicating that another transaction replaced a transaction with the same discriminators. | Field | Value | | ------ | --------------------------- | | `_tag` | `'TransactionUsurpedError'` | **Fix**: The original transaction is no longer relevant. If an unexpected replacement occurred, then investigate which process submitted a conflicting transaction. ``` Effect.catchTag('TransactionUsurpedError', (e) => ...) ``` ### `TransactionDroppedError`[​](#transactiondroppederror "Direct link to transactiondroppederror") An error indicating that the node dropped a transaction, most likely because the mempool is full. | Field | Value | | ------ | --------------------------- | | `_tag` | `'TransactionDroppedError'` | **Fix**: Wait for the mempool to drain and resubmit. Consider increasing the transaction fee if the network supports fee prioritization. ``` Effect.catchTag('TransactionDroppedError', (e) => ...) ``` ### `TransactionInvalidError`[​](#transactioninvaliderror "Direct link to transactioninvaliderror") An error indicating that the node rejected a transaction as invalid. | Field | Value | | ------ | --------------------------- | | `_tag` | `'TransactionInvalidError'` | **Fix**: A malformed transaction or a validation-rule violation caused this error. Review the transaction construction logic. Do not resubmit without changes. ``` Effect.catchTag('TransactionInvalidError', (e) => ...) ``` ## Shielded wallet (`@midnight-ntwrk/wallet-sdk-shielded`)[​](#shielded-wallet-midnight-ntwrkwallet-sdk-shielded "Direct link to shielded-wallet-midnight-ntwrkwallet-sdk-shielded") The shielded wallet exposes 8 error types: ### `OtherWalletError`[​](#otherwalleterror "Direct link to otherwalleterror") Catch-all for wallet errors that do not fit a more specific category. | Field | Value | | ------ | ---------------- | | `_tag` | `'Wallet.Other'` | **Fix**: Inspect the error details. If this surfaces in production, then consider opening an issue with a reproduction case. ``` Effect.catchTag('Wallet.Other', (e) => ...) ``` ### `SyncWalletError`[​](#syncwalleterror "Direct link to syncwalleterror") An error indicating that a wallet sync with the Midnight blockchain failed. | Field | Value | | ------ | --------------- | | `_tag` | `'Wallet.Sync'` | **Fix**: Check connectivity to the node. Retry the sync operation. Persistent failures may indicate a corrupted local state. ``` Effect.catchTag('Wallet.Sync', (e) => ...) ``` ### `SubmissionWalletError`[​](#submissionwalleterror "Direct link to submissionwalleterror") A wrapper around submission errors that occur at the wallet layer (distinct from the node-client `SubmissionError`). | Field | Value | | ------ | -------------------------------- | | `_tag` | `'Wallet.SubmissionWalletError'` | **Fix**: Unwrap and inspect the underlying cause. Usually delegates to the node-client submission path. ``` Effect.catchTag('Wallet.SubmissionWalletError', (e) => ...) ``` ### `InsufficientFundsError`[​](#insufficientfundserror "Direct link to insufficientfundserror") An error indicating that the wallet does not hold enough tokens of the specified type to complete the operation. | Field | Value | | ------ | ------------------------------------- | | `_tag` | `'Wallet.InsufficientFunds'` | | Fields | `tokenType: string`, `amount: bigint` | **Fix**: Check the wallet balance for `tokenType` before constructing the transaction. Request a top-up or reduce the transfer amount. ``` Effect.catchTag('Wallet.InsufficientFunds', (e) => { console.log(`Need more ${e.tokenType}, shortfall: ${e.amount}`) }) ``` ### `AddressError`[​](#addresserror "Direct link to addresserror") An error indicating that the provided address is invalid. | Field | Value | | ------ | ------------------------- | | `_tag` | `'Wallet.Address'` | | Fields | `originalAddress: string` | **Fix**: Validate the address format before use. To understand the address format, see the [Address encoding](/sdks/official/wallet-developer-guide.md#address-encoding) section of the wallet SDK guide. The `originalAddress` field contains the rejected input. ``` Effect.catchTag('Wallet.Address', (e) => ...) ``` ### `InvalidCoinHashesError`[​](#invalidcoinhasheserror "Direct link to invalidcoinhasheserror") An error indicating that one or more coins are missing their required nonce hashes. | Field | Value | | ------ | ---------------------------- | | `_tag` | `'Wallet.InvalidCoinHashes'` | | Fields | `missingNonces: unknown[]` | **Fix**: Ensure coins are fully synced before spending. The `missingNonces` field identifies the affected coins. ``` Effect.catchTag('Wallet.InvalidCoinHashes', (e) => ...) ``` ### `TransactingError`[​](#transactingerror "Direct link to transactingerror") Error during transaction construction or fee balancing. | Field | Value | | ------ | ---------------------- | | `_tag` | `'Wallet.Transacting'` | **Fix**: Check that inputs are valid and that the fee token balance is sufficient. Review transaction parameters. ``` Effect.catchTag('Wallet.Transacting', (e) => ...) ``` ### `TransactionHistoryError`[​](#transactionhistoryerror "Direct link to transactionhistoryerror") Error reading or writing the transaction history store. | Field | Value | | ------ | ----------------------------- | | `_tag` | `'Wallet.TransactionHistory'` | **Fix**: Check local storage availability and permissions. A corrupt store history might be causing the error. Clearing and resyncing is a recovery option. ``` Effect.catchTag('Wallet.TransactionHistory', (e) => ...) ``` ## Unshielded wallet (`@midnight-ntwrk/wallet-sdk-unshielded-wallet`)[​](#unshielded-wallet-midnight-ntwrkwallet-sdk-unshielded-wallet "Direct link to unshielded-wallet-midnight-ntwrkwallet-sdk-unshielded-wallet") The unshielded wallet exposes eleven error types: all eight from the shielded wallet (same `_tag` values) plus five additional types below. ### `SignError`[​](#signerror "Direct link to signerror") Failed to sign a transaction. | Field | Value | | ------ | --------------- | | `_tag` | `'Wallet.Sign'` | **Fix**: Ensure the signing key is available and not locked. Check hardware wallet connectivity if applicable. ``` Effect.catchTag('Wallet.Sign', (e) => ...) ``` ### `ApplyTransactionError`[​](#applytransactionerror "Direct link to applytransactionerror") Failed to apply a transaction to the local UTXO set. | Field | Value | | ------ | --------------------------- | | `_tag` | `'Wallet.ApplyTransaction'` | **Fix**: Usually follows a submission error. Verify that the node accepted the transaction before attempting to apply it locally. ``` Effect.catchTag('Wallet.ApplyTransaction', (e) => ...) ``` ### `RollbackUtxoError`[​](#rollbackutxoerror "Direct link to rollbackutxoerror") Failed to roll back a UTXO during a chain reorganisation. | Field | Value | | ------ | ----------------------- | | `_tag` | `'Wallet.RollbackUtxo'` | **Fix**: If rollback fails repeatedly, then the local UTXO state might be inconsistent. If that happens, then you might need a full resync. ``` Effect.catchTag('Wallet.RollbackUtxo', (e) => ...) ``` ### `SpendUtxoError`[​](#spendutxoerror "Direct link to spendutxoerror") Failed to mark a UTXO as spent. | Field | Value | | ------ | -------------------- | | `_tag` | `'Wallet.SpendUtxo'` | **Fix**: The UTXO may already be spent or not present in the local set. To reconcile state, resync the wallet. ``` Effect.catchTag('Wallet.SpendUtxo', (e) => ...) ``` ### `UtxoNotFoundError`[​](#utxonotfounderror "Direct link to utxonotfounderror") A referenced UTXO could not be found in the local set. | Field | Value | | ------ | --------------------- | | `_tag` | `'UtxoNotFoundError'` | **Fix**: Ensure the wallet is fully synced. The UTXO might have already been spent or the sync might be behind the chain tip. ``` Effect.catchTag('UtxoNotFoundError', (e) => ...) ``` ## DUST wallet (`@midnight-ntwrk/wallet-sdk-dust-wallet`)[​](#dust-wallet-midnight-ntwrkwallet-sdk-dust-wallet "Direct link to dust-wallet-midnight-ntwrkwallet-sdk-dust-wallet") The DUST wallet exposes four error types, all shared with the shielded wallet: | Error | `_tag` | | ------------------------ | ---------------------------- | | `OtherWalletError` | `'Wallet.Other'` | | `SyncWalletError` | `'Wallet.Sync'` | | `TransactingError` | `'Wallet.Transacting'` | | `InsufficientFundsError` | `'Wallet.InsufficientFunds'` | For field details and fixes, see the [Shielded wallet](#shielded-wallet-midnight-ntwrkwallet-sdk-shielded) section. ## Capabilities (`@midnight-ntwrk/wallet-sdk-capabilities`)[​](#capabilities-midnight-ntwrkwallet-sdk-capabilities "Direct link to capabilities-midnight-ntwrkwallet-sdk-capabilities") The capabilities package exposes three error types. ### `ProvingError`[​](#provingerror "Direct link to provingerror") Wraps errors from the proving provider. | Field | Value | | ------ | ------------------ | | `_tag` | `'Wallet.Proving'` | **Fix**: Check proof server connectivity and that you are loading the correct circuit keys. Inspect the wrapped cause for the underlying provider error. ``` Effect.catchTag('Wallet.Proving', (e) => ...) ``` ### `SubmissionError` (Capabilities)[​](#submissionerror-capabilities "Direct link to submissionerror-capabilities") Submission error raised at the capabilities/service layer. | Field | Value | | ------ | ------------------- | | `_tag` | `'SubmissionError'` | **Fix**: Same as node-client `SubmissionError`. Check node connectivity and transaction validity. ``` Effect.catchTag('SubmissionError', (e) => ...) ``` ### `InsufficientFundsError` (Capabilities — native `Error`)[​](#insufficientfundserror-capabilities--native-error "Direct link to insufficientfundserror-capabilities--native-error") This is a plain JavaScript `Error`, *not* a `Data.TaggedError`. It is thrown (not yielded as an Effect failure) during coin selection. **Known messages**: `"Insufficient Funds: could not balance "` Where `` is the token identifier. **Fix**: Catch with standard `try/catch` or `Effect.tryPromise`. Ensure the wallet has enough of the specified token type before invoking coin selection. ## Utilities (`@midnight-ntwrk/wallet-sdk-utilities`)[​](#utilities-midnight-ntwrkwallet-sdk-utilities "Direct link to utilities-midnight-ntwrkwallet-sdk-utilities") The utilities package exposes five error types. ### `LedgerError`[​](#ledgererror "Direct link to ledgererror") Wraps exceptions thrown by the ledger WASM module. | Field | Value | | ------ | --------------- | | `_tag` | `'LedgerError'` | **Fix**: Inspect the wrapped cause. Usually indicates invalid state passed to the ledger. Check that ledger inputs are well-formed. ``` Effect.catchTag('LedgerError', (e) => ...) ``` ### `LeftError`[​](#lefterrorl "Direct link to lefterrorl") Raised when you encounter an `Either.Left` value where you expected a `Right`. | Field | Value | | ------ | ------------- | | `_tag` | `'LeftError'` | **Fix**: Check the logic that produces the `Either` value. A `Left` here indicates an unhandled error branch. ``` Effect.catchTag('LeftError', (e) => ...) ``` ### `InvalidProtocolSchemeError`[​](#invalidprotocolschemeerror "Direct link to invalidprotocolschemeerror") This error occurs when one or more of the network URLs provided uses an unsupported protocol scheme. | Field | Value | | ------ | ------------------------------ | | `_tag` | `'InvalidProtocolSchemeError'` | **Fix**: Ensure URLs use the expected scheme (for example, `ws://` or `wss://` for WebSocket connections, `http://` or `https://` for HTTP). ``` Effect.catchTag('InvalidProtocolSchemeError', (e) => ...) ``` ### `FailedToDeriveWebSocketUrlError`[​](#failedtoderivewebsocketurlerror "Direct link to failedtoderivewebsocketurlerror") This error occurs when the system cannot derive a WebSocket URL from the provided input. | Field | Value | | ------ | ----------------------------------- | | `_tag` | `'FailedToDeriveWebSocketUrlError'` | **Fix**: Check that the input URL is well-formed and that the derivation logic covers the provided scheme/host combination. ``` Effect.catchTag('FailedToDeriveWebSocketUrlError', (e) => ...) ``` ### `ClientError`[​](#clienterror "Direct link to clienterror") A client-side networking error, corresponding to HTTP 400–499 status codes. | Field | Value | | ------ | --------------- | | `_tag` | `'ClientError'` | **Fix**: These indicate a problem with the request, such as bad input, authentication failure, or not found. Do not retry without changing the request. Inspect the error for the specific status code. ``` Effect.catchTag('ClientError', (e) => ...) ``` ### `ServerError`[​](#servererror "Direct link to servererror") A server-side error, corresponding to HTTP 500+ status codes. | Field | Value | | ------ | --------------- | | `_tag` | `'ServerError'` | **Fix**: For persistent 500 errors, check server logs. The SDK automatically retries on transient 502–504 errors (gateway/service unavailable errors). ``` Effect.catchTag('ServerError', (e) => ...) ``` ## Runtime (`@midnight-ntwrk/wallet-sdk-runtime`)[​](#runtime-midnight-ntwrkwallet-sdk-runtime "Direct link to runtime-midnight-ntwrkwallet-sdk-runtime") The runtime package exposes one error type. ### `WalletRuntimeError`[​](#walletruntimeerror "Direct link to walletruntimeerror") A configuration error in the wallet runtime. | Field | Value | | ------ | ---------------------- | | `_tag` | `'WalletRuntimeError'` | **Known messages**: * `"No variant to init"`: No wallet variant was provided during initialisation * `"Empty variants list"`: The variants list supplied to the runtime is empty **Fix**: Ensure that you configure at least one wallet variant before you initialise the runtime. ``` Effect.catchTag('WalletRuntimeError', (e) => ...) ``` ## Address format (`@midnight-ntwrk/wallet-sdk-address-format`)[​](#address-format-midnight-ntwrkwallet-sdk-address-format "Direct link to address-format-midnight-ntwrkwallet-sdk-address-format") The address format package exposes five error types. These are plain JavaScript `Error` throws, not `Data.TaggedError` instances. Catch with standard `try/catch`. | Message | Cause | | ------------------------------------------------ | ------------------------------------------------------ | | `"Expected prefix mn"` | Address does not start with the `mn` prefix | | `"Segment contains disallowed characters"` | Address segment has characters outside the allowed set | | `"Expected type , got "` | Address type byte does not match the expected type | | `"Coin public key needs to be 32 bytes long"` | Public key component is the wrong length | | `"Unshielded address needs to be 32 bytes long"` | Unshielded address payload is the wrong length | | `"Dust address is too large"` | DUST address exceeds the maximum allowed size | **Fix**: Validate address strings before passing them to the address-format API. Use the shielded wallet's `AddressError` (`'Wallet.Address'`) for higher-level address validation. ## Complete tag registry[​](#complete-tag-registry "Direct link to Complete tag registry") All twenty-nine `_tag` values, alphabetically sorted | `_tag` | Package | Error type | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | | `'ClientError'` | `@midnight-ntwrk/wallet-sdk-utilities` | `ClientError` | | `'ConnectionError'` | `@midnight-ntwrk/wallet-sdk-node-client` | `ConnectionError` | | `'FailedToDeriveWebSocketUrlError'` | `@midnight-ntwrk/wallet-sdk-utilities` | `FailedToDeriveWebSocketUrlError` | | `'InvalidProtocolSchemeError'` | `@midnight-ntwrk/wallet-sdk-utilities` | `InvalidProtocolSchemeError` | | `'LeftError'` | `@midnight-ntwrk/wallet-sdk-utilities` | `LeftError` | | `'LedgerError'` | `@midnight-ntwrk/wallet-sdk-utilities` | `LedgerError` | | `'ParseError'` | `@midnight-ntwrk/wallet-sdk-node-client` | `ParseError` | | `'ServerError'` | `@midnight-ntwrk/wallet-sdk-utilities` | `ServerError` | | `'SubmissionError'` | `@midnight-ntwrk/wallet-sdk-node-client`, `@midnight-ntwrk/wallet-sdk-capabilities` | `SubmissionError` | | `'TransactionDroppedError'` | `@midnight-ntwrk/wallet-sdk-node-client` | `TransactionDroppedError` | | `'TransactionInvalidError'` | `@midnight-ntwrk/wallet-sdk-node-client` | `TransactionInvalidError` | | `'TransactionProgressError'` | `@midnight-ntwrk/wallet-sdk-node-client` | `TransactionProgressError` | | `'TransactionUsurpedError'` | `@midnight-ntwrk/wallet-sdk-node-client` | `TransactionUsurpedError` | | `'UtxoNotFoundError'` | `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `UtxoNotFoundError` | | `'Wallet.Address'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `AddressError` | | `'Wallet.ApplyTransaction'` | `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `ApplyTransactionError` | | `'Wallet.InsufficientFunds'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet`, `@midnight-ntwrk/wallet-sdk-dust-wallet` | `InsufficientFundsError` | | `'Wallet.InvalidCoinHashes'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `InvalidCoinHashesError` | | `'Wallet.Other'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet`, `@midnight-ntwrk/wallet-sdk-dust-wallet` | `OtherWalletError` | | `'Wallet.Proving'` | `@midnight-ntwrk/wallet-sdk-capabilities` | `ProvingError` | | `'Wallet.RollbackUtxo'` | `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `RollbackUtxoError` | | `'Wallet.Sign'` | `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `SignError` | | `'Wallet.SpendUtxo'` | `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `SpendUtxoError` | | `'Wallet.SubmissionWalletError'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `SubmissionError` (wallet) | | `'Wallet.Sync'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet`, `@midnight-ntwrk/wallet-sdk-dust-wallet` | `SyncWalletError` | | `'Wallet.Transacting'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet`, `@midnight-ntwrk/wallet-sdk-dust-wallet` | `TransactingError` | | `'Wallet.TransactionHistory'` | `@midnight-ntwrk/wallet-sdk-shielded`, `@midnight-ntwrk/wallet-sdk-unshielded-wallet` | `TransactionHistoryError` | | `'WalletRuntimeError'` | `@midnight-ntwrk/wallet-sdk-runtime` | `WalletRuntimeError` | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight.js Midnight.js provides tools for deploying and interacting with smart contracts, managing encrypted private state, generating zero-knowledge proofs, and submitting transactions to the Midnight network. This guide provides a comprehensive overview of the Midnight.js SDK, including its architecture, packages, and how to get started. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before using Midnight.js, ensure that you have: * [Node.js](https://nodejs.org/) version 22.x or higher installed. * [Docker](https://www.docker.com/) installed and running (required for the [proof server](/guides/run-proof-server.md)). ## Packages[​](#packages "Direct link to Packages") Midnight.js uses a modular architecture, with each package providing a specific functionality. ### Core[​](#core "Direct link to Core") The core packages provide the foundational functionality for the SDK. | Package | Purpose | | ---------------------------------------- | ----------------------------------------------------------------- | | `@midnight-ntwrk/midnight-js-types` | Shared types, interfaces, and provider contracts | | `@midnight-ntwrk/midnight-js-contracts` | Contract deployment, circuit calls, and transaction submission | | `@midnight-ntwrk/midnight-js-network-id` | Network identifier configuration for runtime and ledger WASM APIs | | `@midnight-ntwrk/midnight-js-utils` | Shared utilities (hex encoding, bech32m, assertions) | ### Providers[​](#providers "Direct link to Providers") The provider packages includes functionality for proof generation, private state management, and public data queries. | Package | Purpose | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `@midnight-ntwrk/midnight-js-indexer-public-data-provider` | GraphQL-based blockchain data provider (queries and subscriptions) | | `@midnight-ntwrk/midnight-js-level-private-state-provider` | AES-256-GCM encrypted persistent state storage via [LevelDB](https://github.com/Level/level) | | `@midnight-ntwrk/midnight-js-http-client-proof-provider` | HTTP client for the Midnight proof server | | `@midnight-ntwrk/midnight-js-fetch-zk-config-provider` | Browser-compatible zero-knowledge artifact provider using the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | | `@midnight-ntwrk/midnight-js-node-zk-config-provider` | Node.js filesystem-based ZK artifact provider | | `@midnight-ntwrk/midnight-js-logger-provider` | Application-specific [Pino](https://github.com/pinojs/pino) logger configuration | ### Tooling[​](#tooling "Direct link to Tooling") The tooling packages provide tools for compiling Compact smart contracts. | Package | Purpose | | ------------------------------------- | ------------------------------------------------- | | `@midnight-ntwrk/midnight-js-compact` | Compact compiler manager for contract compilation | ## Installation[​](#installation "Direct link to Installation") To install the barrel package that provides a single entry point for the SDK. * npm * yarn ``` npm install @midnight-ntwrk/midnight-js ``` ``` yarn add @midnight-ntwrk/midnight-js ``` To install the individual packages: * npm * yarn ``` npm install @midnight-ntwrk/midnight-js-types npm install @midnight-ntwrk/midnight-js-contracts npm install @midnight-ntwrk/midnight-js-network-id npm install @midnight-ntwrk/midnight-js-utils npm install @midnight-ntwrk/midnight-js-indexer-public-data-provider npm install @midnight-ntwrk/midnight-js-level-private-state-provider npm install @midnight-ntwrk/midnight-js-http-client-proof-provider npm install @midnight-ntwrk/midnight-js-fetch-zk-config-provider npm install @midnight-ntwrk/midnight-js-node-zk-config-provider npm install @midnight-ntwrk/midnight-js-logger-provider npm install @midnight-ntwrk/ledger-v8 ``` ``` yarn add @midnight-ntwrk/midnight-js-types yarn add @midnight-ntwrk/midnight-js-contracts yarn add @midnight-ntwrk/midnight-js-network-id yarn add @midnight-ntwrk/midnight-js-utils yarn add @midnight-ntwrk/midnight-js-indexer-public-data-provider yarn add @midnight-ntwrk/midnight-js-level-private-state-provider yarn add @midnight-ntwrk/midnight-js-http-client-proof-provider yarn add @midnight-ntwrk/midnight-js-fetch-zk-config-provider yarn add @midnight-ntwrk/midnight-js-node-zk-config-provider yarn add @midnight-ntwrk/midnight-js-logger-provider yarn add @midnight-ntwrk/ledger-v8 ``` important Always refers to the [Compatibility matrix](/relnotes/support-matrix.md) to know which version of the SDK works with other components of the Midnight Network. ## Configure the network[​](#configure-the-network "Direct link to Configure the network") The network ID sets the network identifier for the SDK. To perform operations on the Midnight Network, you need to set the appropriate network ID. Other Midnight.js libraries and components use this network ID to execute operations on the network. * preprod * undeployed ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('preprod'); export const CONFIG = { indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preprod.midnight.network', proofServer: 'http://127.0.0.1:6300', }; ``` ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('undeployed'); export const CONFIG = { indexer: 'http://localhost:8088/api/v4/graphql', indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', node: 'ws://localhost:9944', proofServer: 'http://localhost:6300', }; ``` note The undeployed network is a local network that is not deployed to the blockchain. It is used for testing and development purposes. For more information, see [Running a local network](/guides/networks-and-environments.md#running-a-local-network). Available networks include: | Network | Network ID | | ---------- | ------------ | | Mainnet | `mainnet` | | Preview | `preview` | | Preprod | `preprod` | | Undeployed | `undeployed` | For Node.js environments, enable WebSocket for GraphQL subscriptions: ``` import { WebSocket } from 'ws'; globalThis.WebSocket = WebSocket; ``` ## Configure providers[​](#configure-providers "Direct link to Configure providers") Providers are modular, pluggable components that each handle a specific capability required for transaction construction and submission to the Midnight blockchain. ``` import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { FetchZkConfigProvider } from '@midnight-ntwrk/midnight-js-fetch-zk-config-provider'; import * as ledger from '@midnight-ntwrk/ledger-v8'; const zkConfigProvider = new FetchZkConfigProvider(zkArtifactsUrl); const providers: MidnightProviders = { privateStateProvider: levelPrivateStateProvider({ privateStoragePasswordProvider: () => password, accountId: walletAddress, }), publicDataProvider: indexerPublicDataProvider(queryUrl, subscriptionUrl), zkConfigProvider, proofProvider: httpClientProofProvider(proofServerUrl, zkConfigProvider), walletProvider, // from @midnight-ntwrk/wallet-sdk-facade midnightProvider, // from @midnight-ntwrk/wallet-sdk-facade }; ``` info The `walletProvider` and `midnightProvider` handle transaction balancing and submission to the blockchain. The Wallet SDK package provides them. For more information, see the [Wallet SDK](/sdks/official/wallet-developer-guide.md) guide. You can either use the `FetchZkConfigProvider` or the `NodeZkConfigProvider` to provide the ZK configuration for the proof provider. ### Fetch ZK configuration provider[​](#fetch-zk-configuration-provider "Direct link to Fetch ZK configuration provider") ZK configuration provider that retrieves proving keys, verifier keys, and ZK intermediate representation over HTTP/HTTPS. Here is an example using the `FetchZkConfigProvider` method: ``` import { FetchZkConfigProvider } from '@midnight-ntwrk/midnight-js-fetch-zk-config-provider'; const zkConfigProvider = new FetchZkConfigProvider('https://example.com/zk-artifacts'); const proverKey = await zkConfigProvider.getProverKey('myCircuit'); const verifierKey = await zkConfigProvider.getVerifierKey('myCircuit'); const zkir = await zkConfigProvider.getZKIR('myCircuit'); ``` ### Node ZK configuration provider[​](#node-zk-configuration-provider "Direct link to Node ZK configuration provider") ZK configuration provider that retrieves proving keys, verifier keys, and ZK intermediate representation from the file system. Here is an example using the `NodeZkConfigProvider` method: ``` import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; const zkConfigProvider = new NodeZkConfigProvider('/path/to/zk-artifacts'); const proverKey = await zkConfigProvider.getProverKey('myCircuit'); const verifierKey = await zkConfigProvider.getVerifierKey('myCircuit'); const zkir = await zkConfigProvider.getZKIR('myCircuit'); ``` ### DApp Connector proof provider[​](#dapp-connector-proof-provider "Direct link to DApp Connector proof provider") Proof provider implementation that delegates zero-knowledge proof generation to a DApp Connector wallet. Use this when your DApp runs in a browser and the user's wallet handles proving. Install the `@midnight-ntwrk/dapp-connector-proof-provider` package: ``` npm install @midnight-ntwrk/dapp-connector-proof-provider ``` Use the `dappConnectorProofProvider` function to create a proof provider: ``` import { dappConnectorProofProvider } from '@midnight-ntwrk/midnight-js-dapp-connector-proof-provider'; const proofProvider = await dappConnectorProofProvider( walletConnectedAPI, zkConfigProvider, costModel ); const provenTx = await proofProvider.proveTx(unprovenTx); ``` The `dappConnectorProofProvider` function takes the following *required* parameters: * `walletConnectedAPI`: DApp Connector wallet API with proving capabilities * `zkConfigProvider`: Provider for ZK configuration artifacts * `costModel`: Cost model for transaction proving note The DApp Connector API handles the wallet connection and provides the `walletConnectedAPI` parameter. For more information, see the [DApp Connector](/api-reference/dapp-connector.md) API reference. ## Deploy a smart contract[​](#deploy-a-smart-contract "Direct link to Deploy a smart contract") The `deployContract` method deploys a smart contract to the blockchain. It takes the following parameters: * `providers`: The providers object. * `compiledContract`: The compiled contract. * `privateStateId`: The private state ID. * `initialPrivateState`: The initial private state. ``` import { deployContract } from '@midnight-ntwrk/midnight-js-contracts'; const deployed = await deployContract(providers, { compiledContract, privateStateId: 'my-state', initialPrivateState: { counter: 0n }, }); ``` The `deployContact` method returns a `deployedContract` promise. This object contains the contract address and the private state ID. ``` const contractAddress = deployed.deployTxData.public.contractAddress; console.log(`Contract Address: ${contractAddress}`); ``` ## Interact with the contract[​](#interact-with-the-contract "Direct link to Interact with the contract") To interact with the contract, use the `findDeployedContract` method to get the deployed contract object. ``` import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; const contract = await findDeployedContract(providers, { contractAddress: contractAddress, compiledContract, privateStateId: 'my-state', initialPrivateState: {}, }); ``` This method takes the following parameters: * `providers`: The providers object. * Options containing the following properties: * `contractAddress`: The contract address * `compiledContract`: The compiled contract * `privateStateId`: The private state ID * `initialPrivateState`: The initial private state After initializing the contract object, you can call circuits from your smart contract using the `callTx` property. ``` const transaction = await contract.callTx.someCircuit(circuitArguments); ``` This operation creates a new transaction and submits it to the blockchain. To access the transaction details: ``` const transaction = await contract.callTx.someCircuit(circuitArguments); console.log('Transaction ID:', transaction.public.txId); console.log(`Block: ${transaction.public.blockHeight}\n`); ``` ## Transaction submission[​](#transaction-submission "Direct link to Transaction submission") When you already have transaction payloads or options objects prepared, these helpers submit call, deploy, or generic transactions through the configured providers. This is useful for explicit submission flows outside the `contract.callTx.*` convenience methods. ``` import { submitCallTx, submitDeployTx, submitTx } from '@midnight-ntwrk/midnight-js-contracts'; // Submit a call transaction await submitCallTx(providers, callOptions); // Submit a deploy transaction await submitDeployTx(providers, deployOptions); // Generic transaction submission await submitTx(providers, txData); ``` ## Query state[​](#query-state "Direct link to Query state") After deploying a smart contract, you can query the private and public states of the contract using the `getStates` and `getPublicStates` methods. ``` import { getStates, getPublicStates } from '@midnight-ntwrk/midnight-js-contracts'; const states = await getStates(providers, contractAddress, privateStateId); const publicStates = await getPublicStates(providers, contractAddress); ``` The `getStates` method retrieves the Zswap, ledger, and private states of the deployed smart contract corresponding to the given identifier using the given providers. It accepts the following parameters: * `providers`: The providers object. * `contractAddress`: The contract address. * `privateStateId`: The private state ID. The `getPublicStates` method fetches only the public visible (Zswap and ledger) states of a deployed smart contract. It accepts the following parameters: * `providers`: The providers object. * `contractAddress`: The contract address. To get the unshielded balance of the contract, use the `getUnshieldedBalances` method passing the providers and contract address as parameters. ``` const balances = await getUnshieldedBalances(providers, contractAddress); console.log('Unshielded Balances:', balances); ``` ## Key concepts[​](#key-concepts "Direct link to Key concepts") These concepts are important to understand the Midnight.js SDK and how it works. ### Contract model[​](#contract-model "Direct link to Contract model") The contract model uses the following terminology: * **Circuit**: Smart contract function that executes locally and generates a zero-knowledge proof. * **Witness**: Private computation that runs on the end-user's device. * **Private state**: User-local state updated by circuits — never stored on-chain. * **Ledger state**: On-chain public contract state. ### ZK artifacts[​](#zk-artifacts "Direct link to ZK artifacts") ZK artifacts are the files generated by the Compact compiler to create zero-knowledge proofs. It includes the following files: * **Prover key**: Binary used to create zero-knowledge proofs. * **Verifier key**: Binary used for on-chain proof verification. * **ZKIR**: Zero-Knowledge Intermediate Representation of compiled contracts. ### Transaction flow[​](#transaction-flow "Direct link to Transaction flow") Submitting a contract interaction runs locally first (producing an unproven transaction), then uses the typed providers to prove, balance, and broadcast the transaction on the network. The diagram below summarizes that sequence. ### Transaction status[​](#transaction-status "Direct link to Transaction status") Transactions can have the following statuses: * `SucceedEntirely`: All transaction segments succeeded. * `FailFallible`: Guaranteed portion succeeded, fallible portion failed. * `FailEntirely`: Transaction is invalid. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight wallet SDK The Midnight wallet SDK provides a comprehensive TypeScript implementation for managing wallets on the Midnight Network. It supports the three-token system that powers Midnight: * **Unshielded tokens**: NIGHT and other unshielded tokens * **Shielded tokens**: Shielded tokens with zero-knowledge proofs * **DUST**: DUST for transaction fees This guide covers how to use the wallet SDK to manage wallets on the Midnight Network. ## Packages[​](#packages "Direct link to Packages") The Midnight wallet SDK provides a modular architecture with specialized packages for each operation. It consists of the following packages: | Package | Purpose | | --------------------------------------------- | ----------------------------------------- | | `@midnightntwrk/wallet-sdk-facade` | Unified API for all wallet operations | | `@midnightntwrk/wallet-sdk-unshielded-wallet` | Manages NIGHT and unshielded tokens | | `@midnightntwrk/wallet-sdk-shielded` | Manages shielded tokens with ZK proofs | | `@midnightntwrk/wallet-sdk-dust-wallet` | Manages DUST for transaction fees | | `@midnightntwrk/wallet-sdk-hd` | Hierarchical deterministic key derivation | | `@midnightntwrk/wallet-sdk-address-format` | Bech32m address encoding and decoding | | `@midnightntwrk/wallet-sdk-node-client` | Communicates with Midnight nodes | | `@midnightntwrk/wallet-sdk-indexer-client` | Queries the Midnight indexer | | `@midnightntwrk/wallet-sdk-prover-client` | Interfaces with the proving server | For complete package details, see the [wallet SDK release notes](/relnotes/wallet.md). ## Installation[​](#installation "Direct link to Installation") Install the wallet SDK using your preferred package manager: * npm * yarn ``` npm install @midnightntwrk/wallet-sdk-facade@VERSION \ @midnightntwrk/wallet-sdk-hd@VERSION \ @midnightntwrk/wallet-sdk-address-format@VERSION \ @midnightntwrk/wallet-sdk-unshielded-wallet@VERSION \ @midnightntwrk/wallet-sdk-shielded@VERSION \ @midnightntwrk/wallet-sdk-dust-wallet@VERSION \ @midnight-ntwrk/ledger-v8 ``` ``` yarn add @midnightntwrk/wallet-sdk-facade@VERSION \ @midnightntwrk/wallet-sdk-hd@VERSION \ @midnightntwrk/wallet-sdk-address-format@VERSION \ @midnightntwrk/wallet-sdk-unshielded-wallet@VERSION \ @midnightntwrk/wallet-sdk-shielded@VERSION \ @midnightntwrk/wallet-sdk-dust-wallet@VERSION \ @midnight-ntwrk/ledger-v8 ``` Replace `VERSION` with the compatible version of the wallet SDK packages as defined in the [release compatibility matrix](/relnotes/support-matrix.md). ## Wallet architecture[​](#wallet-architecture "Direct link to Wallet architecture") The Wallet SDK uses a three-wallet architecture corresponding to Midnight's token model: * **WalletFacade**: Unified interface that coordinates all three wallet types * **UnshieldedWallet**: Manages NIGHT and other unshielded tokens using UTxO model * **ShieldedWallet**: Manages privacy-preserving shielded tokens using ZK proofs * **DustWallet**: Manages DUST for paying transaction fees ## Derive wallet keys[​](#derive-wallet-keys "Direct link to Derive wallet keys") The Wallet SDK uses hierarchical deterministic (HD) key derivation following BIP-32/BIP-44/CIP-1852 standards. All three wallet types derive keys from a single seed. ### Derivation path[​](#derivation-path "Direct link to Derivation path") The SDK follows this derivation path: ``` m / 44' / 2400' / account' / role / index ``` Path components: * `account`: Account index, typically 0 for the first account * `role`: Wallet type identifier that determines the key's purpose: * `0` (Roles.NightExternal): Unshielded operations * `2` (Roles.Dust): DUST token operations * `3` (Roles.Zswap): Shielded operations * `index`: Address index, typically 0 for the primary address ### Derive keys from a seed[​](#derive-keys-from-a-seed "Direct link to Derive keys from a seed") This example shows how to derive all three key types (unshielded, shielded, and DUST) from a single master seed. The function handles edge cases where key derivation might fail and automatically retries with the next index as specified in the BIP-44 standard. ``` import * as ledger from '@midnight-ntwrk/ledger-v8'; import type { Role } from '@midnightntwrk/wallet-sdk-hd'; import { AccountKey, HDWallet, Roles } from '@midnightntwrk/wallet-sdk-hd'; import { Buffer } from 'buffer'; function deriveRoleKey(accountKey: AccountKey, role: Role, addressIndex: number = 0): Buffer { const result = accountKey.selectRole(role).deriveKeyAt(addressIndex); if (result.type === 'keyDerived') { return Buffer.from(result.key); } // There is small possibility of the derivation failing, so we retry with the next index as specified return deriveRoleKey(accountKey, role, addressIndex + 1); } function deriveAllKeys(seed: Uint8Array) { const hdWallet = HDWallet.fromSeed(seed); if (hdWallet.type !== 'seedOk') { throw new Error('Failed to derive keys'); } const account = hdWallet.hdWallet.selectAccount(0); const shieldedSeed = deriveRoleKey(account, Roles.Zswap); const dustSeed = deriveRoleKey(account, Roles.Dust); const unshieldedKey = deriveRoleKey(account, Roles.NightExternal); hdWallet.hdWallet.clear(); // Clear the HDWallet to avoid holding the private key in memory for longer than needed return { shielded: { seed: shieldedSeed, keys: ledger.ZswapSecretKeys.fromSeed(shieldedSeed) }, dust: { seed: dustSeed, key: ledger.DustSecretKey.fromSeed(dustSeed) }, unshielded: unshieldedKey, }; } ``` ### Example usage[​](#example-usage "Direct link to Example usage") This example shows how to derive all three key types (unshielded, shielded, and DUST) from a single master seed. ``` const seed = Buffer.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex' ); const derivedKeys = deriveAllKeys(seed); // Clear the seed from memory after use seed.fill(0); console.log('Derived keys successfully'); console.log('Unshielded (Night) secret key:', derivedKeys.unshielded.toString('hex')); console.log('Shielded seed:', derivedKeys.shielded.seed.toString('hex')); console.log('DUST seed:', derivedKeys.dust.seed.toString('hex')); ``` Security Always clear the HD wallet after key derivation to avoid keeping the seed in memory longer than necessary. ## Initialize the wallet[​](#initialize-the-wallet "Direct link to Initialize the wallet") The `WalletFacade` provides a unified interface for all wallet operations. Initialize it with configuration and wallet-specific secret keys. ### Configuration[​](#configuration "Direct link to Configuration") Before initializing the wallet, create a configuration object that specifies network endpoints, cost parameters, and transaction history storage. The configuration differs depending on whether you connect to the hosted Preprod testnet or a local undeployed development network. * Preprod * Undeployed ``` import { type DefaultConfiguration } from '@midnightntwrk/wallet-sdk-facade'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk-unshielded-wallet'; const configuration: DefaultConfiguration = { networkId: 'preprod', costParameters: { feeBlocksMargin: 5, }, relayURL: new URL('wss://rpc.preprod.midnight.network'), provingServerUrl: new URL('http://localhost:6300'), indexerClientConnection: { indexerHttpUrl: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWsUrl: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', }, txHistoryStorage: new InMemoryTransactionHistoryStorage(), }; ``` ``` import { type DefaultConfiguration } from '@midnightntwrk/wallet-sdk-facade'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk-unshielded-wallet'; const INDEXER_PORT = Number.parseInt(process.env['INDEXER_PORT'] ?? '8088', 10); const NODE_PORT = Number.parseInt(process.env['NODE_PORT'] ?? '9944', 10); const PROOF_SERVER_PORT = Number.parseInt(process.env['PROOF_SERVER_PORT'] ?? '6300', 10); const INDEXER_HTTP_URL = `http://localhost:${INDEXER_PORT}/api/v4/graphql`; const INDEXER_WS_URL = `ws://localhost:${INDEXER_PORT}/api/v4/graphql/ws`; const configuration: DefaultConfiguration = { networkId: 'undeployed', costParameters: { feeBlocksMargin: 5, }, relayURL: new URL(`ws://localhost:${NODE_PORT}`), provingServerUrl: new URL(`http://localhost:${PROOF_SERVER_PORT}`), indexerClientConnection: { indexerHttpUrl: INDEXER_HTTP_URL, indexerWsUrl: INDEXER_WS_URL, }, txHistoryStorage: new InMemoryTransactionHistoryStorage(), }; ``` ### Complete initialization[​](#complete-initialization "Direct link to Complete initialization") This example demonstrates the complete wallet initialization process, including key derivation, keystore creation, and starting all three wallet types. The initialization pattern ensures proper key management and wallet setup before network synchronization begins. ``` import * as ledger from '@midnight-ntwrk/ledger-v8'; import { DustWallet } from '@midnightntwrk/wallet-sdk-dust-wallet'; import { WalletFacade } from '@midnightntwrk/wallet-sdk-facade'; import { ShieldedWallet } from '@midnightntwrk/wallet-sdk-shielded'; import { createKeystore, PublicKey, UnshieldedWallet, } from '@midnightntwrk/wallet-sdk-unshielded-wallet'; async function initWallet(seed: Buffer) { // Derive keys const derivedKeys = deriveAllKeys(seed); const unshieldedKeystore = createKeystore( derivedKeys.unshielded, configuration.networkId ); // Initialize wallet facade const wallet = await WalletFacade.init({ configuration, shielded: (config) => ShieldedWallet(config).startWithSecretKeys(derivedKeys.shielded.keys), unshielded: (config) => UnshieldedWallet(config).startWithPublicKey( PublicKey.fromKeyStore(unshieldedKeystore) ), dust: (config) => DustWallet(config).startWithSecretKey( derivedKeys.dust.key, ledger.LedgerParameters.initialParameters().dust ), }); await wallet.start(derivedKeys.shielded.keys, derivedKeys.dust.key); return { wallet, derivedKeys, unshieldedKeystore }; } ``` For the complete example, see the [initialization snippet](https://github.com/midnightntwrk/midnight-wallet/blob/main/packages/docs-snippets/src/snippets/initialization.ts). ## Wallet state[​](#wallet-state "Direct link to Wallet state") The wallet exposes an observable state that updates as the blockchain synchronizes. ### Access wallet state[​](#access-wallet-state "Direct link to Access wallet state") The wallet provides methods to access both the current state snapshot and subscribe to state changes over time. Use `waitForSyncedState()` to wait until the wallet finishes its initial synchronization with the blockchain before performing operations. ``` import * as rx from 'rxjs'; // Wait for initial sync const syncedState = await wallet.waitForSyncedState(); console.log('Shielded balance:', syncedState.shielded.balances); console.log('Unshielded balance:', syncedState.unshielded.balances); console.log('DUST balance:', syncedState.dust.totalCoins); // Subscribe to state changes wallet.state().subscribe((state) => { if (state.isSynced) { console.log('Wallet is synced'); console.log('Shielded coins:', state.shielded.availableCoins.length); console.log('Unshielded UTxOs:', state.unshielded.availableCoins.length); } }); ``` ### Wallet state structure[​](#wallet-state-structure "Direct link to Wallet state structure") The wallet state includes: * **Balances**: Token amounts grouped by token type * **Available coins**: Coins ready to spend * **Pending coins**: Coins waiting for confirmation * **Progress**: Synchronization status * **Addresses**: Bech32m-encoded addresses for each wallet type ## Address encoding[​](#address-encoding "Direct link to Address encoding") Midnight uses Bech32m format for all addresses. The SDK provides utilities for encoding and decoding addresses. ### Address types[​](#address-types "Direct link to Address types") Midnight supports three address types: | Prefix | Type | Description | | ---------------- | ---------- | ------------------------------------------------- | | `mn_addr` | Unshielded | Payment addresses for NIGHT and unshielded tokens | | `mn_shield-addr` | Shielded | Payment addresses for shielded tokens | | `mn_dust` | DUST | Addresses for DUST generation | Each prefix includes a network identifier: * **Mainnet**: no suffix (for example, `mn_addr`) * **Preprod**: `_preprod` suffix (for example, `mn_addr_preprod`) * **Preview**: `_preview` suffix * **Undeployed**: `_undeployed` suffix ### Encode addresses[​](#encode-addresses "Direct link to Encode addresses") Encoding converts raw public keys and addresses into human-readable Bech32m format. The encoded addresses include the network identifier and are suitable for sharing with users or displaying in user interfaces. Each wallet type requires different encoding based on its key structure. ``` import { MidnightBech32m, UnshieldedAddress, ShieldedAddress, DustAddress, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey, } from '@midnightntwrk/wallet-sdk-address-format'; import * as ledger from '@midnight-ntwrk/ledger-v8'; const networkId = 'preprod'; // Encode unshielded address const verifyingKey = ledger.signatureVerifyingKey(unshieldedSecretKey.toString('hex')); const unshieldedAddress = new UnshieldedAddress( Buffer.from(ledger.addressFromKey(verifyingKey), 'hex') ); const unshieldedBech32m = MidnightBech32m.encode(networkId, unshieldedAddress).toString(); // Encode shielded address const shieldedKeys = ledger.ZswapSecretKeys.fromSeed(shieldedSeed); const shieldedAddress = new ShieldedAddress( new ShieldedCoinPublicKey(Buffer.from(shieldedKeys.coinPublicKey, 'hex')), new ShieldedEncryptionPublicKey(Buffer.from(shieldedKeys.encryptionPublicKey, 'hex')) ); const shieldedBech32m = MidnightBech32m.encode(networkId, shieldedAddress).toString(); // Encode dust address const dustSecretKey = ledger.DustSecretKey.fromSeed(dustSeed); const dustAddress = new DustAddress(dustSecretKey.publicKey); const dustBech32m = MidnightBech32m.encode(networkId, dustAddress).toString(); ``` ### Decode addresses[​](#decode-addresses "Direct link to Decode addresses") Decoding converts Bech32m-formatted addresses back into their raw byte representations. This is necessary when you need to extract the underlying public keys or address bytes for cryptographic operations, transaction building, or verification. The decode process validates the address format and network identifier. ``` // Parse and decode unshielded address const parsedUnshielded = MidnightBech32m.parse(unshieldedBech32m); const decodedUnshielded = parsedUnshielded.decode(UnshieldedAddress, networkId); // Parse and decode shielded address const parsedShielded = MidnightBech32m.parse(shieldedBech32m); const decodedShielded = parsedShielded.decode(ShieldedAddress, networkId); ``` For complete address examples, see the [addresses snippet](https://github.com/midnightntwrk/midnight-wallet/blob/main/packages/docs-snippets/src/snippets/addresses.no-net.ts). ## Make transfers[​](#make-transfers "Direct link to Make transfers") The wallet provides high-level methods for transferring tokens. The following examples assume you have initialized the wallet and derived the necessary keys as shown in the [Initialize the wallet](#initialize-the-wallet) section. ### Unshielded transfers[​](#unshielded-transfers "Direct link to Unshielded transfers") Unshielded transfers move NIGHT or other unshielded tokens between addresses using standard UTxO-based transactions. These transfers are visible on the blockchain and require signing with the unshielded secret key. ``` import * as ledger from '@midnight-ntwrk/ledger-v8'; await wallet .transferTransaction( [ { type: 'unshielded', outputs: [ { amount: 1_000_000n, receiverAddress: await receiverWallet.unshielded.getAddress(), type: ledger.unshieldedToken().raw, }, ], }, ], { shieldedSecretKeys, dustSecretKey, }, { ttl: new Date(Date.now() + 30 * 60 * 1000), } ) .then((recipe) => wallet.signRecipe(recipe, (payload) => keystore.signData(payload))) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` Unshielded transfers require signing with the unshielded secret key since they involve UTxO-based transactions with Schnorr signatures. ### Shielded transfers[​](#shielded-transfers "Direct link to Shielded transfers") Shielded transfers move tokens privately using zero-knowledge proofs. These transfers hide transaction amounts and participant identities from observers while still maintaining verifiable correctness. Unlike unshielded transfers, they do not require unshielded signature operations. ``` await wallet .transferTransaction( [ { type: 'shielded', outputs: [ { amount: 1_000_000n, receiverAddress: await receiverWallet.shielded.getAddress(), type: ledger.shieldedToken().raw, }, ], }, ], { shieldedSecretKeys, dustSecretKey, }, { ttl: new Date(Date.now() + 30 * 60 * 1000), } ) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` note Shielded transfers do not require unshielded signatures since all operations are proven with zero-knowledge proofs. ### Combined transfers[​](#combined-transfers "Direct link to Combined transfers") The wallet supports atomic transactions that combine both unshielded and shielded token transfers. This allows you to move different token types in a single operation, reducing transaction overhead and ensuring both transfers complete together or not at all. ``` await wallet .transferTransaction( [ { type: 'unshielded', outputs: [ { amount: 1_000_000n, receiverAddress: await receiverWallet.unshielded.getAddress(), type: ledger.unshieldedToken().raw, }, ], }, { type: 'shielded', outputs: [ { amount: 1_000_000n, receiverAddress: await receiverWallet.shielded.getAddress(), type: ledger.shieldedToken().raw, }, ], }, ], { shieldedSecretKeys, dustSecretKey, }, { ttl: new Date(Date.now() + 30 * 60 * 1000), } ) .then((recipe) => wallet.signRecipe(recipe, (payload) => keystore.signData(payload))) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` ## Balance transactions[​](#balance-transactions "Direct link to Balance transactions") Transaction balancing automatically provides inputs to cover outputs and fees. The wallet supports balancing at different stages of transaction construction. The following examples assume you have an initialized wallet with the necessary secret keys. ### Balance an unproven transaction[​](#balance-an-unproven-transaction "Direct link to Balance an unproven transaction") Balancing an unproven transaction selects appropriate inputs to cover the specified outputs and transaction fees. This operation must occur before zero-knowledge proof generation, allowing the wallet to determine the complete set of inputs required. The example below assumes you have created a transaction intent specifying the desired outputs. ``` const unprovenTx = ledger.Transaction.fromParts( 'preprod', undefined, undefined, intent ); const balancedRecipe = await wallet.balanceUnprovenTransaction( unprovenTx, { shieldedSecretKeys, dustSecretKey, }, { ttl: new Date(Date.now() + 30 * 60 * 1000), } ); ``` ### Balance a finalized transaction[​](#balance-a-finalized-transaction "Direct link to Balance a finalized transaction") Balancing a finalized transaction adds inputs to a transaction that already contains zero-knowledge proofs. This is particularly useful for DUST sponsorship scenarios where a separate party pays transaction fees. The `tokenKindsToBalance` parameter controls which token types to balance. ``` const finalizedRecipe = await wallet.balanceFinalizedTransaction( finalizedTx, { shieldedSecretKeys, dustSecretKey, }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['dust'], // Only balance DUST for fees } ); ``` ## Manage DUST[​](#manage-dust "Direct link to Manage DUST") DUST is generated from registered NIGHT holdings and is required to pay transaction fees. The following examples assume you have an initialized wallet with an unshielded keystore and the necessary secret keys. ### Register NIGHT for DUST generation[​](#register-night-for-dust-generation "Direct link to Register NIGHT for DUST generation") Registration designates unshielded NIGHT coins to generate DUST tokens over time. Once registered, these coins continuously produce DUST that accumulates in your DUST wallet. The registered NIGHT remains in your unshielded wallet and can be deregistered later. ``` const { unshielded } = await wallet.waitForSyncedState(); await wallet .registerNightUtxosForDustGeneration( unshielded.availableCoins, unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signData(payload) ) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` info DUST generation begins automatically once NIGHT is registered. You must wait for the blockchain to process the registration before DUST appears in your wallet. ### Deregister NIGHT from DUST generation[​](#deregister-night-from-dust-generation "Direct link to Deregister NIGHT from DUST generation") Deregistration stops DUST generation from previously registered NIGHT coins. This operation requires DUST to pay the transaction fee, so you must balance the transaction with `tokenKindsToBalance: ['dust']` after creating the deregistration recipe. ``` const { unshielded } = await wallet.waitForSyncedState(); await wallet .deregisterFromDustGeneration( [unshielded.availableCoins[0]], // Deregister specific coin unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signData(payload) ) .then((recipe) => wallet.balanceUnprovenTransaction( recipe.transaction, { shieldedSecretKeys, dustSecretKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['dust'], } ) ) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` ### Redesignate DUST to another address[​](#redesignate-dust-to-another-address "Direct link to Redesignate DUST to another address") Redesignation redirects DUST generation from registered NIGHT coins to a different DUST address. This is useful when transferring DUST generation rights to another wallet or service. The redesignation operation is atomic and requires DUST for transaction fees. ``` await wallet .registerNightUtxosForDustGeneration( [unshielded.availableCoins[0]], unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signData(payload), receiverDustAddress // Redirect to this address ) .then((recipe) => wallet.balanceUnprovenTransaction( recipe.transaction, { shieldedSecretKeys, dustSecretKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['dust'], } ) ) .then((recipe) => wallet.finalizeRecipe(recipe)) .then((tx) => wallet.submitTransaction(tx)); ``` ## DUST sponsorship[​](#dust-sponsorship "Direct link to DUST sponsorship") DUST sponsorship enables a service to pay transaction fees on behalf of users. This is useful for DApps that want to subsidize user fees. The following example demonstrates a two-party sponsorship flow where the user prepares a transaction and a sponsor adds the required DUST for fees. ### Sponsorship workflow[​](#sponsorship-workflow "Direct link to Sponsorship workflow") DUST sponsorship follows a three-step process that separates transaction creation from fee payment: 1. User creates and balances transaction without fees 2. Sponsor balances the transaction to add DUST for fees 3. Sponsor submits the transaction ``` // User prepares transaction without fees const userRecipe = await userWallet.balanceUnboundTransaction( transaction, { shieldedSecretKeys: userShieldedKeys, dustSecretKey: userDustKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['shielded', 'unshielded'], // No DUST } ); const userSigned = await userWallet.signRecipe( userRecipe, (payload) => userKeystore.signData(payload) ); const userFinalized = await userWallet.finalizeRecipe(userSigned); // Sponsor adds fees and submits await sponsorWallet .balanceFinalizedTransaction( userFinalized, { shieldedSecretKeys: sponsorShieldedKeys, dustSecretKey: sponsorDustKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000), tokenKindsToBalance: ['dust'], // Only add DUST } ) .then((recipe) => sponsorWallet.signRecipe(recipe, (payload) => sponsorKeystore.signData(payload))) .then((recipe) => sponsorWallet.finalizeRecipe(recipe)) .then((tx) => sponsorWallet.submitTransaction(tx)); ``` ## Atomic swaps[​](#atomic-swaps "Direct link to Atomic swaps") Atomic swaps enable trustless token exchanges between parties. The SDK supports creating swap offers that can be merged into a single transaction. The following examples assume both parties have initialized wallets with the necessary secret keys. ### Create and execute a swap[​](#create-and-execute-a-swap "Direct link to Create and execute a swap") The swap process involves two parties: * The initiator creates a partial transaction offering tokens in exchange for different tokens. * The counterparty completes the swap by balancing the transaction with their own inputs. The wallet handles all cryptographic operations and ensures both parties receive their expected tokens atomically. ``` // Alice initiates swap const aliceSwapTx = await aliceWallet .initSwap( { shielded: { [token1]: 1_000_000n } }, // Offer token1 [ { type: 'shielded', outputs: [ { type: token2, amount: 1_000_000n, receiverAddress: aliceShieldedAddress, }, ], }, ], // Request token2 { shieldedSecretKeys: aliceShieldedKeys, dustSecretKey: aliceDustKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000) } ) .then((recipe) => aliceWallet.finalizeRecipe(recipe)); // Bob completes swap by balancing Alice's transaction await bobWallet .balanceFinalizedTransaction( aliceSwapTx, { shieldedSecretKeys: bobShieldedKeys, dustSecretKey: bobDustKey }, { ttl: new Date(Date.now() + 30 * 60 * 1000) } ) .then((recipe) => bobWallet.finalizeRecipe(recipe)) .then((tx) => bobWallet.submitTransaction(tx)); ``` info The swap is atomic - either both parties exchange tokens or the transaction fails. Token amounts and types are hidden from observers. ## Use alternative proving[​](#use-alternative-proving "Direct link to Use alternative proving") By default, the wallet uses an HTTP-based proving server. For browser environments or alternative deployment scenarios, you can use WASM-based proving. ### WASM proving[​](#wasm-proving "Direct link to WASM proving") For browser environments or situations where HTTP access to a proving server is restricted, you can use WebAssembly-based proving. This approach runs proof generation entirely in the client environment but is significantly slower than using a dedicated proving server. ``` import { makeWasmProvingService } from '@midnightntwrk/wallet-sdk-capabilities'; const wallet = await WalletFacade.init({ configuration, shielded: (config) => ShieldedWallet(config).startWithSecretKeys(shieldedKeys), unshielded: (config) => UnshieldedWallet(config).startWithPublicKey(publicKey), dust: (config) => DustWallet(config).startWithSecretKey(dustKey, dustParams), provingService: () => makeWasmProvingService(), // Use WASM proving }); ``` Performance WASM proving is slower than native proving servers. Use it only when HTTP access to a proving server is not available. ## Lifecycle management[​](#lifecycle-management "Direct link to Lifecycle management") The wallet lifecycle management provides control over the wallet's startup and shutdown processes. ### Start the wallet[​](#start-the-wallet "Direct link to Start the wallet") Starting the wallet initiates all synchronization processes with the Midnight Network. This includes connecting to the node, indexer, and beginning to scan for transactions and state updates. You must call this method after initializing the wallet facade but before performing any operations. ``` await wallet.start(shieldedSecretKeys, dustSecretKey); ``` ### Stop the wallet[​](#stop-the-wallet "Direct link to Stop the wallet") Stopping the wallet gracefully shuts down all background processes, closes network connections to the node and indexer, and releases resources. This ensures clean termination and prevents resource leaks in your application. ``` await wallet.stop(); ``` warning Always stop the wallet before exiting your application to ensure proper cleanup of network connections and resources. ## DApp integration[​](#dapp-integration "Direct link to DApp integration") For DApp integration, use the DApp Connector API, which provides a standardized interface for wallet interactions. This API enables DApps to interact with browser wallets like Lace through a consistent interface. The example below shows how a DApp connects to and interacts with a Lace Midnight wallet. ``` import { nativeToken } from '@midnight-ntwrk/ledger-v8'; // Check if wallet is available const wallet = window.midnight?.mnLace; if (!wallet) { console.error('Please install Lace Midnight wallet'); throw new Error('Wallet not found'); } // Display wallet information to user console.log('Wallet name:', wallet.name); console.log('Wallet API version:', wallet.apiVersion); // Connect to wallet on preprod network try { const connectedApi = await wallet.connect('preprod'); console.log('Connected to wallet'); // Get wallet configuration const config = await connectedApi.getConfiguration(); console.log('Indexer URI:', config.indexerUri); console.log('Proving Server URI:', config.proverServerUri); console.log('Network ID:', config.networkId); // Query wallet balances const shieldedBalances = await connectedApi.getShieldedBalances(); const unshieldedBalances = await connectedApi.getUnshieldedBalances(); const dustBalance = await connectedApi.getDustBalance(); console.log('Shielded balances:', shieldedBalances); console.log('Unshielded balances:', unshieldedBalances); console.log('Dust balance:', dustBalance); // Get wallet addresses const shieldedAddresses = await connectedApi.getShieldedAddresses(); const unshieldedAddress = await connectedApi.getUnshieldedAddress(); const dustAddress = await connectedApi.getDustAddress(); console.log('Shielded address:', shieldedAddresses.shieldedAddress); console.log('Unshielded address:', unshieldedAddress); console.log('Dust address:', dustAddress); // Initiate a payment const transaction = await connectedApi.makeTransfer([ { kind: 'unshielded', tokenType: nativeToken().raw, value: 10n ** 6n, // 1 NIGHT recipient: 'mn_addr_preprod1abcdef...', // Replace with actual address }, ]); // Submit transaction await connectedApi.submitTransaction(transaction); console.log('Transaction submitted successfully'); } catch (error) { console.error('Error connecting to wallet:', error); } ``` tip To learn more about the DApp Connector API, see the [DApp Connector API](/api-reference/dapp-connector.md) documentation. ## References[​](#references "Direct link to References") * [Wallet SDK repository](https://github.com/midnightntwrk/midnight-wallet/tree/main/packages/docs-snippets/src/snippets) * [Wallet SDK release notes](/relnotes/wallet.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Common SDK integration issues This troubleshooting guide covers common errors and how to resolve them when building DApps using Midnight.js and Wallet SDKs. ## Midnight.js SDK issues[​](#midnightjs-sdk-issues "Direct link to Midnight.js SDK issues") Midnight.js errors are plain JavaScript classes. Catch them with `try/catch` and the `instanceof` operator. ### A transaction fails during execution[​](#a-transaction-fails-during-execution "Direct link to A transaction fails during execution") **Errors**: `TxFailedError`, `DeployTxFailedError`, `CallTxFailedError`, `ReplaceMaintenanceAuthorityTxFailedError`, `RemoveVerifierKeyTxFailedError`, `InsertVerifierKeyTxFailedError` All transaction error classes expose a `finalizedTxData` property containing the finalization data of the failed transaction. `TxFailedError` and `CallTxFailedError` additionally expose a `circuitId` property. **What to check**: * Check the `finalizedTxData` property on the caught error to identify which transaction failed and why. * For call transactions, check the `circuitId` property to identify the circuit that constructed the transaction. ``` import { CallTxFailedError, DeployTxFailedError } from '@midnight-ntwrk/midnight-js-contracts'; try { await client.call(/* ... */); } catch (error) { if (error instanceof CallTxFailedError) { console.error('Call failed, tx data:', error.finalizedTxData); console.error('Circuit ID:', error.circuitId); } else if (error instanceof DeployTxFailedError) { console.error('Deploy failed, tx data:', error.finalizedTxData); } else { throw error; } } ``` ### Deployed contract type does not match expectations[​](#deployed-contract-type-does-not-match-expectations "Direct link to Deployed contract type does not match expectations") **Error**: `ContractTypeError` This error occurs when the deployed contract state does not match the expected contract type, or when one or more verifier keys are mismatched. **What to check**: * Check the `circuitIds` property to identify which circuits carry undefined or non-matching verifier keys. * Verify that you compiled and deployed the contract with the verifier keys the SDK expects. ### Call transaction configuration is incomplete[​](#call-transaction-configuration-is-incomplete "Direct link to Call transaction configuration is incomplete") **Error**: `IncompleteCallTxPrivateStateConfig` This error occurs when a call transaction sets `privateStateId` without providing a `privateStateProvider`. **What to check**: * If you set `privateStateId` in the call options, then you must also provide a `privateStateProvider`. * Check the `privateStateId` and `privateStateProvider` properties on the error to see which values the SDK received and which were omitted. ### Contract lookup configuration is incomplete[​](#contract-lookup-configuration-is-incomplete "Direct link to Contract lookup configuration is incomplete") **Error**: `IncompleteFindContractPrivateStateConfig` This error occurs when a contract lookup sets `initialPrivateState` without providing a `privateStateId`. The runtime throws this message: ``` 'initialPrivateState' was defined for contract find while 'privateStateId' was undefined ``` **What to check**: * If you supply `initialPrivateState` in the find options, then you must also supply a `privateStateId`. * Check the `initialPrivateState` and `privateStateId` properties on the error for the values passed. For the complete list of Midnight.js error classes and their properties, see the [Midnight.js error reference](/sdks/error-reference/midnight-js.md). ## Wallet SDK[​](#wallet-sdk "Direct link to Wallet SDK") Wallet SDK errors are often Effect `Data.TaggedError` instances. Use `Effect.catchTag` with the `_tag` value to catch a specific error, or `Effect.catchTags` to handle a union. ### Cannot connect to the node[​](#cannot-connect-to-the-node "Direct link to Cannot connect to the node") **Errors**: `ConnectionError` (`_tag: 'ConnectionError'`), `InvalidProtocolSchemeError` (`_tag: 'InvalidProtocolSchemeError'`), `FailedToDeriveWebSocketUrlError` (`_tag: 'FailedToDeriveWebSocketUrlError'`) **Known `ConnectionError` messages**: * `"Could not connect within specified time range (5s)"` — the node is unreachable or slow to respond. * `"Failed to retrieve genesis transactions"` — connected but genesis data is unavailable. **What to check**: * Verify the node WebSocket URL is correct and the node is running. * If connecting over a slow network, then you should consider increasing the connection timeout. * If you see `InvalidProtocolSchemeError`, then ensure all network URLs use the expected scheme: `ws://` or `wss://` for WebSocket connections, `http://` or `https://` for HTTP. ### The SDK cannot parse a node response[​](#the-sdk-cannot-parse-a-node-response "Direct link to The SDK cannot parse a node response") **Error**: `ParseError` (`_tag: 'ParseError'`) **What to check**: * This usually indicates a protocol version mismatch between the SDK and the node. * Verify the SDK and node versions are compatible and update whichever is out of date. note Always refer to the [Compatibility matrix](/relnotes/support-matrix.md) to check for compatible versions of the SDK and node for the environment you are working in. ### The node rejects a transaction as invalid[​](#the-node-rejects-a-transaction-as-invalid "Direct link to The node rejects a transaction as invalid") **Error**: `TransactionInvalidError` (`_tag: 'TransactionInvalidError'`) **What to check**: * A malformed transaction or a validation-rule violation caused this error. * Review the transaction construction logic. You should not resubmit without changes. ### Insufficient funds[​](#insufficient-funds "Direct link to Insufficient funds") **Errors**: `InsufficientFundsError` (`_tag: 'Wallet.InsufficientFunds'`), `InsufficientFundsError` (Capabilities — plain `Error`) The tagged-error variant exposes `tokenType: string` and `amount: bigint`. The capabilities variant is a plain JavaScript `Error` thrown during coin selection, not an Effect failure. **Known capabilities message**: `"Insufficient Funds: could not balance "` **What to check**: * Check the wallet balance for the token type before constructing the transaction. * Reduce the transfer amount or request a top-up. * For the capabilities plain `Error`, use `try/catch` or `Effect.tryPromise` rather than `Effect.catchTag`. ### Proof generation fails[​](#proof-generation-fails "Direct link to Proof generation fails") **Error**: `ProvingError` (`_tag: 'Wallet.Proving'`) **What to check**: * Confirm the [proof server](/guides/run-proof-server.md) is running and accessible. * Verify you are loading the correct circuit keys. * Check the wrapped cause for the underlying provider error. ### Coins are missing nonce hashes[​](#coins-are-missing-nonce-hashes "Direct link to Coins are missing nonce hashes") **Error**: `InvalidCoinHashesError` (`_tag: 'Wallet.InvalidCoinHashes'`) **What to check**: * Ensure coins are fully synced before spending. * Check the `missingNonces` field to identify the affected coins. ### Address is invalid[​](#address-is-invalid "Direct link to Address is invalid") **Errors**: `AddressError` (`_tag: 'Wallet.Address'`) `AddressError` exposes `originalAddress: string` which contains the rejected input. Address-format errors are plain `Error` throws. You can catch them with `try/catch`. **Common address-format messages**: * `"Expected prefix mn"`: The address does not start with the `mn` prefix. * `"Segment contains disallowed characters"`: The address segment contains characters outside the allowed set. * `"Unshielded address needs to be 32 bytes long"`: The unshielded address payload is the wrong length. * `"Dust address is too large"`: The DUST address exceeds the maximum allowed size. **What to check**: * Validate address strings before passing them to the address-format API. * Use `AddressError` for higher-level address validation at the wallet layer. ### HTTP networking errors[​](#http-networking-errors "Direct link to HTTP networking errors") **Errors**: `ClientError` (`_tag: 'ClientError'`), `ServerError` (`_tag: 'ServerError'`) **What to check**: * `ClientError` corresponds to HTTP 400–499 status codes. These indicate a problem with the request itself such as a bad input, authentication failure, or a not-found resource. Do not retry without changing the request. Check the error for the specific status code. * `ServerError` corresponds to HTTP 500+ status codes. For persistent 500 errors, check the server logs. The SDK automatically retries on transient 502–504 errors. For the complete list of Wallet SDK error types, see the [Wallet SDK error reference](/sdks/error-reference/wallet-sdk.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # AI integration AI coding assistants are fast, but they hallucinate on Midnight. Compact and the Midnight SDK are barely represented in their training data, so an assistant left on its own invents syntax, calls functions that do not exist, and hands you code that fails at compile time. This section covers tools that close that gap. They keep you in the loop, where you steer and approve, while the assistant checks its own output against the real Compact compiler, SDK, and source. You spend less time debugging invented code and more time building. ## What you can do[​](#what-you-can-do "Direct link to What you can do") * Write Compact smart contracts without hallucinated syntax, checked against the real compiler. * Scaffold a DApp frontend and wire it to a contract and the Lace wallet. * Spin up and health-check a local devnet (node, indexer, and proof server). * Review your own contract for privacy leaks before you push. ## Start here[​](#start-here "Direct link to Start here") [✦](/ai-integration/midnight-expert.md) ### [Midnight Expert](/ai-integration/midnight-expert.md) [A suite of Claude Code plugins for building on Midnight. Install, run doctor, and compile your first verified contract in minutes.](/ai-integration/midnight-expert.md) [Get started→](/ai-integration/midnight-expert.md) [✦](https://academy.midnight.network/) ### [Midnight Academy](https://academy.midnight.network/) [New to Midnight? Learn selective disclosure, ZK proofs, and how to build, through guided, interactive lessons.](https://academy.midnight.network/) [Start learning→](https://academy.midnight.network/) ## More coming[​](#more-coming "Direct link to More coming") Midnight Expert is the first tool covered here, not the last. More first-party AI integration tools are on the way, including Midnight Manual and Compass P. Each gets a quick start here and links out to its own documentation as it becomes ready. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Kapa MCP server The Kapa MCP server exposes the same Midnight knowledge base that powers the "Ask AI" button on this documentation site. It gives your AI coding assistant documentation-grounded answers about Midnight directly in your editor, so you can ask questions without switching to a browser tab. For background on why the project moved to Kapa and how it fits alongside Midnight Expert, see the [migration blog post](/blog/migrating-to-kapa-and-midnight-expert). ## Install[​](#install "Direct link to Install") ### Claude Code[​](#claude-code "Direct link to Claude Code") Run one command: ``` claude mcp add --transport http midnight https://midnight.mcp.kapa.ai ``` ### Cursor and VS Code[​](#cursor-and-vs-code "Direct link to Cursor and VS Code") Open the "Ask AI" button on this site, click "Use MCP", and choose "Add to Cursor" or "Add to VS Code". Both are one-click installs. ### Any other MCP client[​](#any-other-mcp-client "Direct link to Any other MCP client") For any client that supports remote MCP servers in a JSON config, add the server manually: ``` { "mcpServers": { "midnight": { "type": "http", "url": "https://midnight.mcp.kapa.ai" } } } ``` Some clients label this a remote or HTTP server and ask for a transport field; the URL is the same in every case. You can also click "Copy MCP URL" from the "Use MCP" menu and paste it wherever your client expects it. ## What it covers[​](#what-it-covers "Direct link to What it covers") Kapa indexes a curated set of Midnight sources: the official documentation, hand-picked core repositories (the ledger, midnight.js, and the node), and standalone material such as the whitepaper. Ask how DUST generation works, how to structure a witness, or what a specific ledger type does, and you get an answer grounded in current documentation rather than stale training data. ## Midnight Expert[​](#midnight-expert "Direct link to Midnight Expert") For hands-on development tasks like writing and validating Compact contracts, running a local devnet, or decoding error codes, use [Midnight Expert](/ai-integration/midnight-expert.md) alongside Kapa. See the [Midnight agent skills](/sdks/community/ai-tools/midnight-agent-skills.md) page or the [migration blog post](/blog/migrating-to-kapa-and-midnight-expert) for setup instructions. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Expert Midnight Expert is a suite of Claude Code plugins for building on Midnight. It works as a human-in-the-loop coding assistant: you steer and approve while it writes and reviews Compact, scaffolds DApps, and checks its own output against the real compiler and source. That last part is the point, so you get working code instead of hallucinations. It is built as Claude Code plugins today. This quick start takes you from install to your first compiled contract in a few minutes. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * Claude Code (the CLI or an IDE extension). * macOS or Linux. On Windows, run everything inside [WSL2](https://learn.microsoft.com/windows/wsl/). * `jq` and the GitHub CLI. The installer checks for these and helps you install any that are missing. * The Compact toolchain. If you do not have it yet, Step 2 sets it up so Step 3 can compile. ## Step 1: install the plugins[​](#step-1-install-the-plugins "Direct link to Step 1: install the plugins") Run the guided installer. It registers the marketplace, enables the plugins, and checks that everything it needs is in place. ``` curl -fsSL https://midnightntwrk.expert/install.sh | bash ``` Other install methods You can also add the marketplace from inside Claude Code by running `/plugin` and pasting `https://midnightntwrk.expert`, or from the command line with `claude plugin marketplace add https://midnightntwrk.expert`. Slash commands from a plugin installed mid-session only appear after you restart Claude Code; skills and agents activate right away. ## Step 2: check your setup[​](#step-2-check-your-setup "Direct link to Step 2: check your setup") Run `/midnight-expert:doctor` to confirm your environment is ready. It reports on plugin installation, external tools, and connectivity. If it flags a missing Compact CLI or proof server, ask your assistant to install it, then run doctor again. ## Step 3: your first verified result[​](#step-3-your-first-verified-result "Direct link to Step 3: your first verified result") Open Claude Code in an empty folder and type: > Write a minimal Compact counter contract in `contracts/Counter.compact` and compile it. Here is what happens: 1. The plugins steer the assistant to work from checked Compact knowledge and the real compiler rather than its training data, which is unreliable for Compact. 2. It writes `Counter.compact`: a `Counter` ledger field, an `increment` circuit, and a `read` circuit that returns the value. 3. It compiles the file with the real Compact CLI. If it tries to finish without compiling a contract it just wrote or changed, a check catches that and prompts it to compile first. 4. If the compile fails, it reads the actual compiler error, fixes the source, and compiles again. **What you see:** a `Counter.compact` file in your repo and a successful compile, with the generated TypeScript types and ZK artifacts in the output directory. You went from a one-line prompt to a contract that compiles. To watch the verification directly, ask the assistant to check a fact: ``` /midnight-verify:verify "A Compact Counter ledger field supports increment and read" ``` It compiles and runs a tiny test contract, then returns Confirmed, Refuted, or Inconclusive with the evidence. If something breaks If a compile fails or the assistant seems to be guessing, run `/midnight-expert:doctor` for the ecosystem, and `/midnight-tooling:doctor` for the Compact CLI itself. ## Next steps[​](#next-steps "Direct link to Next steps") Pick the path that matches what you are building. Describe the goal in plain language and the right plugin activates on its own. * **Smart contracts.** "Write a Compact contract for a sealed-bid voting system and walk me through the disclosure rules." More in the [`compact-core` README](https://github.com/midnightntwrk/midnight-expert/tree/main/plugins/compact-core). * **DApp frontends.** "Scaffold a Vite and React DApp wired to my counter contract and connect it to the Lace wallet." More in the [`midnight-dapp-dev` README](https://github.com/midnightntwrk/midnight-expert/tree/main/plugins/midnight-dapp-dev). Also worth trying: * Run a local devnet and check its health: "Is my local proof server healthy, and is the indexer caught up to the node?" * Look up any error code: "The node rejected my transaction with code 166. What does that mean?" * Review your own contract before you push: "Review `contracts/Report.compact` for potential privacy leaks before I push." For the full set of plugins, skills, and agents, browse the [marketplace](https://midnightntwrk.expert/) or the [GitHub repository](https://github.com/midnightntwrk/midnight-expert). Each plugin ships a detailed README. ## Go deeper[​](#go-deeper "Direct link to Go deeper") * [Midnight Expert marketplace](https://midnightntwrk.expert/): install instructions and an overview. * [GitHub repository](https://github.com/midnightntwrk/midnight-expert): source, per-plugin READMEs, and issues. * File a bug or request with `/midnight-expert:feedback`. * Show proof server and Compact CLI status in your status bar with `/midnight-tooling:install-statusline-script`. Get updates sooner Updates reach the marketplace 3 to 5 days after they merge, which gives the community time to test them. To live on the bleeding edge, use the GitHub repository `midnightntwrk/midnight-expert` as your marketplace address instead. --- > For the complete documentation index, see [llms.txt](/llms.txt) # The Compact language Midnight comes with its own programming language, Compact, which enables you to write smart contracts for the Midnight ecosystem. The Compact compiler outputs zero-knowledge circuits that are used to prove the correctness of interactions with the ledger. This section will provide a more in-depth breakdown of writing Compact and working with its supporting tools. Subsequent sections cover security best practices, Compact language reference and the Compact standard library API reference. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact compiler usage page This is the usage page of **compactc**, a compiler for Compact. This document assumes you are using **compactc** directly. Typically, however, the compiler is invoked via the **compact** tool's `compile` command, which is described in the [usage page for that tool](/compact/compilation-and-tooling/dev-tool-usage.md). # NAME compactc # OVERVIEW The Compact compiler, **compactc**, is part of the Compact toolchain. It takes as input a Compact source program in a specified source file and translates it into several target files in a specified directory. # SYNOPSIS **compactc** *flag* **...** *sourcepath* *targetpath* # DESCRIPTION The flags *flag* **...** are optional. They are described under FLAGS later in this document. *sourcepath* should identify a file containing a Compact source program, and *targetpath* should identify a target directory into which the target files are to be placed. The target directory is created if it does not already exist. **compactc** compiles the source file and produces from it the following target files: * a Typescript type-definition file *targetdir***/contract/index.d.ts** * a Javascript source file *targetdir***/contract/index.js** * a Javascript source-map file *targetdir***/contract/index.js.map** * one Zk/ir circuit file for each exported circuit *circuitname* in *targetdir***/zkir/***circuitname***.zkir**, and * a pair of proving keys for each exported circuit *circuitname* in *targetdir***/keys/***circuitname***.prover** and *targetdir***/keys/***circuitname***.verifier**. Compact source files can include other Compact source files via an **include** form: **include** '*name*'; They can also import externally defined modules via an **import** form: **import** *name*; **import** '*name*'; By default, the compiler looks for include files and externally defined modules with non-absolute pathnames relative to the directory of the including or importing file under the full filename *name***.compact**. If this fails, it looks for the file in the *Compact search list*. The Compact search list is * the value of the **--compact-path** command-line option, if provided, * otherwise the value of the **COMPACT\_PATH** environment variable, if set, * otherwise empty. The search list is a colon-separated (semicolon-separated on Windows) list of directory pathnames *dirpath***:...:***dirpath* (*dirpath***;...;***dirpath* under Windows), and the compiler looks under the full pathname *dirpath***/***name***.compact** for each *dirpath* in order until the file is found or the set of *dirpath* entries is exhausted. Most Compact source programs should import the standard library **CompactStandardLibrary**. This is typically done by placing the following line near the top of the program: **import CompactStandardLibrary;** **CompactStandardLibrary** is built into the compiler, not found in the filesystem. # FLAGS The following flags, if present, affect the compiler's behavior as follows: **--help** Prints help text and exits. **--version** Prints the compiler version and exits. **--language-version** Prints the language version supported by the compiler and exits. **--runtime-version** Prints the runtime version required by the compiler and exits. **--ledger-version** Prints the ledger version required by the compiler and exits. **--feature-zkir-v3** Causes the compiler to generate circuits using ZKIR version 3, overriding the default (version 2). **--vscode** Causes the compiler to omit newlines from error messages, so that they are rendered properly within the VS Code extension for Compact. **--skip-zk** Causes the compiler to skip the generation of proving keys. Generating proving keys can be time-consuming, so this option is useful when debugging only the Typescript output. The compiler also skips, after printing a warning message, the generation of proving keys when it cannot find zkir. **--no-communications-commitment** Omits the contract communications commitment that enables data integrity for contract-to-contract calls. **--sourceRoot *sourceRoot-value*** Overrides the compiler's setting of the sourceRoot field in the generated source-map (.js.map) file. By default, the compiler tries to determine a useful value based on the source and target-directory pathnames, but this value might not be appropriate for the deployed structure of the application. **--compact-path *search list*** Sets the Compact path, overriding the default value, which is the value of the environment variable COMPACT\_PATH, if it is set, and empty otherwise. ***search list*** should be a colon-separated (semicolon-separated under Windows) sequence of directory pathnames. The Compact path controls where the compiler looks for include and external module files with non-absolute pathnames. It always looks first relative to the directory of the including or importing file, then in each directory in the Compact path from left to right. **--trace-search** Causes the compiler to print a sequence of messages saying where it is looking for each included file and imported module source file. **--trace-passes** Causes the compiler to print tracing information that is generally useful only to compiler developers. # EXAMPLES Assuming **src/test.compact** contains a well-formed Compact program containing circuits *foo*, *bar*, and *baz* where *foo* and *bar* are exported but *baz* is not and *foo* touches (reads or writes) a ledger field but *bar* does not: ``` compactc src/test.compact obj/test ``` produces: ``` obj/test/contract/index.d.ts obj/test/contract/index.js obj/test/contract/index.js.map obj/test/contract/contract-info.json obj/test/zkir/foo.zkir obj/test/keys/foo.prover obj/test/keys/foo.verifier ``` Note that ``` compactc --skip-zk src/test.compact obj/test ``` produces the same, except without the keys. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact command-line tool usage page This is the usage page of the Compact command-line tool. This tool allows the user to run any of Compact toolchain's tools: the compiler, the formatter, and the fixup tool. It also allows the user to update the toolchain or command-line tool itself. # NAME Compact command-line tool # OVERVIEW The Compact command-line tool provides a set of utilities for Compact smart contract development. # SYNOPSIS **compact** *options* **...** **compact** *command* *options* **..** # DESCRIPTION The *options* flags are optional and are described under OPTIONS later in this document. The Compact command-line tool takes a *command*. This command is the program that the tool runs. Supported commands are listed below and the more complicated ones are explained in detail under the command name: **check** Checks for updates with the remote server \[aliases: ch] and exits. **update** Updates to the latest or a specific version of the Compact toolchain \[aliases: u, up] and exits . **format** Formats Compact files \[aliases: f, fmt] and exits. **fixup** Applies fixup transformations to Compact files \[aliases: fx, fix] and exits. **list** Lists available Compact versions \[aliases: l] and exits. **clean** Removes all Compact versions \[aliases: cl] and exits. **self** Commands for managing the Compact tool itself \[aliases: s]. **compile** Calls the compiler \[aliases: c] and exits. **help** Prints the help of the command-line tool and exits. # OPTIONS The following options are available for all commands, and if present, they affect the tool's behavior as follows: **--directory *directorypath*** Sets the Compact artifact directory and exits. By default this will be `$HOME/.compact`. The directory will be created if it does not exist. This can also be configured via an environment variable. \[env: COMPACT\_DIRECTORY=] \[default: /Users/username/.compact] **--help** Prints help for this tool or of *command* provided by the tool and exits. **--version** Prints the version of this tool or of *command* and exits. # CHECK Synopsis: **compact** **check** *options* This command checks for updates of the Compact toolchain on the remote server. Assuming there are not versions of the Compact toolchain installed, running: ``` compact check ``` results in: ``` compact: no version installed. compact: Latest version available: 0.28.0. ``` where **0.28.0** is the latest available Compact toolchain version on the remote server. However, assuming that the previous version of the Compact toolchain is installed, running: ``` compact check ``` results in: ``` compact: aarch64-darwin -- Update Available -- 0.26.0 compact: Latest version available: 0.28.0. ``` where **0.26.0** is the installed version and **0.28.0** is the latest available version of the Compact toolchain. The command **update** can be used to update to this version. **aarch64-darwin** displays the chosen binary of the Compact toolchain for your machine's architecture. # UPDATE Synopsis: **compact** **update** *options* *compactversion* This command updates to the latest version of the Compact toolchain if no version is specified, otherwise, it updates to the specified version of the Compact toolchain *compactversion*. *compactversion* can be specified as a full version, such as **0.30.1**, as a major.minor prefix such as **0.30** which resolves to the latest patch release for that minor version, or as a major prefix only such as **0** which resolves to the latest minor and patch release for that major version. Upon switching from one version to another, by default this command switches the default compiler version to the installed one. This can be overwritten by **--no-set-default** option. If the compiler is downloaded, then it is not downloaded again. The following options are specific to this command: **--no-set-default** Doesn't set the newly installed compiler as the default. We now present some simple examples of using this command. Assuming the latest Compact toolchain on the remote server is **0.28.0** and the last time you updated your Compact toolchain was to **0.26.0**, running: ``` compact update ``` results in: ``` compact: aarch64-darwin -- 0.28.0 -- installed compact: aarch64-darwin -- 0.28.0 -- default. ``` Now after updating to the latest version, running: ``` compact update ``` results in: ``` compact: aarch64-darwin -- 0.28.0 -- already installed compact: aarch64-darwin -- 0.28.0 -- default. ``` However, running: ``` compact update --no-set-default ``` results in: ``` compact: aarch64-darwin -- 0.28.0 -- already installed ``` To switch to an older version, run: ``` compact update 0.26.0 ``` which results in: ``` compact: aarch64-darwin -- 0.26.0 -- already installed compact: aarch64-darwin -- 0.26.0 -- default. ``` To keep the default unchanged, run: ``` compact update --no-set-default 0.26.0 ``` which results in: ``` compact: aarch64-darwin -- 0.26.0 -- already installed ``` # COMPILE Synopsis: **compact** **compile** *+version* *options* *sourcepath* *targetpath* This command compiles the Compact source program in *sourcepath* using the specified Compact toolchain version *version* if it exists. If no version is specified, the installed default version of the Compact toolchain is used. The *options* are optional. If *+version* does not exist, then both the installed default compiler and the command-line tool *options* can be used. Otherwise, only the *options* of the installed specified compiler can be used. The *targetpath* specifies the target directory for the outputs of the compiler. Visit [the compiler usage page](/compact/compilation-and-tooling/compiler-usage.md) for a more detailed explanation of how to use it. If **+version** is specified such as **+0.30.0**, `compact compile` uses that exact version of the toolchain to compile the program. If no version is specified, the default toolchain version (as set by `compact update`) is used. Partial version specifiers are not supported here; the version must be fully qualified, that is, **+0.30.0** is supported but **+0.30** is not. If the requested toolchain version is not installed, `compact compile` will fail with an error. Run `compact update _version_` first to install it. Assuming that Compact toolchain **0.26.0** and **0.30.0** are installed and **0.26.0** is the default, running: ``` compact compile +0.27.0 --language-version ``` results in: ``` Error: Failed to run compactc Caused by: 0: Couldn't find compiler for aarch64-darwin (0.27.0) 1: Directory does not exist ``` whereas running: ``` compact compile --language-version ``` results in `0.18.0` (which is the corresponding language version for the toolchain **0.26.0**) and running: ``` compact compile +0.30.0 --language-version ``` results in `0.22.0` (which is the corresponding language version for the toolchain **0.30.0**). Running: ``` compact compile +version --help ``` returns the help text of the compiler for a specific version **+version**, whereas running: ``` compact compile --help ``` returns the help text specified in the Compact command-line tool for the compiler. # FORMAT Synopsis: **compact** **format** *options* *files* This command formats one or more Compact source files using the installed format-compact tool. *files* can be individual `.compact` files or directories; when a directory is given, all `.compact` files within it are discovered recursively, respecting `.gitignore` rules. If no *files* are specified, the current directory (`.`) is used. The following options are specific to this command: **--check** Checks whether files are already formatted without modifying them. Exits with a non-zero status and prints a diff for any file that would be changed. This is useful in CI pipelines to enforce formatting without altering source files. **--verbose** Prints each file processed along with its outcome (**formatted**, **unchanged**, or an error). Without this flag only failures are reported. Additionally, the formatter tool itself provides extra flags. Visit [the format usage page](/compact/compilation-and-tooling/formatter-usage.md) for a more detailed explanation of this tool. We now present some simple examples of using this command. Assuming **src/** contains a well-formed Compact source files, format all of them in place: ``` compact format src/ ``` Check formatting without modifying files (suitable for CI): ``` compact format --check src/ ``` Format a single file verbosely: ``` compact format --verbose src/counter.compact ``` Assuming **src/test.compact** contains an ill-formed Compact program, running: ``` compact format src/test.compact ``` exits with an error message describing the problem that prevents the Compact program in **src/test.compact** from compiling. # FIXUP Synopsis: **compact** **fixup** *options* *files* This command applies fixup transformations to one or more Compact source files using the installed fixup-compact tool. Unlike **format**, which only reformats whitespace and style, **fixup** also updates source programs to reflect recent language changes. *files* can be individual `.compact` files or directories; when a directory is given, all `.compact` files within it are discovered recursively, respecting `.gitignore` rules. If no *files* are specified, the current directory (`.`) is used. The following options are specific to this command: **--check** Checks whether files need fixup without modifying them. Exits with a non-zero status and prints a diff for any file that would be changed. Useful in CI pipelines to verify that source files are up to date. Additionally, the fixup tool itself provides extra flags. Visit [the fixup usage page](/compact/compilation-and-tooling/fixup-usage.md) for a more detailed explanation of this tool. We now present some simple examples of using this command. Assuming **src/** contains a well-formed Compact source files, apply fixup to all files in **src/** in place: ``` compact fixup src/ ``` Check whether any files need fixup without modifying them (suitable for CI): ``` compact fixup --check src/ ``` Apply fixup including `Uint` range endpoint adjustment: ``` compact fixup --update-Uint-ranges src/ ``` Assuming **src/test.compact** contains an ill-formed Compact program, running ``` compact fixup src/test.compact ``` exits with an error message describing the problem that prevents the Compact program in **src/test.compact** from compiling. # LIST Synopsis: **compact** **list** *options* This command lists available Compact toolchain versions on the remote server if no option is set. When the **--installed** option is set, it lists the locally installed versions of the Compact toolchain. The following options are specific to this command: **--installed** Shows installed versions and exits. We now present some simple examples of using this command. Assuming that the latest available Compact toolchain version is **0.28.0** on the remote server, running: ``` compact list ``` results in: ``` compact: available versions → 0.28.0 - x86_macos, aarch64_macos, x86_linux 0.26.0 - x86_macos, aarch64_macos, x86_linux 0.25.0 - x86_macos, aarch64_macos, x86_linux 0.24.0 - x86_macos, aarch64_macos, x86_linux 0.23.0 - aarch64_macos, x86_linux 0.22.0 - x86_macos, x86_linux ``` Assuming that locally versions **0.26.0** and **0.28.0** have been installed, running: ``` compact list --installed ``` results in: ``` compact: installed versions → 0.28.0 0.26.0 ``` The right arrow indicates the version to be used by the Compact command-line tool when no version is specified. # CLEAN Synopsis: **compact** **clean** *options* This command removes all local versions of the Compact toolchain if no option is set. When **--cache** is set, it also removes the cache directory. When **--keep-current** is set, the version currently set as the default is kept. In addition to removing version directories, `compact clean` removes the compactc, format-compact, and fixup-compact symlinks from the bin directory. After running `compact clean` without **--keep-current**, the toolchain is unusable until \`compact update\`\` is run again to reinstall a version. With **--keep-current**, the symlinks are preserved alongside the kept version. The following options are specific to this command: **--cache** removes the cache directory as well. **--keep-current** keeps the version currently in use. We now present some simple examples of using this command. Assuming that versions **0.26.0** and **0.28.00** of the Compact toolchain are locally installed, running: ``` compact clean --cache ``` results in: ``` compact: removed /Users/username/Library/Caches/compactc/github_cache.json compact: removing versions compact: removed 0.28.0 compact: removed 0.26.0 ``` Now running: ``` compact list --installed ``` results in: ``` compact: installed versions no versions available on this machine try: compact update ``` Now running: ``` compact update compact update 0.26.0 compact clean --keep-current ``` results in: ``` compact: removing versions compact: removed 0.28.0 compact: kept 0.26.0 ``` # SELF Synopsis: **compact** **self** *options* *subcommand* Manages the Compact command-line tool itself. Running: ``` compact self check ``` checks if a newer version of the Compact command-line tool is available or not. Assuming the latest version of the Compact command-line tool is **0.4.0** and it is already installed this results in: ``` compact: compact -- 0.4.0 -- Up to date ``` However, if the latest version of the Compact command-line tool is not installed the command above results in: ``` compact: compact -- Update available -- 0.5.0 ``` Running: ``` compact self update ``` updates the Compact command-line tool to the latest version. If the tool is already at the latest version, running `compact self update` results in (assuming the latest version is **0.5.0**): ``` compact: compact -- 0.5.0 -- Up to date ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact fixup usage page This is the usage page of **fixup-compact**, a fix up tool for Compact. This document assumes you are using **fixup-compact** directly. Typically, however, the fixup tool is invoked via the **compact** tool's `fixup` command, which is described in the [usage page for that tool](/compact/compilation-and-tooling/dev-tool-usage.md). # NAME fixup-compact # OVERVIEW The Compact fixup tool is part of Compact toolchain. It takes as input a Compact source program in a specified source file, attempts to update it to account for recent changes in the Compact language, formats it, and writes the updated and reformatted program to a specified file. If such a file is not specified, it writes the updated and formatted program to standard output. # SYNOPSIS **fixup-compact** *flag* **...**... *sourcepath* *targetpath* # DESCRIPTION The flags *flag* **...** are optional. They are described under FLAGS later in this document. *sourcepath* should specify a file containing a Compact source program, and *targetpath* should specify the file into which the updated and formatted program should be written. *targetpath* may be the same as *sourcepath*, in which case the source program is replaced with the updated and reformatted equivalent. We recommend, however, that you direct the output to a different file and compare it with the original, to verify that the changes make sense. # FLAGS The following flags, if present, affect the fixup tool's behavior as follows: **--help** Prints help text and exits. **--version** Prints the compiler version and exits. **--language-version** Prints the language version and exits. **--vscode** Causes error messages to be printed on a single line so they are rendered properly within the VS Code extension for Compact. **--update-Uint-ranges** Adjusts the end point of each Uint whose size is given by a range with a constant end point and issues a warning for each Uint whose size is given by a range when the end point is a generic-variable reference. **--compact-path *search list*** Sets the Compact search list to ***search list***, overriding the default (the value of the **COMPACT\_PATH** environment variable, if set, otherwise empty). The search list is a colon-separated (semicolon-separated on Windows) list of directory pathnames. **--trace-search** Causes the fixup tool to print a sequence of messages saying where it is looking for each included file and imported module source file. **--line-length *n*** Sets the target line length to *n* (default 100). # EXAMPLES Assuming **src/test.compact** contains a well-formed Compact program, running: ``` fixup-compact src/test.compact ``` prints the updated and formatted program of **src/test.compact** to standard output. Assuming that **fixed** is an existing directory, running: ``` fixup-compact src/test.compact fixed/test.compact ``` writes the updated and formatted program to **fixed/test.compact**. If the **fixed** directory does not exist the fixup tool complains that it cannot create the output file. Alternatively, running: ``` fixup-compact src/test.compact src/test.compact ``` rewrites the updated and formatted program to **src/test.compact**. Assuming **src/test.compact** contains an ill-formed Compact program, running: ``` fixup-compact src/test.compact ``` exits with an error message describing the problem that prevents the Compact program in **src/test.compact** from compiling. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact formatter usage page This is the usage page of **format-compact**, a formatter for Compact. This document assumes you are using **format-compact** directly. Typically, however, the formatter is invoked via the **compact** tool's `format` command, which is described in the [usage page for that tool](/compact/compilation-and-tooling/dev-tool-usage.md). # NAME format-compact # OVERVIEW The Compact formatter is part of the Compact toolchain. It takes as input a Compact source program in a specified source file, reformats it, and writes the reformatted program to a specified file. If such a file is not specified, it writes the reformatted program to standard output. # SYNOPSIS **format-compact** *flag* **...** *sourcepath* *targetpath* # DESCRIPTION The flags *flag* **...** are optional. They are described under FLAGS later in this document. *sourcepath* should specify a file containing a Compact source program, and *targetpath* should specify a target file in which the reformatted program is to be written. *targetpath* may be an existing file, in which case the file will be replaced with the formatted program. *targetpath* may be the same as *sourcepath*, in which case the source program is replaced with the reformatted equivalent. # FLAGS The following flags, if present, affect the formatter's behavior as follows: **--help** Prints help text and exits. **--version** Prints the compiler version and exits. **--language-version** Prints the language version and exits. **--vscode** Causes error messages to be printed on a single line so they are rendered properly within the VS Code extension for Compact. **--line-length *n*** Sets the target line length to *n* (default 100). # EXAMPLES Assuming `src/test.compact` contains a well-formed Compact program, running: ``` format-compact src/test.compact ``` prints the formatted program of **src/test.compact** to standard output. Assuming that **formatted** is an existing directory, running: ``` format-compact src/test.compact formatted/test.compact ``` writes the formatted program to **formatted/test.compact**. If the **formatted** directory does not exist the formatter complains that it cannot create the output file. Alternatively, running: ``` format-compact src/test.compact src/test.compact ``` rewrites the formatted program to **src/test.compact**. Assuming **src/test.compact** contains an ill-formed Compact program, running: ``` format-compact src/test.compact ``` exits with an error message describing the problem that prevents the Compact program in **src/test.compact** from compiling. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Neovim setup for Compact [compact.vim](https://github.com/1NickPappas/compact.vim) is a community-driven plugin that provides Compact language support for Neovim. ## Features[​](#features "Direct link to Features") The plugin provides the following capabilities for working with Compact source files: * Syntax highlighting (regex-based and tree-sitter) * Smart indentation * Code folding * Text objects (requires [nvim-treesitter-textobjects](https://github.com/nvim-treesitter/nvim-treesitter-textobjects)) * Import navigation via `gf` * Compiler integration via `:make` * Local scoping (variable references scoped per circuit/block) ![Syntax highlighting](/assets/images/compact-syntax-19f5693a997c34fd63b937000110cb69.png) ## Installation[​](#installation "Direct link to Installation") Install with [lazy.nvim](https://github.com/folke/lazy.nvim): ``` { "1NickPappas/compact.vim" } ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Visual Studio Code extension for Compact The \[Visual Studio Code extension] for Compact is a plugin that assists with writing and debugging smart contracts written in Midnight's Compact language. DApp developers can create new smart contracts * using a file template * from scratch, optionally using code snippets. ## Installation[​](#installation "Direct link to Installation") Install via the \[Releases page] () ## Features[​](#features "Direct link to Features") ### Syntax highlighting[​](#syntax-highlighting "Direct link to Syntax highlighting") Smart contracts are written in the Compact language. The following language elements will be recognized and formatted: * Compact keywords, such as `enum`, `struct`, and `circuit` * string, boolean, and numeric literals * comments * parentheses ![Syntax highlighting](/assets/images/compact-syntax-a76e9fa96b86a7476a71cb0a2eb51e26.png) ### Building Compact source files and error highlighting[​](#building-compact-source-files-and-error-highlighting "Direct link to Building Compact source files and error highlighting") For building smart contracts, you will typically want to add a script definition in `package.json`, like so: ``` "scripts": { "compact": "compact compile --vscode ./src/myContract.compact ./src/managed/myContract" } ``` The preceding assumes that the Compact compiler is on the shell's command search path (if it isn't, follow the instructions provided in [Running Midnight Compact compiler](/develop/tutorial/building/counter-build#compile-the-code)). It also uses the Compact compiler's --vscode option to omit newlines in error messages, so that they render properly inside the VS Code environment. This allows you to compile your smart contract using: ``` yarn compact ``` When you edit complex contracts, and you want to have fast interactions, it is more convenient to add a [task file](https://code.visualstudio.com/docs/editor/tasks) `.vscode/tasks.json` configured like this: ``` { "version": "2.0.0", "tasks": [ { "label": "Compile compact file to JS", "type": "shell", "command": "npx compact compile --vscode --skip-zk ${file} ${workspaceFolder}/src/managed", "group": "build", "presentation": { "echo": true, "reveal": "never", "focus": false, "panel": "shared", "showReuseMessage": false, "clear": true, "revealProblems": "onProblem" }, "problemMatcher": [ "$compactException", "$compactInternal", "$compactCommandNotFound" ] } ] } ``` The preceding configuration uses the Compact compiler flag `--skip-zk` to skip the generation of circuits, which can take a long time and may be unnecessary when you only want to the compiler to check your syntax. Moreover, you can configure a `problemMatcher` for VS Code: ``` "problemMatcher": [ "$compactException", "$compactInternal", "$compactCommandNotFound" ] ``` so that all errors reported by the compiler will be shown on the **Problems** tab. ### Code snippets[​](#code-snippets "Direct link to Code snippets") The VS Code extension provides the following [code snippets](https://code.visualstudio.com/docs/editor/userdefinedsnippets) when editing Compact smart contracts: * `ledger` (`state`) * `constructor` in ledger * potentially exported `circuit` (`function` / `transition`) * `witness` (`private` function) * constructor * import Compact `standard library` (`init`, `stdlib`) * `if` statement (`cond`) * `map` (`for`) * `fold` * `enum` * `struct` * `module` * `assert` * `pragma` There is also a `compact` template, which will generate a simple Compact skeleton for a contract. ![Code snippets and errors](/assets/images/code-snippets-errors-6017f43d451ce0ec358c4a8c1fdfa6ae.gif) ### New Compact smart contract[​](#new-compact-smart-contract "Direct link to New Compact smart contract") If you are creating DApp, you can create a new smart contract with an empty ledger and a single circuit as follows: 1. Bring up the commands pallette (Cmd+Shift+P). 2. Select **Snippets: Fill File with Snippet**. 3. Select **Compact**. Be aware: if you perform these steps in an existing file, the contents of the file are overwritten. Other snippets are available from inside the file. Just start typing the name of the function. ![File template](/assets/images/file-template-948ccce3632ac1881582a420a797e703.gif) ## License[​](#license "Direct link to License") The Visual Studio Code extension for Compact is distributed under the Apache 2.0 license. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Ledger data types Compact language version 0.26.0, compiler version 0.34.0. ## Kernel[​](#kernel "Direct link to Kernel") This ADT is a special ADT defining various built-in operations and valid only as a top-level ADT type. ### balance[​](#balance "Direct link to balance") ``` balance(token_type: Either, Bytes<32>>): Uint<128> ``` Returns the current contract's balance of the unshielded token of the given token type. The balance is not updated during contract execution as a result of unshielded sends and receives. It is always fixed to the value provided at the start of execution. ### balanceGreaterThan[​](#balancegreaterthan "Direct link to balanceGreaterThan") ``` balanceGreaterThan(token_type: Either, Bytes<32>>, amount: Uint<128>): Boolean ``` Checks whether the current balance of the unshielded token of the given type is greater than the given amount. ### balanceLessThan[​](#balancelessthan "Direct link to balanceLessThan") ``` balanceLessThan(token_type: Either, Bytes<32>>, amount: Uint<128>): Boolean ``` Checks whether the current balance of the unshielded token of the given type is less than the given amount. ### blockTimeGreaterThan[​](#blocktimegreaterthan "Direct link to blockTimeGreaterThan") ``` blockTimeGreaterThan(time: Uint<64>): Boolean ``` Checks whether the current block time (measured in seconds since the Unix epoch) is greater than the given amount. ### blockTimeLessThan[​](#blocktimelessthan "Direct link to blockTimeLessThan") ``` blockTimeLessThan(time: Uint<64>): Boolean ``` Checks whether the current block time (measured in seconds since the Unix epoch) is less than the given amount. ### checkpoint[​](#checkpoint "Direct link to checkpoint") ``` checkpoint(): [] ``` Marks all execution up to this point as being a single atomic unit, allowing partial transaction failures to be split across it. ### claimContractCall[​](#claimcontractcall "Direct link to claimContractCall") ``` claimContractCall(addr: Bytes<32>, entry_point: Bytes<32>, comm: Field): [] ``` Require the presence of another contract call in the containing transaction, with a match address, entry point hash, and communication commitment, that is not claimed by any other call. ### claimUnshieldedCoinSpend[​](#claimunshieldedcoinspend "Direct link to claimUnshieldedCoinSpend") ``` claimUnshieldedCoinSpend(token_type: Either, Bytes<32>>, address: Either, amount: Uint<128>): [] ``` Claims an unshielded coin spend - authorizes an unshielded coin of the given token type to be transferred to the given address. ### claimZswapCoinReceive[​](#claimzswapcoinreceive "Direct link to claimZswapCoinReceive") ``` claimZswapCoinReceive(note: Bytes<32>): [] ``` Requires the presence of a commitment in the containing transaction and that no other call claims it as a receive. ### claimZswapCoinSpend[​](#claimzswapcoinspend "Direct link to claimZswapCoinSpend") ``` claimZswapCoinSpend(note: Bytes<32>): [] ``` Requires the presence of a commitment in the containing transaction and that no other call claims it as a spend. ### claimZswapNullifier[​](#claimzswapnullifier "Direct link to claimZswapNullifier") ``` claimZswapNullifier(nul: Bytes<32>): [] ``` Requires the presence of a nullifier in the containing transaction and that no other call claims it. ### incUnshieldedInputs[​](#incunshieldedinputs "Direct link to incUnshieldedInputs") ``` incUnshieldedInputs(token_type: Either, Bytes<32>>, amount: Uint<128>): [] ``` Increments the unshielded input for the token of the given token type by the given amount - used when receiving tokens. ### incUnshieldedOutputs[​](#incunshieldedoutputs "Direct link to incUnshieldedOutputs") ``` incUnshieldedOutputs(token_type: Either, Bytes<32>>, amount: Uint<128>): [] ``` Increments the unshielded output for the token of the given token type by the given amount - used when sending tokens. ### mintShielded[​](#mintshielded "Direct link to mintShielded") ``` mintShielded(domain_sep: Bytes<32>, amount: Uint<64>): [] ``` Mints a given amount of shielded coins with a token type derived from the contract's address, and a given domain separator. ### mintUnshielded[​](#mintunshielded "Direct link to mintUnshielded") ``` mintUnshielded(domain_sep: Bytes<32>, amount: Uint<64>): [] ``` Mints a given amount of unshielded coins with a token type derived from the contract's address, and a given domain separator. ### self[​](#self "Direct link to self") ``` self(): ContractAddress ``` Returns the current contract's address. ContractAddress is defined in CompactStandardLibrary. ## Cell\[​](#cellvalue_type "Direct link to Cell") This ADT is a single Cell containing a value of type value\_type and is used implicitly when the ledger field type is an ordinary Compact type. Programmers cannot write Cell explicitly when declaring a ledger field.. ### read[​](#read "Direct link to read") ``` read(): value_type ``` Returns the current contents of this Cell. *available from Typescript as a getter on the ledger field* ### resetToDefault[​](#resettodefault "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Cell to the default value of its type. ### write[​](#write "Direct link to write") ``` write(value: value_type): [] ``` Overwrites the content of this Cell with the given value. ### writeCoin[​](#writecoin "Direct link to writeCoin") ``` writeCoin(coin: ShieldedCoinInfo, recipient: Either): [] ``` Writes a ShieldedCoinInfo to this Cell, which is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this write fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ## Counter[​](#counter "Direct link to Counter") This ADT is a simple counter. ### decrement[​](#decrement "Direct link to decrement") ``` decrement(amount: Uint<16>): [] ``` Decrements the counter by a given amount. Decrementing below zero results in a run-time error. ### increment[​](#increment "Direct link to increment") ``` increment(amount: Uint<16>): [] ``` Increments the counter by the given amount. ### lessThan[​](#lessthan "Direct link to lessThan") ``` lessThan(threshold: Uint<64>): Boolean ``` Returns if the counter is less than the given threshold value. ### read[​](#read-1 "Direct link to read") ``` read(): Uint<64> ``` Retrieves the current value of the counter. *available from Typescript as a getter on the ledger field* ### resetToDefault[​](#resettodefault-1 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Counter to its default value of 0. ## Set\[​](#setvalue_type "Direct link to Set") This ADT is an unbounded set of values of type value\_type. ### insert[​](#insert "Direct link to insert") ``` insert(elem: value_type): [] ``` Updates this Set to include a given element. ### insertCoin[​](#insertcoin "Direct link to insertCoin") ``` insertCoin(coin: ShieldedCoinInfo, recipient: Either): [] ``` Inserts a ShieldedCoinInfo into this Set, which is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this insertion fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ### isEmpty[​](#isempty "Direct link to isEmpty") ``` isEmpty(): Boolean ``` Returns whether this Set is the empty set. *available from Typescript as `isEmpty(): boolean`* ### member[​](#member "Direct link to member") ``` member(elem: value_type): Boolean ``` Returns if an element is contained within this Set. *available from Typescript as `member(elem: value_type): boolean`* ### remove[​](#remove "Direct link to remove") ``` remove(elem: value_type): [] ``` Update this Set to not include a given element. ### resetToDefault[​](#resettodefault-2 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Set to the empty set. ### size[​](#size "Direct link to size") ``` size(): Uint<64> ``` Returns the number of unique entries in this Set. *available from Typescript as `size(): bigint`* ### \[Symbol.iterator][​](#symboliterator "Direct link to \[Symbol.iterator]") *callable only from TypeScript* ``` [Symbol.iterator](): Iterator ``` Iterates over the entries in this Set. ## Map\[​](#mapkey_type-value_type "Direct link to Map") This ADT is an unbounded set of mappings between values of type key\_type and values of type value\_type. ### insert[​](#insert-1 "Direct link to insert") ``` insert(key: key_type, value: value_type): [] ``` Updates this Map to include a new value at a given key. ### insertCoin[​](#insertcoin-1 "Direct link to insertCoin") ``` insertCoin(key: key_type, coin: ShieldedCoinInfo, recipient: Either): [] ``` Inserts a ShieldedCoinInfo into this Map at a given key, where the ShieldedCoinInfo is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this insertion fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ### insertDefault[​](#insertdefault "Direct link to insertDefault") ``` insertDefault(key: key_type): [] ``` Updates this Map to include the value type's default value at a given key. ### isEmpty[​](#isempty-1 "Direct link to isEmpty") ``` isEmpty(): Boolean ``` Returns if this Map is the empty map. *available from Typescript as `isEmpty(): boolean`* ### lookup[​](#lookup "Direct link to lookup") ``` lookup(key: key_type): value_type ``` Looks up the value of a key within this Map. The returned value may be another ADT. *available from Typescript as `lookup(key: key_type): value_type`* ### member[​](#member-1 "Direct link to member") ``` member(key: key_type): Boolean ``` Returns if a key is contained within this Map. *available from Typescript as `member(key: key_type): boolean`* ### remove[​](#remove-1 "Direct link to remove") ``` remove(key: key_type): [] ``` Updates this Map to not include a given key. ### resetToDefault[​](#resettodefault-3 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Map to the empty map. ### size[​](#size-1 "Direct link to size") ``` size(): Uint<64> ``` Returns the number of entries in this Map. *available from Typescript as `size(): bigint`* ### \[Symbol.iterator][​](#symboliterator-1 "Direct link to \[Symbol.iterator]") *callable only from TypeScript* ``` [Symbol.iterator](): Iterator<[key_type, value_type]> ``` Iterates over the key-value pairs contained in this Map. ## List\[​](#listvalue_type "Direct link to List") This ADT is an unbounded list of values of type value\_type. ### head[​](#head "Direct link to head") ``` head(): Maybe ``` Retrieves the head of this List, returning a Maybe, ensuring this call succeeds on the empty list. Maybe is defined in CompactStandardLibrary (compact-runtime from Typescript). *available from Typescript as `head(): Maybe`* ### isEmpty[​](#isempty-2 "Direct link to isEmpty") ``` isEmpty(): Boolean ``` Returns if this List is the empty list. *available from Typescript as `isEmpty(): boolean`* ### length[​](#length "Direct link to length") ``` length(): Uint<64> ``` Returns the number of elements contained in this List. *available from Typescript as `length(): bigint`* ### popFront[​](#popfront "Direct link to popFront") ``` popFront(): [] ``` Removes the first element from the front of this list. ### pushFront[​](#pushfront "Direct link to pushFront") ``` pushFront(value: value_type): [] ``` Pushes a new element onto the front of this list. ### pushFrontCoin[​](#pushfrontcoin "Direct link to pushFrontCoin") ``` pushFrontCoin(coin: ShieldedCoinInfo, recipient: Either): [] ``` Pushes a ShieldedCoinInfo onto the front of this List, where the ShieldedCoinInfo is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this push fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ### resetToDefault[​](#resettodefault-4 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this List to the empty list. ### \[Symbol.iterator][​](#symboliterator-2 "Direct link to \[Symbol.iterator]") *callable only from TypeScript* ``` [Symbol.iterator](): Iterator ``` Iterates over the entries in this List. ## MerkleTree\[​](#merkletreenat-value_type "Direct link to MerkleTree") This ADT is a bounded Merkle tree of depth nat where 2 `<=` nat `<= 32` containing values of type value\_type. ### checkRoot[​](#checkroot "Direct link to checkRoot") ``` checkRoot(rt: MerkleTreeDigest): Boolean ``` Tests if the given Merkle tree root is the root for this Merkle tree. MerkleTreeDigest is defined in CompactStandardLibrary (compact-runtime from Typescript). *available from Typescript as `checkRoot(rt: MerkleTreeDigest): boolean`* ### insert[​](#insert-2 "Direct link to insert") ``` insert(item: value_type): [] ``` Inserts a new leaf at the first free index in this Merkle tree. ### insertHash[​](#inserthash "Direct link to insertHash") ``` insertHash(hash: Bytes<32>): [] ``` Inserts a new leaf with a given hash at the first free index in this Merkle tree. ### insertHashIndex[​](#inserthashindex "Direct link to insertHashIndex") ``` insertHashIndex(hash: Bytes<32>, index: Uint<64>): [] ``` Inserts a new leaf with a given hash at a specific index in this Merkle tree. ### insertIndex[​](#insertindex "Direct link to insertIndex") ``` insertIndex(item: value_type, index: Uint<64>): [] ``` Inserts a new leaf at a specific index in this Merkle tree. ### insertIndexDefault[​](#insertindexdefault "Direct link to insertIndexDefault") ``` insertIndexDefault(index: Uint<64>): [] ``` Inserts a default value leaf at a specific index in this Merkle tree. This can be used to emulate a removal from the tree. ### isFull[​](#isfull "Direct link to isFull") ``` isFull(): Boolean ``` Returns if this Merkle tree is full and further items cannot be directly inserted. *available from Typescript as `isFull(): boolean`* ### resetToDefault[​](#resettodefault-5 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Merkle tree to the empty Merkle tree. ### findPathForLeaf[​](#findpathforleaf "Direct link to findPathForLeaf") *callable only from TypeScript* ``` findPathForLeaf(leaf: value_type): MerkleTreePath | undefined ``` Finds the path for a given leaf in a Merkle tree. Be warned that this is O(n) and should be avoided for large trees. Returns undefined if no such leaf exists. MerkleTreePath is defined in compact-runtime. ### firstFree[​](#firstfree "Direct link to firstFree") *callable only from TypeScript* ``` firstFree(): bigint ``` Retrieves the first (guaranteed) free index in the Merkle tree. ### pathForLeaf[​](#pathforleaf "Direct link to pathForLeaf") *callable only from TypeScript* ``` pathForLeaf(index: bigint, leaf: value_type): MerkleTreePath ``` Returns the Merkle path, given the knowledge that a specified leaf is at the given index. It is an error to call this if this leaf is not contained at the given index. MerkleTreePath is defined in compact-runtime. ### root[​](#root "Direct link to root") *callable only from TypeScript* ``` root(): MerkleTreeDigest ``` Retrieves the root of the Merkle tree. MerkleTreeDigest is defined in compact-runtime. ## HistoricMerkleTree\[​](#historicmerkletreenat-value_type "Direct link to HistoricMerkleTree") This ADT is a bounded Merkle tree of depth nat where 2 `<=` nat `<=` 32 containing values of type value\_type, with history. ### checkRoot[​](#checkroot-1 "Direct link to checkRoot") ``` checkRoot(rt: MerkleTreeDigest): Boolean ``` Tests if the given Merkle tree root is one of the past roots for this Merkle tree. MerkleTreeDigest is defined in CompactStandardLibrary (compact-runtime from Typescript). *available from Typescript as `checkRoot(rt: MerkleTreeDigest): boolean`* ### insert[​](#insert-3 "Direct link to insert") ``` insert(item: value_type): [] ``` Inserts a new leaf at the first free index in this Merkle tree. ### insertHash[​](#inserthash-1 "Direct link to insertHash") ``` insertHash(hash: Bytes<32>): [] ``` Inserts a new leaf with a given hash at the first free index in this Merkle tree. ### insertHashIndex[​](#inserthashindex-1 "Direct link to insertHashIndex") ``` insertHashIndex(hash: Bytes<32>, index: Uint<64>): [] ``` Inserts a new leaf with a given hash at a specific index in this Merkle tree. ### insertIndex[​](#insertindex-1 "Direct link to insertIndex") ``` insertIndex(item: value_type, index: Uint<64>): [] ``` Inserts a new leaf at a specific index in this Merkle tree. ### insertIndexDefault[​](#insertindexdefault-1 "Direct link to insertIndexDefault") ``` insertIndexDefault(index: Uint<64>): [] ``` Inserts a default value leaf at a specific index in this Merkle tree. This can be used to emulate a removal from the tree. ### isFull[​](#isfull-1 "Direct link to isFull") ``` isFull(): Boolean ``` Returns if this Merkle tree is full and further items cannot be directly inserted. *available from Typescript as `isFull(): boolean`* ### resetHistory[​](#resethistory "Direct link to resetHistory") ``` resetHistory(): [] ``` Resets the history for this Merkle tree, leaving only the current root valid. ### resetToDefault[​](#resettodefault-6 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Merkle tree to the empty Merkle tree. ### findPathForLeaf[​](#findpathforleaf-1 "Direct link to findPathForLeaf") *callable only from TypeScript* ``` findPathForLeaf(leaf: value_type): MerkleTreePath | undefined ``` Finds the path for a given leaf in a Merkle tree. Be warned that this is O(n) and should be avoided for large trees. Returns undefined if no such leaf exists. MerkleTreePath is defined in compact-runtime. ### firstFree[​](#firstfree-1 "Direct link to firstFree") *callable only from TypeScript* ``` firstFree(): bigint ``` Retrieves the first (guaranteed) free index in the Merkle tree. ### history[​](#history "Direct link to history") *callable only from TypeScript* ``` history(): Iterator ``` An iterator over the roots that are considered valid past roots for this Merkle tree. MerkleTreeDigest is defined in compact-runtime. ### pathForLeaf[​](#pathforleaf-1 "Direct link to pathForLeaf") *callable only from TypeScript* ``` pathForLeaf(index: bigint, leaf: value_type): MerkleTreePath ``` Returns the Merkle path, given the knowledge that a specified leaf is at the given index. It is an error to call this if the index is out of bounds. MerkleTreePath is defined in compact-runtime. ### root[​](#root-1 "Direct link to root") *callable only from TypeScript* ``` root(): MerkleTreeDigest ``` Retrieves the root of the Merkle tree. MerkleTreeDigest is defined in compact-runtime. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Opaque data types Data types whose representations are visible are called transparent. These expose the inner structure of the data so that operations on the data can be understood. Drawbacks to having transparent data types include lesser type safety (or type soundness) - how a programming language discourages or prevents type errors, such as assigning the wrong type to a variable. Opaque data types present an interface without sharing the actual, concrete data structure. These can only be manipulated by calling subroutines that have access to knowledge about the missing structure. The principle of information hiding, segregating design decisions from the underlying software implementation, results in more resilient code. Implementations can be improved or changed completely without the fragility that comes from inner details being depended upon. Defensively coding the parts most likely to change results in more robust code overall. # Midnight opaque data types Opaque types in Compact are a compact type system feature that allow "foreign" JavaScript data to be stored, passed around, and retrieved on behalf of a DApp (but not inspected by Compact code). Midnight’s Compact language currently supports `Opaque<'string'>` and `Opaque<'Uint8Array'>`. These can be stored in a contract's public state. NOTE: These are opaque only within Compact. They are transparent in a DApp's JavaScript code. Their representation on-chain is **NOT** hidden - `Uint8Array` is represented by the array of bytes and `string` is represented by its UTF-8 encoding. # Examples The Bulletin Board example DApp, in the developer tutorial, has an example of opaque data type usage. * The Compact post circuit is a contract entry point that's called from a DApp and passed an `Opaque<'string'>`. Compact code can't look inside this; it does store it in the contract's public state. * Later, the Compact take\_down circuit reads this value and returns it to the JavaScript or TypeScript caller. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact grammar Compact language version 0.26.0. Notational note: In the grammar below, keywords and punctuation are in `monospaced` font. Terminal and nonterminal names are in *emphasized* font. Alternation is indicated by a vertical bar (`|`). Optional items are indicated by the superscript opt. Repetition is specified by ellipses. The notation *X* ⋯ *X*, where *X* is a grammar symbol, represents zero or more occurrences of *X*. The notation *X* `,` ⋯ `,` *X*, where *X* is a grammar symbol and `,` is a literal comma, represents zero or more occurrences of *X* separated by commas. In either case, when the ellipsis is marked with the superscript 1, the notation represents a sequence containing at least one *X*. When such a sequence is followed by *,*opt, an optional trailing comma is allowed, but only if there is at least one *X*. For example, *id* ⋯ *id* represents zero or more *id*s, and *expr* `,` ⋯¹`,` *expr* `,`opt represents one or more comma-separated *expr*s possibly followed by an extra comma. The rules involving commas apply equally to semicolons, i.e., apply when `,` is replaced by `;`. #### identifier[​](#identifier "Direct link to identifier") *id*, *module-name*, *function-name*, *struct-name*, *enum-name*, *contract-name*, *tvar-name*, *type-name* Identifiers have the same syntax as Typescript identifiers. #### field-literal[​](#field-literal "Direct link to field-literal") *nat* A field literal is 0 or a natural number formed from a sequence of digits starting with 1-9, e.g. 723, whose value does not exceed the maximum field value. #### string-literal[​](#string-literal "Direct link to string-literal") *str*, *file* A string literal has the same syntax as a Typescript string. #### version-literal[​](#version-literal "Direct link to version-literal") *version* A version literal takes the form nat.nat representing major and minor versions or nat.nat.nat representing major, minor, and bugfix versions. Where version literals are allowed, a plain nat representing just the major version is also allowed. #### Compact[​](#compact "Direct link to Compact") | | | | | --------- | - | ----------------------------------------------------------------------------- | | *program* | ⟶ | [*program-element*](#program-element) ⋯ [*program-element*](#program-element) | #### Program-element[​](#program-element "Direct link to Program-element") | | | | | ----------------- | -- | ------------------------------------------------------------ | | *program-element* | ⟶ | [*pragma-form*](#pragma) | | | \| | [*module-definition*](#module-definition) | | | \| | [*import-form*](#import-declaration) | | | \| | [*export-form*](#export-declaration) | | | \| | [*include-form*](#include) | | | \| | [*struct-declaration*](#structure-declaration) | | | \| | [*enum-declaration*](#enum-declaration) | | | \| | [*contract-declaration*](#external-contract-declaration) | | | \| | [*implements-declaration*](#contract-implements-declaration) | | | \| | [*type-alias-declaration*](#type-declaration) | | | \| | [*ledger-declaration*](#ledger-declaration) | | | \| | [*witness-declaration*](#witness-declaration) | | | \| | [*constructor-definition*](#constructor) | | | \| | [*circuit-definition*](#circuit-definition) | #### Pragma[​](#pragma "Direct link to Pragma") | | | | | ------------- | - | ---------------------------------------------------------------------- | | *pragma-form* | ⟶ | `pragma` [*id*](#identifier) [*version-expr*](#version-expression) `;` | #### Version-expression[​](#version-expression "Direct link to Version-expression") | | | | | -------------- | -- | ------------------------------------------------------------------------------------ | | *version-expr* | ⟶ | [*version-expr*](#version-expression) `\|\|` [*version-expr0*](#version-expression0) | | | \| | [*version-expr0*](#version-expression0) | #### Version-expression0[​](#version-expression0 "Direct link to version-expression0") | | | | | --------------- | -- | ---------------------------------------------------------------------------- | | *version-expr0* | ⟶ | [*version-expr0*](#version-expression0) `&&` [*version-term*](#version-term) | | | \| | [*version-term*](#version-term) | #### Version-Term[​](#version-term "Direct link to Version-Term") | | | | | -------------- | -- | --------------------------------------------- | | *version-term* | ⟶ | [*version-atom*](#version-atom) | | | \| | `!` [*version-atom*](#version-atom) | | | \| | `<` [*version-atom*](#version-atom) | | | \| | `<=` [*version-atom*](#version-atom) | | | \| | `>=` [*version-atom*](#version-atom) | | | \| | `>` [*version-atom*](#version-atom) | | | \| | `(` [*version-expr*](#version-expression) `)` | #### Version-atom[​](#version-atom "Direct link to Version-atom") | | | | | -------------- | -- | ----------------------------- | | *version-atom* | ⟶ | [*nat*](#field-literal) | | | \| | [*version*](#version-literal) | #### Include[​](#include "Direct link to Include") | | | | | -------------- | - | --------------------------------------- | | *include-form* | ⟶ | `include` [*file*](#string-literal) `;` | #### Module-definition[​](#module-definition "Direct link to Module-definition") | | | | | ------------------- | - | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *module-definition* | ⟶ | `export`opt `module` [*module-name*](#identifier) [*gparams*](#generic-parameter-list)opt `{` [*program-element*](#program-element) ⋯ [*program-element*](#program-element) `}` | #### Generic-parameter-list[​](#generic-parameter-list "Direct link to Generic-parameter-list") | | | | | --------- | - | ---------------------------------------------------------------------------------------------------- | | *gparams* | ⟶ | `<` [*generic-param*](#generic-parameter) `,` ⋯ `,` [*generic-param*](#generic-parameter) `,`opt `>` | #### Generic-parameter[​](#generic-parameter "Direct link to Generic-parameter") | | | | | --------------- | -- | ------------------------------ | | *generic-param* | ⟶ | `#` [*tvar-name*](#identifier) | | | \| | [*tvar-name*](#identifier) | #### Import-declaration[​](#import-declaration "Direct link to Import-declaration") | | | | | ------------- | - | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *import-form* | ⟶ | `import` [*import-selection*](#import-selection)opt [*import-name*](#import-name) [*gargs*](#generic-argument-list)opt [*import-prefix*](#import-prefix)opt `;` | #### Import-selection[​](#import-selection "Direct link to Import-selection") | | | | | ------------------ | - | ------------------------------------------------------------------------------------------------------- | | *import-selection* | ⟶ | `{` [*import-element*](#import-element) `,` ⋯ `,` [*import-element*](#import-element) `,`opt `}` `from` | #### Import-element[​](#import-element "Direct link to Import-element") | | | | | ---------------- | -- | -------------------------------------------- | | *import-element* | ⟶ | [*id*](#identifier) | | | \| | [*id*](#identifier) `as` [*id*](#identifier) | #### Import-name[​](#import-name "Direct link to Import-name") | | | | | ------------- | -- | ------------------------- | | *import-name* | ⟶ | [*id*](#identifier) | | | \| | [*file*](#string-literal) | #### Import-prefix[​](#import-prefix "Direct link to Import-prefix") | | | | | --------------- | - | ---------------------------- | | *import-prefix* | ⟶ | `prefix` [*id*](#identifier) | #### Generic-argument-list[​](#generic-argument-list "Direct link to Generic-argument-list") | | | | | ------- | - | -------------------------------------------------------------------------------- | | *gargs* | ⟶ | `<` [*garg*](#generic-argument) `,` ⋯ `,` [*garg*](#generic-argument) `,`opt `>` | #### Generic-argument[​](#generic-argument "Direct link to Generic-argument") | | | | | ------ | -- | ----------------------- | | *garg* | ⟶ | [*nat*](#field-literal) | | | \| | [*type*](#type) | #### Export-declaration[​](#export-declaration "Direct link to Export-declaration") | | | | | ------------- | - | -------------------------------------------------------------------------------- | | *export-form* | ⟶ | `export` `{` [*id*](#identifier) `,` ⋯ `,` [*id*](#identifier) `,`opt `}` `;`opt | #### Ledger-declaration[​](#ledger-declaration "Direct link to Ledger-declaration") | | | | | -------------------- | - | ---------------------------------------------------------------------------- | | *ledger-declaration* | ⟶ | `export`opt `sealed`opt `ledger` [*id*](#identifier) `:` [*type*](#type) `;` | #### Witness-declaration[​](#witness-declaration "Direct link to Witness-declaration") | | | | | --------------------- | - | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | *witness-declaration* | ⟶ | `export`opt `witness` [*id*](#identifier) [*gparams*](#generic-parameter-list)opt [*simple-parameter-list*](#simple-parameter-list) `:` [*type*](#type) `;` | #### Constructor[​](#constructor "Direct link to Constructor") | | | | | ------------------------ | - | ----------------------------------------------------------------------------------- | | *constructor-definition* | ⟶ | `constructor` [*pattern-parameter-list*](#pattern-parameter-list) [*block*](#block) | #### Circuit-definition[​](#circuit-definition "Direct link to Circuit-definition") | | | | | -------------------- | - | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | *circuit-definition* | ⟶ | `export`opt `pure`opt `circuit` [*function-name*](#identifier) [*gparams*](#generic-parameter-list)opt [*pattern-parameter-list*](#pattern-parameter-list) `:` [*type*](#type) [*block*](#block) | #### Structure-declaration[​](#structure-declaration "Direct link to Structure-declaration") | | | | | -------------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *struct-declaration* | ⟶ | `export`opt `struct` [*struct-name*](#identifier) [*gparams*](#generic-parameter-list)opt `{` [*typed-id*](#typed-identifier) `;` ⋯ `;` [*typed-id*](#typed-identifier) `;`opt `}` `;`opt | | | \| | `export`opt `struct` [*struct-name*](#identifier) [*gparams*](#generic-parameter-list)opt `{` [*typed-id*](#typed-identifier) `,` ⋯ `,` [*typed-id*](#typed-identifier) `,`opt `}` `;`opt | #### Enum-declaration[​](#enum-declaration "Direct link to Enum-declaration") | | | | | ------------------ | - | ---------------------------------------------------------------------------------------------------------------------- | | *enum-declaration* | ⟶ | `export`opt `enum` [*enum-name*](#identifier) `{` [*id*](#identifier) `,` ⋯¹ `,` [*id*](#identifier) `,`opt `}` `;`opt | #### Contract-Implements-declaration[​](#contract-implements-declaration "Direct link to Contract-Implements-declaration") | | | | | ------------------------ | - | ------------------------------------------- | | *implements-declaration* | ⟶ | `contract` `implements` [*type*](#type) `;` | #### External-contract-declaration[​](#external-contract-declaration "Direct link to External-contract-declaration") | | | | | ---------------------- | -- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *contract-declaration* | ⟶ | `export`opt `contract` [*contract-name*](#identifier) `{` [*circuit-declaration*](#external-contract-circuit) `;` ⋯ `;` [*circuit-declaration*](#external-contract-circuit) `;`opt `}` `;`opt | | | \| | `export`opt `contract` [*contract-name*](#identifier) `{` [*circuit-declaration*](#external-contract-circuit) `,` ⋯ `,` [*circuit-declaration*](#external-contract-circuit) `,`opt `}` `;`opt | #### External-contract-circuit[​](#external-contract-circuit "Direct link to External-contract-circuit") | | | | | --------------------- | - | ------------------------------------------------------------------------------------------------------------- | | *circuit-declaration* | ⟶ | `pure`opt `circuit` [*id*](#identifier) [*simple-parameter-list*](#simple-parameter-list) `:` [*type*](#type) | #### Type-declaration[​](#type-declaration "Direct link to Type-declaration") | | | | | ------------------------ | - | ---------------------------------------------------------------------------------------------------------------------- | | *type-alias-declaration* | ⟶ | `export`opt `new`opt `type` [*type-name*](#identifier) [*gparams*](#generic-parameter-list)opt `=` [*type*](#type) `;` | #### Typed-identifier[​](#typed-identifier "Direct link to Typed-identifier") | | | | | ---------- | - | --------------------------------------- | | *typed-id* | ⟶ | [*id*](#identifier) `:` [*type*](#type) | #### Simple-parameter-list[​](#simple-parameter-list "Direct link to Simple-parameter-list") | | | | | ----------------------- | - | ---------------------------------------------------------------------------------------- | | *simple-parameter-list* | ⟶ | `(` [*typed-id*](#typed-identifier) `,` ⋯ `,` [*typed-id*](#typed-identifier) `,`opt `)` | #### Typed-pattern[​](#typed-pattern "Direct link to Typed-pattern") | | | | | --------------- | - | ----------------------------------------- | | *typed-pattern* | ⟶ | [*pattern*](#pattern) `:` [*type*](#type) | #### Pattern-parameter-list[​](#pattern-parameter-list "Direct link to Pattern-parameter-list") | | | | | ------------------------ | - | -------------------------------------------------------------------------------------------- | | *pattern-parameter-list* | ⟶ | `(` [*typed-pattern*](#typed-pattern) `,` ⋯ `,` [*typed-pattern*](#typed-pattern) `,`opt `)` | #### Type[​](#type "Direct link to Type") | | | | | ------ | -- | --------------------------------------------------------------- | | *type* | ⟶ | [*tref*](#type-reference) | | | \| | `Boolean` | | | \| | `Field` | | | \| | `Uint` `<` [*tsize*](#type-size) `>` | | | \| | `Uint` `<` [*tsize*](#type-size) `..` [*tsize*](#type-size) `>` | | | \| | `Bytes` `<` [*tsize*](#type-size) `>` | | | \| | `Opaque` `<` [*str*](#string-literal) `>` | | | \| | `Vector` `<` [*tsize*](#type-size) `,` [*type*](#type) `>` | | | \| | `[` [*type*](#type) `,` ⋯ `,` [*type*](#type) `,`opt `]` | #### Type-reference[​](#type-reference "Direct link to Type-reference") | | | | | ------ | - | -------------------------------------------------------- | | *tref* | ⟶ | [*id*](#identifier) [*gargs*](#generic-argument-list)opt | #### Type-size[​](#type-size "Direct link to Type-size") | | | | | ------- | -- | ----------------------- | | *tsize* | ⟶ | [*nat*](#field-literal) | | | \| | [*id*](#identifier) | | *start* | ⟶ | [*tsize*](#type-size) | | *end* | ⟶ | [*tsize*](#type-size) | #### Block[​](#block "Direct link to Block") | | | | | ------- | - | --------------------------------------------------- | | *block* | ⟶ | `{` [*stmt*](#statement) ⋯ [*stmt*](#statement) `}` | #### Statement[​](#statement "Direct link to Statement") | | | | | ------ | -- | -------------------------------------------------------------------- | | *stmt* | ⟶ | `if` `(` [*expr-seq*](#expression-sequence) `)` [*stmt*](#statement) | | | \| | [*stmt0*](#statement0) | #### Statement0[​](#statement0 "Direct link to statement0") | | | | | ------- | -- | ------------------------------------------------------------------------------------------------------------------ | | *stmt0* | ⟶ | [*expr-seq*](#expression-sequence) `;` | | | \| | `const` [*cbinding*](#const-binding) `,` ⋯¹ `,` [*cbinding*](#const-binding) `;` | | | \| | `if` `(` [*expr-seq*](#expression-sequence) `)` [*stmt0*](#statement0) `else` [*stmt*](#statement) | | | \| | `for` `(` `const` [*id*](#identifier) `of` [*start*](#type-size) `..` [*end*](#type-size) `)` [*stmt*](#statement) | | | \| | `for` `(` `const` [*id*](#identifier) `of` [*expr-seq*](#expression-sequence) `)` [*stmt*](#statement) | | | \| | `return` [*expr-seq*](#expression-sequence) `;` | | | \| | `return` `;` | | | \| | [*block*](#block) | #### Pattern[​](#pattern "Direct link to Pattern") | | | | | --------- | -- | ------------------------------------------------------------------------------------------------------------------------ | | *pattern* | ⟶ | [*id*](#identifier) | | | \| | `[` [*pattern*](#pattern)opt `,` ⋯ `,` [*pattern*](#pattern)opt `,`opt `]` | | | \| | `{` [*pattern-struct-elt*](#pattern-struct-element) `,` ⋯ `,` [*pattern-struct-elt*](#pattern-struct-element) `,`opt `}` | #### Pattern-struct-element[​](#pattern-struct-element "Direct link to Pattern-struct-element") | | | | | -------------------- | -- | --------------------------------------------- | | *pattern-struct-elt* | ⟶ | [*id*](#identifier) | | | \| | [*id*](#identifier) `:` [*pattern*](#pattern) | #### Expression-sequence[​](#expression-sequence "Direct link to Expression-sequence") | | | | | ---------- | -- | -------------------------------------------------------------------------------- | | *expr-seq* | ⟶ | [*expr*](#expression) | | | \| | [*expr*](#expression) `,` ⋯¹ `,` [*expr*](#expression) `,` [*expr*](#expression) | #### Expression[​](#expression "Direct link to Expression") | | | | | ------ | -- | --------------------------------------------------------------------------- | | *expr* | ⟶ | [*expr0*](#expression0) `?` [*expr*](#expression) `:` [*expr*](#expression) | | | \| | [*expr0*](#expression0) `=` [*expr*](#expression) | | | \| | [*expr0*](#expression0) `+=` [*expr*](#expression) | | | \| | [*expr0*](#expression0) `-=` [*expr*](#expression) | | | \| | [*expr0*](#expression0) | #### Expression0[​](#expression0 "Direct link to expression0") | | | | | ------- | -- | ------------------------------------------------------ | | *expr0* | ⟶ | [*expr0*](#expression0) `\|\|` [*expr1*](#expression1) | | | \| | [*expr1*](#expression1) | #### Expression1[​](#expression1 "Direct link to expression1") | | | | | ------- | -- | ---------------------------------------------------- | | *expr1* | ⟶ | [*expr1*](#expression1) `&&` [*expr2*](#expression2) | | | \| | [*expr2*](#expression2) | #### Expression2[​](#expression2 "Direct link to expression2") | | | | | ------- | -- | ---------------------------------------------------- | | *expr2* | ⟶ | [*expr2*](#expression2) `==` [*expr3*](#expression3) | | | \| | [*expr2*](#expression2) `!=` [*expr3*](#expression3) | | | \| | [*expr3*](#expression3) | #### Expression3[​](#expression3 "Direct link to expression3") | | | | | ------- | -- | ---------------------------------------------------- | | *expr3* | ⟶ | [*expr4*](#expression4) `<` [*expr4*](#expression4) | | | \| | [*expr4*](#expression4) `<=` [*expr4*](#expression4) | | | \| | [*expr4*](#expression4) `>=` [*expr4*](#expression4) | | | \| | [*expr4*](#expression4) `>` [*expr4*](#expression4) | | | \| | [*expr4*](#expression4) | #### Expression4[​](#expression4 "Direct link to expression4") | | | | | ------- | -- | -------------------------------------------- | | *expr4* | ⟶ | [*expr4*](#expression4) `as` [*type*](#type) | | | \| | [*expr5*](#expression5) | #### Expression5[​](#expression5 "Direct link to expression5") | | | | | ------- | -- | --------------------------------------------------- | | *expr5* | ⟶ | [*expr5*](#expression5) `+` [*expr6*](#expression6) | | | \| | [*expr5*](#expression5) `-` [*expr6*](#expression6) | | | \| | [*expr6*](#expression6) | #### Expression6[​](#expression6 "Direct link to expression6") | | | | | ------- | -- | --------------------------------------------------- | | *expr6* | ⟶ | [*expr6*](#expression6) `*` [*expr7*](#expression7) | | | \| | [*expr7*](#expression7) | #### Expression7[​](#expression7 "Direct link to expression7") | | | | | ------- | -- | --------------------------- | | *expr7* | ⟶ | `!` [*expr7*](#expression7) | | | \| | [*expr8*](#expression8) | #### Expression8[​](#expression8 "Direct link to expression8") | | | | | ------- | -- | -------------------------------------------------------------------------------------------------------------------- | | *expr8* | ⟶ | [*expr8*](#expression8) `[` [*expr*](#expression) `]` | | | \| | [*expr8*](#expression8) `.` [*id*](#identifier) | | | \| | [*expr8*](#expression8) `.` [*id*](#identifier) `(` [*expr*](#expression) `,` ⋯ `,` [*expr*](#expression) `,`opt `)` | | | \| | [*expr9*](#expression9) | #### Expression9[​](#expression9 "Direct link to expression9") | | | | | ------- | -- | ----------------------------------------------------------------------------------------------------------------------------- | | *expr9* | ⟶ | [*fun*](#function) `(` [*expr*](#expression) `,` ⋯ `,` [*expr*](#expression) `,`opt `)` | | | \| | `map` `(` [*fun*](#function) `,` [*expr*](#expression) `,` ⋯¹ `,` [*expr*](#expression) `,`opt `)` | | | \| | `fold` `(` [*fun*](#function) `,` [*expr*](#expression) `,` [*expr*](#expression) `,` ⋯¹ `,` [*expr*](#expression) `,`opt `)` | | | \| | `slice` `<` [*tsize*](#type-size) `>` `(` [*expr*](#expression) `,` [*expr*](#expression) `)` | | | \| | `[` [*tuple-arg*](#tuple-argument) `,` ⋯ `,` [*tuple-arg*](#tuple-argument) `,`opt `]` | | | \| | `Bytes` `[` [*bytes-arg*](#tuple-argument) `,` ⋯ `,` [*bytes-arg*](#tuple-argument) `,`opt `]` | | | \| | [*tref*](#type-reference) `{` [*struct-arg*](#structure-argument) `,` ⋯ `,` [*struct-arg*](#structure-argument) `,`opt `}` | | | \| | `assert` `(` [*expr*](#expression) `,` [*str*](#string-literal) `)` | | | \| | `emit` `(` [*expr*](#expression) `)` | | | \| | `disclose` `(` [*expr*](#expression) `)` | | | \| | [*term*](#term) | #### Term[​](#term "Direct link to Term") | | | | | ------ | -- | ------------------------------------------------------------------ | | *term* | ⟶ | [*id*](#identifier) | | | \| | `true` | | | \| | `false` | | | \| | [*nat*](#field-literal) | | | \| | [*str*](#string-literal) | | | \| | `pad` `(` [*nat*](#field-literal) `,` [*str*](#string-literal) `)` | | | \| | `default` `<` [*type*](#type) `>` | | | \| | `(` [*expr-seq*](#expression-sequence) `)` | #### Tuple-argument[​](#tuple-argument "Direct link to Tuple-argument") | | | | | ----------- | -- | ------------------------------ | | *tuple-arg* | ⟶ | [*expr*](#expression) | | | \| | `...` [*expr*](#expression) | | *bytes-arg* | ⟶ | [*tuple-arg*](#tuple-argument) | #### Structure-argument[​](#structure-argument "Direct link to Structure-argument") | | | | | ------------ | -- | --------------------------------------------- | | *struct-arg* | ⟶ | [*expr*](#expression) | | | \| | [*id*](#identifier) `:` [*expr*](#expression) | | | \| | `...` [*expr*](#expression) | #### Function[​](#function "Direct link to Function") | | | | | ----- | -- | ----------------------------------------------------------------------------------------------------------- | | *fun* | ⟶ | [*id*](#identifier) [*gargs*](#generic-argument-list)opt | | | \| | [*arrow-parameter-list*](#arrow-parameter-list) [*return-type*](#return-type)opt `=>` [*block*](#block) | | | \| | [*arrow-parameter-list*](#arrow-parameter-list) [*return-type*](#return-type)opt `=>` [*expr*](#expression) | | | \| | `(` [*fun*](#function) `)` | #### Return-type[​](#return-type "Direct link to Return-type") | | | | | ------------- | - | ------------------- | | *return-type* | ⟶ | `:` [*type*](#type) | #### Optionally-typed-pattern[​](#optionally-typed-pattern "Direct link to Optionally-typed-pattern") | | | | | -------------------------- | -- | --------------------------------- | | *optionally-typed-pattern* | ⟶ | [*pattern*](#pattern) | | | \| | [*typed-pattern*](#typed-pattern) | #### Const-Binding[​](#const-binding "Direct link to Const-Binding") | | | | | ---------- | - | --------------------------------------------------------------------------------- | | *cbinding* | ⟶ | [*optionally-typed-pattern*](#optionally-typed-pattern) `=` [*expr*](#expression) | #### Arrow-parameter-list[​](#arrow-parameter-list "Direct link to Arrow-parameter-list") | | | | | ---------------------- | - | ---------------------------------------------------------------------------------------------------------------------------------------- | | *arrow-parameter-list* | ⟶ | `(` [*optionally-typed-pattern*](#optionally-typed-pattern) `,` ⋯ `,` [*optionally-typed-pattern*](#optionally-typed-pattern) `,`opt `)` | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact keywords ## Module-related keywords[​](#module-related-keywords "Direct link to Module-related keywords") * export * from * import * module * prefix ## Statement and expression keywords[​](#statement-and-expression-keywords "Direct link to Statement and expression keywords") * as * assert * circuit * const * constructor * contract * default * disclose * else * emit * enum * fold * for * if * implements * include * ledger * map * new * of * pad * pragma * pure * return * sealed * slice * struct * type * witness ## Built-in data type keywords.[​](#built-in-data-type-keywords "Direct link to Built-in data type keywords.") * Boolean * Bytes * Field * Opaque * Uint * Vector ## Boolean literals[​](#boolean-literals "Direct link to Boolean literals") * false * true ## Keywords reserved for future use[​](#keywords-reserved-for-future-use "Direct link to Keywords reserved for future use") * arguments * await * break * case * catch * class * continue * debugger * delete * do * eval * event * extends * finally * function * in * instanceof * interface * let * null * package * private * protected * public * static * super * switch * this * throw * try * typeof * var * void * while * with * yield --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact reference ## Overview[​](#overview "Direct link to Overview") Compact is a strongly typed, statically typed, bounded programming language for writing smart contracts, designed to be used in combination with TypeScript to implement decentralized applications for Midnight. Midnight's smart contracts have three parts: * public state that is stored and replicated in the Midnight ledger, * a set of zero-knowledge circuits, enabling confidential proofs that the public ledger state resulted from valid executions of the contract logic, and * local, off-chain functions implemented with arbitrary code, allowing access to private state that never leaves the client. Each Compact program (also referred to as a *contract*) can contain several kinds of program elements: * module and import forms for management of namespaces and separate files, * declarations of program-defined types, * declarations of the data that the contract stores in the public ledger, * declarations of *witnesses*, which are callback functions supplied by the TypeScript runner, * definitions of *circuits*, which are functions serving as the operational core of a smart contract, and * the definition of at most one *constructor*, which is a function called when a contract is created and can be used to initialize public and private state. Compact is similar to TypeScript: it has a syntax similar to that of JavaScript, and it layers a type system over the JavaScript syntax. Compact deviates intentionally from TypeScript, however, in several important ways: * Unlike TypeScript, Compact is strongly typed. Programs cannot bypass the static type system via missing type declarations or unsafe casts. Furthermore, the JavaScript code produced by the Compact compiler includes run-time checks enforcing the static types of values that come from outside Compact as well as preventing external application of a Compact circuit with more or fewer than the declared number of arguments. * Compact provides namespace management via static rather than dynamic modules, and these modules can be parameterized via compile-time [generic parameters](#generic-parameters-and-arguments), which include size as well as type parameters. * Because every Compact program must compile into a set of finite proving circuits, the language is *bounded*: all Compact types have sizes that are fixed at compile time, loops are bounded either by constant bounds or by the size of an object of constant size, and recursion is disallowed. * Compact numeric values are limited to unsigned integers either with a program-declared range or with a range determined by the field size of the target proving system. * Compact distinguishes certain values as potentially containing private data that should typically be protected, and it requires explicit declaration of the disclosure of any potential private data via `disclose()` wrappers. The basics of this are discussed in the [description of `disclose`](#explicit-disclosure), and a more thorough description and discussion appears in the separate document [Explicit disclosure in Compact](/compact/reference/explicit-disclosure.md). Like TypeScript, Compact compiles into JavaScript, but it also produces a TypeScript definition file so it effectively also compiles into TypeScript. It produces separate TypeScript definition files and JavaScript implementation files rather than simply producing TypeScript for three reasons: * to allow compiled Compact programs to be used without requiring an additional TypeScript compilation step, * to permit the generated code to check function argument counts without disabling compile-time argument-type checks when called from TypeScript, and * so that it can generate a source-map file that properly maps elements of the generated JavaScript code (e.g., variable bindings and references) to the corresponding elements of the source Compact code. For each circuit that touches the public ledger and hence requires a proof for on-chain execution, the Compact compiler also produces proving circuits in a zero-knowledge intermediate language (*zkir*), and it uses a zkir compiler to produce proving keys for each such circuit. Finally, the compact compiler also produces a JSON-formatted contract info file that contains information about the program and its compiled representation, including version numbers and the types and characteristics of the contract's exported circuits. This document explains each syntactic category individually. It starts by introducing the building blocks that are used in various contexts: identifiers, constants, types, generic parameters, and patterns. Then it describes the structure of Compact programs, each kind of program element, and the statements and expressions that can appear within circuit and constructor bodies. Finally, it discusses the TypeScript target. [Writing a contract](/compact/reference/writing.md) provides a small example of what a Compact program looks like. It also introduces the basic building blocks of a Compact contract. [The full grammar of Compact](/compact/reference/compact-grammar.md) is provided separately. ## Notation[​](#notation "Direct link to Notation") The syntax of Compact programs is given by EBNF grammar snippets that use the following notational conventions: * Keywords and punctuation are in `monospaced` font. * Terminal and nonterminal names are in *emphasized* font. * Alternation is indicated by a vertical bar (`|`). * Optional items are indicated by the superscript opt. * Repetition is specified by ellipses. The notation *X* ⋯ *X*, where *X* is a grammar symbol, represents zero or more occurrences of *X*. The notation *X* `,` ⋯ `,` *X*, where *X* is a grammar symbol and `,` is a literal comma, represents zero or more occurrences of *X* separated by commas. In either case, when the ellipsis is marked with the superscript 1, i.e., ⋯¹, the notation represents a sequence containing at least one *X*. When such a sequence is followed by `,`opt, an optional trailing comma is allowed, but only if there is at least one *X*. For example, *id* ⋯ *id* represents zero or more *id*s, and *expr* `,` ⋯¹ `,` *expr* `,`opt represents one or more comma-separated *expr*s possibly followed by an extra comma. The rules involving commas apply equally to semicolons, i.e., apply when `,` is replaced by `;`. Every program is formed of characters that are organized into atomic sequences of characters known as *tokens*. Each keyword and punctuation symbol appearing in the grammar snippets represents itself exactly, i.e., represents the token consisting of the same sequence of characters. For example, when the keyword `circuit` appears in a grammar snippet, it matches only the token `circuit`, and when the punctuation symbol `:` appears, it matches only the token `:`. Each terminal name appearing in the grammar snippets represents a set of possible tokens. For example, the terminal name *id* represents the set of all identifiers: when *id* appears in a grammar snippet, it matches any identifier. The sets of tokens represented by the terminal names appearing in the grammar snippets are described in [Terminal names](#terminal-names) below. Each nonterminal name appearing in the grammar snippets represents a sequence of tokens that comprise some structured piece of a program. For example, the terminal name *expr* matches any sequence of tokens that can be interpreted as an expression, such as `3 + x` or `a ? b : c`. The set of structures represented by each nonterminal name is given in the various sections of this reference manual along with typing and evaluation rules where appropriate. For example, the structure of a *circuit-definition* is described in [Circuit definitions](#circuit-definitions). ## Terminal names[​](#terminal-names "Direct link to Terminal names") The following terminal names appear in the grammar snippets. * *id*, *module-name*, *function-name*, *struct-name*, *enum-name*, *contract-name*, *tvar-name*, and *type-name* all represent identifier tokens. * *nat* represents natural-number literals. * *str* and *file* represent string literals. * *version* represents version literals (in pragmas). While identifiers and string literals are each represented by more than one name, each represents the entire set of possible identifier or string-literal tokens. The grammar snippets use different terminal names only to suggest their use, e.g, *module-name* for module names versus *tvar-name* for type variable names. ## Static and dynamic errors[​](#static-and-dynamic-errors "Direct link to Static and dynamic errors") The compiler detects various kinds of *static errors*, e.g., malformed syntax, references to undefined identifiers, and type mismatches. When it detects one or more static errors, it prints descriptive error messages for the errors and terminates without generating any output. The code the compiler generates and the run-time libraries it uses detect various kinds of *dynamic errors*, e.g., attempts from code outside of Compact to call Compact circuits with wrong numbers or types of arguments or attempts to cast an unsigned value to an unsigned type that is too small for the value. These errors are reported when the generated code is run and cause evaluation of the current circuit to halt. ## Identifiers, bindings, and scope[​](#identifiers-bindings-and-scope "Direct link to Identifiers, bindings, and scope") Identifiers are used in Compact, as in most other programming languages, to name things. Syntactically, an *identifier* is a *token* (atomic sequence of characters), beginning with with an alphabetic character, a dollar sign (`$`), or an underscore (`_`) followed by one or more alphabetic characters, digits (`0` - `9`), dollar signs, or underscores. Some identifiers are *reserved words*. Of these, some are used as *keywords* in the syntax of the Compact language, e.g., `module`, `import`, `circuit`, and `for`. Others, specifically keywords reserved by JavaScript and TypeScript, are considered reserved for future use in Compact, e.g., `self` and `class`. Still others, specifically every identifier that begins with `__compact`, are reserved for use by the compiler. A comprehensive list of keywords and reserved words is given in [keywords and reserved words](/compact/reference/compact-keywords.md). The remaining identifiers can be used to name specific instances of various kinds of entities, including modules, types, generic parameters, ledger fields, function (circuit or witness) names, function parameters, and local variables. An identifier associated with, i.e., *bound* to, one of these entities can be referenced anywhere within the *scope* of the binding. Compact is lexically scoped, so the scope of each binding is limited to a specific region of the program text. The binding might be *shadowed* (hidden from view) in some region of program text within its scope that contains a binding for the same identifier. It is a static error for an identifier to be bound more than once in a same scope, except that [function overloading](#circuit-and-witness-calls) allows more than one function with the same name to be visible in the same scope with different signatures, i.e., different numbers or kinds of generic parameters and/or different numbers or types of run-time parameters. The scope of each binding depends upon where it appears, as described below. (The caveat "except where shadowed" is not explicitly stated but applies in each case.) * Identifiers bound at the outermost level of a contract (referred to as the *top level*) are visible throughout the contract, but not within any modules that are imported from separate files. * Identifiers bound at the outermost level of a module are visible throughout the module. They are not visible outside of the module unless exported: any exported binding is also visible if and where it is imported from the module. * The generic parameters of a module, structure declaration, or function declaration are visible throughout the declaration. * The run-time parameters of a circuit or constructor are visible within its body. * Identifiers defined by a `const` binding inside a block are visible throughout the block. * Identifiers defined by a `const` binding inside a `for`-loop header are visible throughout the `for` loop. Every reference to an identifier must appear within the scope of a binding for the identifier, in which case we say that the identifier is bound to the entity associated with the identifier by that binding. Otherwise, the reference is a static error. For example: ``` circuit c(): Field { const answer = 42; { const answer = 12; assert(answer != 42, "shadowing did not work!"); } return answer; // returns 42 (the outer 'answer') } ``` The identifier `c` is bound to the circuit named `c`, and this binding is visible throughout the contract, though no references to `c` appear in the example. The first (outer) binding of the identifier `answer` to the value `42` is visible throughout the body of `c` except where shadowed by the second (inner) binding of `answer` within in the inner block, so the reference to `answer` in `return answer` evaluates to `42`. The second (inner) binding of `answer` to `42` is visible throughout the inner block, so the reference to `answer` in `answer != 42` evaluates to `12`. In addition to having a scope, every binding also has a lifetime. For circuit and witness bindings, the lifetime is effectively permanent, i.e., the binding is always available for use whenever the program is run. The lifetimes of ledger-field bindings begin when they are first initialized and are effectively permanent from that point on; although the value of a field can change over time, the association of the ledger-field name with the ledger field's location in the (replicated) public state of a contract never changes. On the other hand, bindings for module names, type names, and generic parameters are live only when a program is compiled, i.e., they help determine the structure of the program and the shape of the data used by the program but are not needed once the program has been compiled. (TypeScript bindings for type names exported from the program's top level do live on, however, in the generated TypeScript definition file.) Variable bindings, i.e., bindings of circuit parameters, constructor parameters, and local variables bound by `const` statements and `for` loops, have dynamic lifetimes. The bindings of a circuit's or constructor's parameters start a new lifetime when the circuit or constructor is called that ends when the circuit or constructor exits. A variable binding established by a `const` statement starts a new lifetime when the `const` statement is evaluated that ends when the block containing the `const` statement exits. A `const` binding established by the `const` subform of a `for`-loop header starts a new lifetime on each iteration of the loop that ends when that iteration ends. Variable bindings can have multiple lifetimes, because a circuit might be called multiple times, a block might be evaluated multiple times, and a `for` loop might be evaluated multiple times and/or have multiple iterations. Variables in Compact are immutable, however: they have the same value over the entire lifetime of the variable's binding. Thus, they are referred to as variables not because their values can vary over any single lifetime but because they can have different values in different lifetimes. ## Generic parameters and arguments[​](#generic-parameters-and-arguments "Direct link to Generic parameters and arguments") Various entities, specifically [module declarations](#modules-exports-and-imports), [structure declarations](#structure-types), [type-alias declarations](#type-aliases), [circuit definitions](#circuit-definitions), and [witness declarations](#declaring-witnesses-for-private-state-management), can have *generic parameters*, i.e., compile-time type and numeric (natural-number) parameters whose values are given at the use site rather than fixed at the point of declaration. This allows the same *generic* code to be used with different specific types, bounds, and sizes. Except where shadowed, generic parameters are visible throughout the entire entity. In particular, the generic parameters of a module are visible within the program elements that appear within the body of the module. When present, generic parameters are enclosed in angle brackets following the name of the generic entity (module, structure, type alias, circuit, or witness). Each parameter is either a type name (e.g., `T`) or a hash-prefixed natural-number name (e.g., `#N`). Generic natural-number parameters are prefixed by `#` to distinguish them from generic type parameters. | | | | | --------------- | -- | ---------------------------------------------------------------------------------------------------------------------------------- | | *gparams* | ⟶ | `<` [*generic-param*](#generic-parameters-and-arguments) `,` ⋯ `,` [*generic-param*](#generic-parameters-and-arguments) `,`opt `>` | | *generic-param* | ⟶ | `#` [*tvar-name*](#terminal-names) | | | \| | [*tvar-name*](#terminal-names) | Generic entities must be *specialized* at the point of use to produce non-generic entities at compile time by supplying them with *generic arguments*. Any attempt to use a generic entity without specializing it is a static error. Generic arguments are also enclosed in angle brackets. Each generic argument must be a type, a natural number literal, or the type or numeric value of a generic parameter. | | | | | ------- | -- | ---------------------------------------------------------------------------------------------------------------- | | *gargs* | ⟶ | `<` [*garg*](#generic-parameters-and-arguments) `,` ⋯ `,` [*garg*](#generic-parameters-and-arguments) `,`opt `>` | | *garg* | ⟶ | [*nat*](#terminal-names) | | | \| | [*type*](#primitive-types) | [The syntax of types](#compact-types) allows for type references, including references to generic parameters, so any generic argument can pass along the value of a generic type or natural-number parameter that is visible at the point of specialization. The `#` used to distinguish generic natural-number parameters from generic type parameters need not and must not be used at the point of specialization. It is a static error, however, if a generic argument supplied for a generic parameter is not numeric when a numeric value is expected or is not a type when a type is expected. The example below demonstrates the use of two levels of generic parameterization, one at the module level and one at the circuit level. ``` module M { export circuit foo(x: T, v: Vector): Vector { return map((y) => [y, x], v); } } import M; export circuit bar1(): Vector<3, [Uint<8>, Boolean]> { return foo>(true, [101, 103, 107]); } export circuit bar2(): Vector<3, [Boolean, Boolean]> { return foo(false, [true, false, true]); } ``` The body of circuit `foo` is generic with respect to the module's type parameters `T` and `N` as well as to the circuit's own parameter `A`. The module is specialized at the point of import, while the circuit is specialized at the point of call (in both `bar1` and `bar2`). ## Compact types[​](#compact-types "Direct link to Compact types") Compact is *statically typed*: every expression in a Compact program must have a type that the compiler can prove to be safe in the expression's context, for all possible values of the expression. For named circuits and witnesses, the parameters and return types must be explicitly declared. For anonymous circuit expressions, the parameters and return types do not need to be declared but can be. The types of `const` bindings can also be declared or not. The language is *strongly typed*: the compiler rejects programs that do not type check. For example, it rejects programs in which a circuit or witness with a parameter type annotation is called with an incorrectly typed argument for that parameter, and it rejects programs where a circuit with a return-type annotation returns an incorrectly typed value. If an optional type annotation is omitted, the compiler attempts to infer a type and it rejects the program if no such type can be inferred. Types consist of built-in primitive types, ledger-state types, program-defined types, and references to generic type parameters in scope. When the term "type" occurs in this document without any other qualifier, it means either a primitive type, ledger-state type, a program-defined type, or a generic type parameter in scope. The use of ledger-state types is, at present, limited to typing the result of `default<`*T*`>` to obtain the default value of type *T*, and only constant bindings can have a ledger-state type. A generic type is not a valid type and so cannot, for example, be used as the type of a parameter or return value. Any attempt to do so is a static error. As with any other generic entity, it must be specialized at the point of use. ### Primitive types[​](#primitive-types "Direct link to Primitive types") The following are the primitive types of Compact: | | | | | ------- | -- | ------------------------------------------------------------------------------ | | *type* | ⟶ | [*tref*](#primitive-types) | | | \| | `Boolean` | | | \| | `Field` | | | \| | `Uint` `<` [*tsize*](#primitive-types) `>` | | | \| | `Uint` `<` [*tsize*](#primitive-types) `..` [*tsize*](#primitive-types) `>` | | | \| | `Bytes` `<` [*tsize*](#primitive-types) `>` | | | \| | `Opaque` `<` [*str*](#terminal-names) `>` | | | \| | `Vector` `<` [*tsize*](#primitive-types) `,` [*type*](#primitive-types) `>` | | | \| | `[` [*type*](#primitive-types) `,` ⋯ `,` [*type*](#primitive-types) `,`opt `]` | | *tref* | ⟶ | [*id*](#terminal-names) [*gargs*](#generic-parameters-and-arguments)opt | | *tsize* | ⟶ | [*nat*](#terminal-names) | | | \| | [*id*](#terminal-names) | * `Boolean` is the type of *Boolean* values. There are only two values of `Boolean` type. They are the values of the expressions `true` and `false`. * `Uint<`*m*`..`*n*`>`, where *m* is the literal `0` or generic natural-number parameter bound to `0`, and where *n* is a non-zero natural number literal or a generic natural-number parameter bound to a non-zero natural number, is the type of *bounded unsigned integer* values between `0` (inclusive) and `n` (exclusive). (While the lower bound is currently required to be `0`, this restriction might be lifted at some point.) `Uint` types with different upper bounds are different types, although the one with the smaller upper bound is a [subtype of the other](#subtyping-and-least-upper-bounds). The compiler and run-time system might impose a limit on the range of supported unsigned integer values. If so, it is a static error whenever a `Uint` type includes values that exceed this limit. The current limit, if any, is given in [Implementation-specific limits](#implementation-specific-limits). * `Uint<`*n*`>`, where *n* is a natural number literal or generic natural-number parameter, is the type of *sized unsigned integer* values with binary representations using up to *n* bits. This is the same type as `Uint<0..`*m*`>` where *m* is equal to 2*n*. Sized integer types can be seen as a convenience for programmers. `Uint<32>`, for example, can be more obvious and less error-prone than the equivalent `Uint<0..4294967296>`. Any Compact program that uses sized integer types can be rewritten to one that uses only bounded integer types, but the converse is not true. * `Field` represents the set of unsigned integers with values up to the order of the native prime field of the ZK proving system. The current maximum field value is given in [Implementation-specific limits](#implementation-specific-limits). * `[`*T1*, ⋯, *Tn*`]`, where *T1*, ⋯, *Tn* are zero or more comma-separated types, is the type of *tuple* values with element types *T1*, ⋯, *Tn*. Tuples are heterogeneous: any element type can differ from any of the others. The *length* of a tuple type is the number *n* of element types. Two tuple types with different lengths are different types. Two tuple types where any element type of one differs from the corresponding element type of the other are also different types, though one of the tuple types might be a [subtype of the other](#subtyping-and-least-upper-bounds). * `Vector<`*n*, *T*`>`, where *n* is a natural number literal or generic natural-number parameter and *T* is a type, is a shorthand notation for the tuple type `[`*T*, ⋯, *T*`]` with *n* occurrences of the type *T*. Note that a vector type and the corresponding tuple type are two different ways of writing exactly the same type. Unless otherwise specified, type rules for vector types are derived from the rules for the corresponding tuple type. * `Bytes<`*n*`>`, where *n* is a natural number literal or a generic natural-number parameter, is the type of *byte vectors* of length *n*. `Bytes` types with different lengths are different types. `Bytes` types are used in the Compact standard library for hashing. String literals in Compact also have a `Bytes` type, where *n* is the number of bytes in the UTF-8 encoding of the string. * `Opaque<`*s*`>`, where *s* is a string literal, is the type of *opaque* values with tag *s*. `Opaque` types with different tags are different types. Opaque values can be manipulated in witnesses and stored in the ledger, but they are opaque to Compact. They are represented in TypeScript as values whose type is the tag. They are represented in cryptographic circuits as a hash of their value. In the ledger, they are represented as a binary enocoding (not a hash) of the underlying value. The only tags currently allowed are `"string"` and `"Uint8Array"`. ### Program-defined types[​](#program-defined-types "Direct link to Program-defined types") Programs can define three kinds of new types: structures, enumerations, and contracts. They can also define structural and nominal aliases for existing types. #### Structure types[​](#structure-types "Direct link to Structure types") Structure types are defined via `struct` declarations with the following form: | | | | | -------------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *struct-declaration* | ⟶ | `export`opt `struct` [*struct-name*](#terminal-names) [*gparams*](#generic-parameters-and-arguments)opt `{` [*typed-id*](#structure-types) `;` ⋯ `;` [*typed-id*](#structure-types) `;`opt `}` `;`opt | | | \| | `export`opt `struct` [*struct-name*](#terminal-names) [*gparams*](#generic-parameters-and-arguments)opt `{` [*typed-id*](#structure-types) `,` ⋯ `,` [*typed-id*](#structure-types) `,`opt `}` `;`opt | | *typed-id* | ⟶ | [*id*](#terminal-names) `:` [*type*](#primitive-types) | A structure declaration has a sequence of named fields which must be separated either by commas or by semicolons. Comma and semicolon separators cannot be mixed within a single structure declaration. A trailing separator is allowed, but not required. Each structure field must have a type annotation. Here are a couple of examples: ``` struct Thing { triple: Vector<3, Field>, flag: Boolean, } struct NumberAnd { num: Uint<32>; item: T } ``` The first declaration introduces a structure type named `Thing` with two fields: `triple` (a vector with three `Field` elements) and `flag` (a Boolean). The second introduces a *generic* structure type named `NumberAnd` with generic parameter `T` and two fields: `num` (a 32-bit unsigned integer) and `item` (a value of type `T`). Generic structure types are not fixed types and must eventually be *specialized* by supplying generic arguments, e.g., `NumberAnd>`. When any generic structure type is specialized, it must be fully specialized: the number of supplied generic arguments must match the number of declared generic parameters. The effect of specializing a generic structure type is to produce the same type as one in which the generic parameters are replaced by the generic argument values. For example, `NumberAnd>` is equivalent to `NumberAnd` if `NumberAnd` had been defined by: ``` struct NumberAnd { num: Uint<32>; item: Uint<8> } ``` It is possible and common for a generic structure type to be specialized via different generic arguments to produce different specialized structure types in different parts of a program. Structure typing is always `nominal`: two types are equivalent only if they have the same names and same fields. They are distinct if they have different names even if they have the same fields. More precisely: each structure type is the same as any other structure type that has the same name, same element names (in the same order), and same element types (in the same order). It is distinct from every other type. This means, for example, that the following program is well-typed: ``` module M { struct NumberAnd { num: Uint<32>; item: Uint<8> } export circuit bar(x: NumberAnd): NumberAnd { return x; } } import M; struct NumberAnd { num: Uint<32>; item: T } export circuit foo(x: NumberAnd>): NumberAnd> { return bar(x); } ``` Structure types must not be recursive, i.e., they cannot contain elements of the same type as the structure, either directly or indirectly. An attempt to define a recursive structure type is a static error. For example, it is a static error to use the following pair of declarations: ``` struct Even { predecessor: Odd } struct Odd { predecessor: Even } export circuit doesntWork(s: Even): Odd { return s.predecessor; } ``` Values of structure types are created with [**structure-creation** expressions](#structure-creation) and accessed via [**structure-field-access** expressions](#structure-field-access). #### Enumeration types[​](#enumeration-types "Direct link to Enumeration types") Enumeration types are defined via `enum` declarations with the following form: | | | | | ------------------ | - | ---------------------------------------------------------------------------------------------------------------------------------- | | *enum-declaration* | ⟶ | `export`opt `enum` [*enum-name*](#terminal-names) `{` [*id*](#terminal-names) `,` ⋯¹ `,` [*id*](#terminal-names) `,`opt `}` `;`opt | An enumeration declaration has a non-empty sequence of named elements separated by commas. A trailing comma is allowed but not required. An enumeration declaration introduces a named enumeration type, such as `Arrow` in the example below: ``` enum Arrow { up, down, left, right }; ``` Within the scope of this declaration, a value of type `Arrow` can have one of four values, selected via `Arrow.up`, `Arrow.down`, `Arrow.left`, and `Arrow.right`. Two enumeration types are the same if they have the same name and the same element names (in the same order) and distinct otherwise. #### Contract types[​](#contract-types "Direct link to Contract types") Defining a contract type enables a Compact program to specify a collection of circuit signatures (that is, their names, parameter types, and return types) that describe another contract on which the program depends. Contract types are defined using the `contract` form, which has the following syntax: | | | | | ---------------------- | -- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *contract-declaration* | ⟶ | `export`opt `contract` [*contract-name*](#terminal-names) `{` [*circuit-declaration*](#contract-types) `;` ⋯ `;` [*circuit-declaration*](#contract-types) `;`opt `}` `;`opt | | | \| | `export`opt `contract` [*contract-name*](#terminal-names) `{` [*circuit-declaration*](#contract-types) `,` ⋯ `,` [*circuit-declaration*](#contract-types) `,`opt `}` `;`opt | | | | | | ----------------------- | - | --------------------------------------------------------------------------------------------------------------------- | | *circuit-declaration* | ⟶ | `pure`opt `circuit` [*id*](#terminal-names) [*simple-parameter-list*](#contract-types) `:` [*type*](#primitive-types) | | *simple-parameter-list* | ⟶ | `(` [*typed-id*](#structure-types) `,` ⋯ `,` [*typed-id*](#structure-types) `,`opt `)` | A contract type definition specifies a set of circuit declarations, separated either by commas or by semicolons. Comma and semicolon separators cannot be mixed within a single contract type definition. A trailing comma or semicolon is allowed, but not required. The set of circuit names in the contract type definition must be a proper set, without duplicates. Each circuit declaration must be "simple"; that is, it must not make use of generic parameters. The declaration may require the circuit to be pure. Here is an example of a contract type definition: ``` contract Adder { circuit setAddAmount(n: Uint<64>): []; circuit addTo(n: Uint<64>): Uint<64>; } ``` A `contract` declaration introduces a new contract type into its scope. A contract type is a regular program-defined Compact type, just like a structure type or enumeration type. For example, it can be used as the type of a circuit parameter or witness function parameter, the type of a structure element, or the specializing argument of a ledger-state type such as `List` or `Map`. Here is an example of a ledger declaration using the `Adder` type and a constructor that initializes it. ``` export ledger adders: List; constructor(a: Adder) { adders.pushFront(disclose(a)); } ``` (See later sections of this Compact reference for more information about ledger-state types and constructors.) When some subset of a contract's circuits matches the set of those declared in a contract type, the contract is said to **satisfy** (or **have**) that type. More precisely, the **signature** of a circuit consists of the types of its parameters, plus its return type, as well as whether it is declared to be `pure`. Changing the parameter names or using destructuring patterns in a circuit definition does not change its signature, because the signature is determined only by the parameter and return *types*. The circuit declarations in a contract type declaration also have signatures, consisting of their types and whether they are declared to be pure. For example, the signature of `addTo` in the `Adder` interface above is > `Uint<64>` → `Uint<64>` A contract **satisfies** a contract type when, for every circuit declared in the `contract` form, the contract exports a circuit with the same name and with a signature whose types are identical to the one in the declaration. Furthermore, every circuit declared `pure` in the contract type declaration must also be declared `pure` (explicitly) in the satisfying contract implementation. If the circuit in the contract type declaration is *not* declared `pure`, the type can be satisfied by any circuit with the same name and a matching signature, regardless of whether the implementation is declared `pure`. For example, any contract that exports `setAddAmount` and `addTo` circuits with signatures identical to those in the `Adder` declaration above satisfies the `Adder` contract type. A contract whose definition of `addTo` is declared to be `pure` would also satisfy the `Adder` type. This is true regardless of whether the contract declares any intention to satisfy the type. In other words, contract typing is structural, not nominal. On the other hand, when a contract type is used to describe the required interface for a set of contracts, and a contract is intended to implement that interface, it is useful to assert that intention. This is accomplished with the `contract implements` program element, which asserts that the current contract has a specific type. | | | | | ------------------------ | - | ------------------------------------------------------ | | *implements-declaration* | ⟶ | `contract` `implements` [*type*](#primitive-types) `;` | Here is an example. ``` contract implements Adder; ``` The contract type named in the `contract implements` form must be in scope, using Compact's existing rules for the scope of program-defined types. The `contract implements` declaration applies to the contract being defined at the point where it appears. A contract may be declared to satisfy several different contract types by including multiple `contract implements` declarations. A contract type represents the set of all possible deployed contracts that satisfy the corresponding contract type definition. A contract value (i.e., a value with a contract type) might be represented by the address of a deployed contract. No mechanism is provided within the Compact language to *create* values with contract types. Instead, the surrounding context (that is, the application code) introduces a contract value into the Compact program by calling a circuit or constructor with a value representing a deployed contract or by returning a contract value from a witness function. To reiterate what was previously stated, a contract satisfies a contract type by exporting definitions with matching types and purity declarations for all the type's declared circuits, no matter whether a `contract implements` declaration appears in the code. If such a declaration *is* present, though, the compiler will verify it and reject the program with a compile-time error if the contract fails to export the circuits required by the contract type. The contract can export additional circuits, as needed, as long as some subset of the exported circuits satifies the requirements of the contract type. Current limitations on contract types The current Compact compiler imposes limitations on the circuits that can satisfy a contract type, disqualifying any circuits that call witnesses. It also imposes limitations on how the implementing code artifacts are found and loaded. See [the section describing cross-contract call expressions](#cross-contract-calls) for full details. #### Type aliases[​](#type-aliases "Direct link to Type aliases") Type aliases can be created via `type` declarations of the form: | | | | | ------------------------ | - | ----------------------------------------------------------------------------------------------------------------------------------------------- | | *type-alias-declaration* | ⟶ | `export`opt `new`opt `type` [*type-name*](#terminal-names) [*gparams*](#generic-parameters-and-arguments)opt `=` [*type*](#primitive-types) `;` | Within the scope of a type-alias declaration of *type-name* for *type*, *type-name* is itself a type. Type aliases are either structural or nominal, depending on whether the optional `new` modifier is present: * A type alias *type-name* for *type* declared without the optional `new` modifier is a structural type alias, i.e., *type-name* is the same type and is fully interchangeable with *type*. * A type alias *type-name* for *type* declared with the optional `new` modifier is a nominal type alias, i.e., *type-name* is a distinct type compatible with *type* but neither a subtype of nor a supertype of *type* (or any other type). Any nominal type alias *type-name* for some type *type* is compatible with *type* in the following senses: * values of type *type-name* have the same representation as values of type *type* * values of type *type-name* can be used by primitive operations that require a value of type *type* * values of type *type-name* can be cast explicitly to *type*, and * values of type *type* can be cast explicitly to type *type-name*. For example, within the scope of ``` new type V3U16 = Vector<3, Uint<16>> ``` a value of type `V3U16` can be referenced or sliced just like a vector of type `Vector<3, Uint<16>>`, but it cannot, for example, be passed to a function that expects a value of type `Vector<3, Uint<16>>` without an explicit cast. When one operand of an arithmetic operation (e.g., `+`) receives a value of some nominal type alias *type-name*, the other operand must also be of type *type-name*, and the result of performing the operation is cast to type *type-name*. This might cause a dynamic error if the result cannot be represented by type *type-name*. Values of any nominal type alias *type-name* cannot be compared directly using, e.g., `<`, or `==`, with values of any other type, including with values of type *type*. Such comparisons require one of the operands to be cast to the type of the other. Both structural and nominal type aliases can take generic parameters, e.g.: ``` type V3 = Vector<3, T>; ``` and ``` new type VField<#N> = Vector; ``` When a generic nominal type is specialized, the specialized type is a nominal type. ### Subtyping and least upper bounds[​](#subtyping-and-least-upper-bounds "Direct link to Subtyping and least upper bounds") Some Compact types are *related* to other types via subtyping. Informally, if a type *T* is a *subtype* of a type *S* (equivalently, *S* is a *supertype* of type *T*), then every value of type *T* is also a value of type *S*, i.e., any value of type *T* can be used where a value of type *S* is expected without the need for an explicit cast. For example, a circuit or witness can be called with argument expressions whose types are subtypes of the corresponding parameter type annotations, and a `const` binding statement with a type annotation can be given a value with an expression whose type is a subtype of the type annotation. Subtyping is exclusively defined by the following rules: * Any type *T* is a subtype of itself (subtyping is reflexive) * `Uint<0..`*n*`>` is a subtype of `Uint<0..`*m*>\` if *n* is less than (or equal to) *m* * `Uint<0..`*n*`>` is a subtype of `Field` if *n-1* is less than or equal to the maximum field value. (Whether `Field` is a subtype of `Uint<0..`*n*`>` if *n-1* is greater than the maximum field value is currently unspecified.) * The tuple type `[`*T1*, ⋯, *Tn*`]` is a subtype of the tuple type `[`*S1*, ⋯, *Sn*`]` if they have the same length and each type *Ti* is a subtype of the corresponding type *Si*. * If the circuits declared in contract type `B` are a superset of those declared in contract type `A`, then `B` is a subtype of `A`. A contract type can therefore be a subtype of many disjoint supertypes. The *least upper bound* (with respect to subtyping) of a non-empty set of types {*T1*, ⋯, *Tn*} is a type *S* such that: * ***S* is an upper bound:** *Ti* is a subtype of *S* for all *i* in the range 1..*n*, and * ***S* is the least upper bound:** for all upper bounds *R* of the set of types {*T1*, ⋯, *Tn*}, *S* is a subtype of *R*. Note that least upper bounds do not exist for all sets of types, because some types (such as `Boolean` and `Field`) are not related. **Tuple and vector types:** Every vector type is equivalent to some tuple type. Specifically, as noted in the earlier section on [Primitive types](#primitive-types), the vector type `Vector<`*n*, *T*`>` is equivalent to the tuple type `[`*T*, ⋯, *T*`]` with *n* occurrences of *T*. Thus the above subtyping rule for tuple types applies to vector types as well: every vector type is a subtype of the equivalent tuple type and possibly of some other tuple and vector types. In general, a vector type `Vector<`*n*, *T*`>` is a subtype of a tuple type `[`*S1*, ⋯, *Sn*`]` if *T* is a subtype of each of the types *S1*, ⋯, *Sn*. This means, for instance, that a vector can often be passed to a circuit where a tuple is expected. On the other hand, tuple types do not always have equivalent vector types. For example, neither `[Boolean, Field]` nor `[Uint<8>, Uint<16>]` is equivalent to any vector type. We say, however, that a tuple type `[`*T1*, ⋯, *Tn*`]` with possibly distinct types *T1*, ⋯, *Tn* "*has a vector type*" if the least upper bound *S* of the set of types {*T1*, ⋯, *Tn*} exists. In that case, the tuple type has the vector type `Vector<`*n*, *S*`>`. Some operations over tuples (such as mapping and folding) require the tuple type to have a vector type. When a tuple type has a vector type, the tuple type is a subtype of the vector type, but it might not be the same as the vector type. For example, `[Uint<16>, Uint<16>]` has the vector type `Vector<2, Uint<16>>`, and the two types are the same, whereas `[Uint<8>, Uint<16>]` also has the vector type `Vector<2, Uint<16>>`, but the types are not the same. **Contract types:** The least upper bound of a pair of contract types is the intersection of their declared circuits, which may be empty. (The empty contract type is useless, but valid.) Also, any pair of contract types has a greatest lower bound: the union of their declared circuits. The subtyping rule for contract types creates another way to define what it means for a contract to satisfy or implement a contract type. First, recognize that the entire set of circuits exported by a Compact program forms a "natural" contract type. In other words, every Compact program induces a contract type that could be written as a `contract` declaration. Then, if that "natural" contract type is a subtype of some other contract type `A`, then the contract implementation satisfies `A`. ## Patterns and destructuring[​](#patterns-and-destructuring "Direct link to Patterns and destructuring") The parameters of a circuit or constructor and the target of a `const` binding are specified via patterns: | | | | | -------------------- | -- | -------------------------------------------------------------------------------------------------------------------------------- | | *pattern* | ⟶ | [*id*](#terminal-names) | | | \| | `[` [*pattern*](#patterns-and-destructuring)opt `,` ⋯ `,` [*pattern*](#patterns-and-destructuring)opt `,`opt `]` | | | \| | `{` [*pattern-struct-elt*](#patterns-and-destructuring) `,` ⋯ `,` [*pattern-struct-elt*](#patterns-and-destructuring) `,`opt `}` | | *pattern-struct-elt* | ⟶ | [*id*](#terminal-names) | | | \| | [*id*](#terminal-names) `:` [*pattern*](#patterns-and-destructuring) | In its simplest form, a pattern is just an identifier. For example, in the code below, the parameter of `sumTuple` is the identifier `x` and the targets of the two const bindings are the identifiers `a` and `b`. ``` circuit sumTuple(x: [Field, Field]): Field { const a = x[0], b = x[1]; return a + b; } ``` When the parameter type is a tuple, vector, or struct, it is often convenient to use one of the *destructuring* forms of patterns to name individual pieces of the tuple or struct at the point of binding rather than extracting them at each point of use. For example, one could replace the above with: ``` circuit sumTuple(x: [Field, Field]): Field { const [a, b] = x; return a + b; } ``` or more simply with: ``` circuit sumTuple([a, b]: [Field, Field]): Field { return a + b; } ``` Here is a similar example that destructures a struct instead of a tuple: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumStruct({x, y}: S): Uint<64> { return x + y; } ``` Whereas the elements of a tuple pattern are necessarily given in order, the elements of a struct pattern need not be consistent with the order of the fields in the declaration. For example, the definition of `sumStruct` below is equivalent to the one above, even though the order of the pattern elements has been swapped: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumStruct({y, x}: S): Uint<64> { return x + y; } ``` By default, the names bound by the pattern are the same as the names of the structure elements. When this is not convenient, it is possible to choose different names for the structure elements: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumStruct({x: a, y}: S): Uint<64> { return a + y; } ``` While `x: a` looks like an identifier with a type annotation, in this context it simply indicates that `a` rather than `x` is bound to the value in the `x` field. Patterns can be arbitrarily nested, e.g.: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumTupleStruct([{x: a1, y: b1}, {x: a2, y: b2}]: [S, S]): Uint<64> { return a1 + b1 + a2 + b2; } ``` It is permissible and sometimes useful to not name certain parts of the tuple or struct. ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumSomeYs([{y: b1}, , {y: b3}]: [S, S, S]): Uint<64> { return b1 + b3; } ``` Here the input is a tuple with three elements, but the pattern skips the second by putting two commas between the first and third. Similarly, while each element of the tuple is a struct with both `x` and `y` fields, the pattern ignores the `x` fields simply by failing to mention them. It is a static error if a pattern implies a different shape from the declared or inferred type of value to be destructured. For example: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumStruct({x, y}: [Uint<16>, Uint<32>]): Uint<64> { return x + y; } ``` fails because it tries to treat a tuple as a struct, while: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumSomeYs([{y: b1}, , , {y: b3}]: [S, S, S]): Uint<64> { return b1 + b3; } ``` fails because it implies that the input tuple has four elements (including two skipped elements) when it actually has only three, and: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumSomeYs([{y: b1}, , {z: b3}]: [S, S, S]): Uint<64> { return b1 + b3; } ``` fails because it tries to name a nonexistent `z` field in one of the structs. Trailing commas in a pattern imply nothing about the structure of the input and are ignored: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumSomeYs([{y: b1,}, , {y: b3,},]: [S, S, S]): Uint<64> { return b1 + b3; } ``` ## Programs[​](#programs "Direct link to Programs") A compact program is a sequence of zero or more program elements. | | | | | ----------------- | -- | -------------------------------------------------------------------------- | | *program* | ⟶ | [*program-element*](#programs) ⋯ [*program-element*](#programs) | | *program-element* | ⟶ | [*pragma-form*](#pragmas) | | | \| | [*module-definition*](#modules-exports-and-imports) | | | \| | [*import-form*](#imports) | | | \| | [*export-form*](#exports) | | | \| | [*include-form*](#include-files) | | | \| | [*struct-declaration*](#structure-types) | | | \| | [*enum-declaration*](#enumeration-types) | | | \| | [*contract-declaration*](#contract-types) | | | \| | [*implements-declaration*](#contract-types) | | | \| | [*type-alias-declaration*](#type-aliases) | | | \| | [*ledger-declaration*](#declaring-and-maintaining-public-state) | | | \| | [*witness-declaration*](#declaring-witnesses-for-private-state-management) | | | \| | [*constructor-definition*](#contract-constructor) | | | \| | [*circuit-definition*](#circuit-definitions) | Briefly: * A [pragma form](#pragmas) allows the program to declare the version of the compiler and/or the language that it requires. * A [module definition](#modules-exports-and-imports) defines a Compact module, which also contains a sequence of program elements in its own nested scope. * An [export form](#exports) exports bindings from a module or from [the program itself](#top-level-exports). * An [import form](#imports) imports bindings from a Compact module. * An [include form](#include-files) allows program elements to be included from other files. * A [structure definition](#structure-types) defines a structure type. * An [enumeration definition](#enumeration-types) defines an enumeration type. * A [contract definition](#contract-type-definition) defines a contract type. * An [implements declaration](#contract-implements-declaration) declares that a contract satisfies a contract type. * A [type-alias definition](#type-aliases) defines a type alias, possibly creating a distinct type. * A [witness declaration](#declaring-witnesses-for-private-state-management) declares a witness, which is a callback function whose definition must be provided by any application using the contract. * A [ledger declaration](#declaring-and-maintaining-public-state) declares one field of the contract's public state. * A [constructor definition](#contract-constructor) defines the contract's constructor, if any. * A [circuit definition](#circuit-definitions) defines a circuit. The order of program elements in a program or module is unimportant, except that any module must be defined before any import of the module, and any program-defined types used as generic parameters by an import form must be defined before the import form. Detailed descriptions of struct, enum, contract, and type-alias declarations appear in [Compact types](#compact-types) above. Detailed descriptions of the remaining program elements are described in the following section. ## Pragmas[​](#pragmas "Direct link to Pragmas") A pragma takes the following form and declares a constraint on either the compiler version (*id* = `compiler_version`) or the language version (*id* = `language_version`) | | | | | --------------- | -- | --------------------------------------------------------------- | | *pragma-form* | ⟶ | `pragma` [*id*](#terminal-names) [*version-expr*](#pragmas) `;` | | *version-expr* | ⟶ | [*version-expr*](#pragmas) `\|\|` [*version-expr0*](#pragmas) | | | \| | [*version-expr0*](#pragmas) | | *version-expr0* | ⟶ | [*version-expr0*](#pragmas) `&&` [*version-term*](#pragmas) | | | \| | [*version-term*](#pragmas) | | *version-term* | ⟶ | [*version-atom*](#pragmas) | | | \| | `!` [*version-atom*](#pragmas) | | | \| | `<` [*version-atom*](#pragmas) | | | \| | `<=` [*version-atom*](#pragmas) | | | \| | `>=` [*version-atom*](#pragmas) | | | \| | `>` [*version-atom*](#pragmas) | | | \| | `(` [*version-expr*](#pragmas) `)` | | *version-atom* | ⟶ | [*nat*](#terminal-names) | | | \| | [*version*](#terminal-names) | *version* is a dot-separated pair or trio of natural numbers, so along with *nat* this allows *version* to be either a single natural number, a pair of natural numbers separated by a `.`, or a trio of natural numbers separated by a `.`, e.g., `1`, `1.2`, or `1.2.7`. For example, if a program includes the following pragma form: ``` pragma compiler_version >= 1.0.0 && !1.0.5; ``` All versions of the compiler from 1.0.0 up except for 1.0.5 will accept the pragma and compile the program, and all other versions will print an appropriate message and discontinue compilation of the program. ## Modules, exports, and imports[​](#modules-exports-and-imports "Direct link to Modules, exports, and imports") Modules in Compact are used for namespace management and also possibly to split programs into multiple files. A module is a named collection of program elements created via a module definition, which takes the following form: | | | | | ------------------- | - | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *module-definition* | ⟶ | `export`opt `module` [*module-name*](#terminal-names) [*gparams*](#generic-parameters-and-arguments)opt `{` [*program-element*](#programs) ⋯ [*program-element*](#programs) `}` | A module definition makes a binding from *module-name* to the module visible in the program or module containing the module definition. Any bindings established by program elements within the module are not made visible, at least not until the module is imported. A module can have [generic parameters](#generic-parameters-and-arguments), in which case it is a *generic module* and must be specialized with generic arguments at the point of import. ### Exports[​](#exports "Direct link to Exports") By default, identifier bindings created by the program elements within the body of a module are visible only within the module, i.e., they are not exported from the module. Any identifier defined at or imported into the top level of a module can be exported from the module in one of two ways: (1) by prefixing the definition with the `export` keyword, or by listing the identifier in a separate `export` declaration: | | | | | ------------- | - | ---------------------------------------------------------------------------------------- | | *export-form* | ⟶ | `export` `{` [*id*](#terminal-names) `,` ⋯ `,` [*id*](#terminal-names) `,`opt `}` `;`opt | For example, the following module exports `G` and `S` but not `F`. ``` module M { export { G }; export struct S { x: Uint<16>, y: Boolean } circuit F(s: S): Boolean { return s.y; } circuit G(s: S): Uint<16> { return F(s) ? s.x : 0; } } ``` Exporting a binding from a module has no effect unless the module is imported. ### Imports[​](#imports "Direct link to Imports") A module can be imported into another module or into the program top level, making some or all of its exported bindings visible there, potentially with a prefix. | | | | | ------------------ | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | *import-form* | ⟶ | `import` [*import-selection*](#imports)opt [*import-name*](#imports) [*gargs*](#generic-parameters-and-arguments)opt [*import-prefix*](#imports)opt `;` | | *import-selection* | ⟶ | `{` [*import-element*](#imports) `,` ⋯ `,` [*import-element*](#imports) `,`opt `}` `from` | | *import-element* | ⟶ | [*id*](#terminal-names) | | | \| | [*id*](#terminal-names) `as` [*id*](#terminal-names) | | *import-name* | ⟶ | [*id*](#terminal-names) | | | \| | [*file*](#terminal-names) | | *import-prefix* | ⟶ | `prefix` [*id*](#terminal-names) | For example: ``` module Runner { export circuit start(): [] {} export circuit stop(): [] {} } module UseRunner1 { import Runner; // start and stop are now in scope } module UseRunner2 { import { start } from Runner; // start is now in scope, but not stop } module UseRunner3 { import Runner prefix Runner$; // Runner$start and Runner$stop are now in scope, but not stop or run } ``` and ``` module Identity { export { id } circuit id(x: T): T { return x; } } import Identity; // id is now in scope, specialized to type Field ``` When *import-name* is an identifier and an import for *import-name* appears before any visible definition of *import-name*, the module is assumed to reside in the filesystem, and it is imported directly from there. If *import-name* is an identifier *module-name*, a definition for module *module-name* must be contained within the file *module-name*`.compact` in the same directory as the importing file or in one of the directories in the Compact path. If *import-name* is a string `"{`*prefix/*`}`*module-name*`"` where `{`*prefix/*`}` is either empty or is a pathname ending in a directory separator, a definition for a module named *module-name* must be contained within a file *module-name*`.compact` that is either: * (a) if `{`*prefix/*`}`*module-name*`.compact` is an absolute pathname, then exactly at `{`*prefix/*`}`*module-name*`.compact`, otherwise * (b) at `{`*prefix/*`}`*module-name*`.compact` relative to the directory of the importing file or to one of the directories in the Compact path. Details on the search order and the mechanism for setting the Compact path are given in [Compiler Usage](/compact/compilation-and-tooling/compiler-usage.md). In any of these cases, it is a static error if *module-name*`.compact` is not found, if it does not contain a definition for a module named *module-name*, or if it contains anything else other than comments and whitespace. Several examples follow. Example 1: The file `M.compact` below contains a single module definition: ``` module M { export { F }; export struct S { x: Uint<16>, y: Boolean } circuit F(x: S): Boolean { return x.y; } } ``` Then, `test1.compact` import `M` from `M.compact`: ``` import M; export { F }; ``` whereas `test2.compact` uses its own definition of `M`: ``` module M { export { G }; export struct S { x: Uint<16>, y: Boolean } circuit G(x: S): Boolean { return x.y; } } import M; export { G }; ``` Importing by a pathname allows multiple modules with the same name to be imported into the same scope. For example: The file `M.compact` below contains a single module definition, as before: ``` module M { export { F }; export struct S { x: Uint<16>, y: Boolean } circuit F(x: S): Boolean { return x.y; } } ``` and `A/M.compact` contains a different module definition: ``` module M { export { F }; export struct S { x: Uint<16>, y: Boolean } circuit F(x: S): Boolean { return x.y; } } ``` Then the program `test.compact` can define `M` and import all three of `M`, `"M"`, and `"A/M"`: ``` module M { export { F }; export struct S { x: Uint<16>, y: Boolean } circuit F(x: S): Boolean { return x.y; } } import M prefix M1$; import "M" prefix M2$; import "A/M" prefix M3$; export { M1$F, M2$F, M3$F }; ``` ### The compact standard library[​](#the-compact-standard-library "Direct link to The compact standard library") Compact's standard library can be imported by `import CompactStandardLibrary`. The standard library defines a number of useful types and circuits along with ledger-state types such as `Counter`, `Map`, and `MerkleTree`. ### Top-level exports[​](#top-level-exports "Direct link to Top-level exports") Certain kinds of program elements can be exported from a contract's top level, namely circuits, program-defined types, and ledger fields. Exporting them makes them visible outside of the contract, i.e., to the TypeScript driver for the smart contract. The circuits exported at the top level of a contract (i.e., not merely exported from a module) are the entry points of the contract. (A Compact program has no "main" entry point, but is more similar to a library containing multiple entry points that share a common store.) Although multiple circuits with the same name are allowed generally to support [function overloading](#circuit-and-witness-calls), it is a static error if more than one circuit with the same name is exported from the top level. It is also a static error for a generic circuit, i.e., one with generic parameters, to be exported from the top level. Program-defined types exported from the top level of the main file can be used to describe the argument and return types of witnesses and exported circuits; these may accept generic arguments, but generic arguments marked as sizes rather than types are dropped in the exported type. For example: ``` export struct S<#n, T> { v: Vector; curidx: Uint<0..n> } ``` is exported for use as a TypeScript type with the `T` parameter but not the `n` parameter, i.e.,: ``` export type S = { v: T[]; curidx: bigint } ``` Ledger field names exported from the top level are visible for direct inspection by code outside of the contract via the generated TypeScript `ledger()` function. It is a static error to export any other kind of binding from the top level. ## Include files[​](#include-files "Direct link to Include files") Compact allows programs and modules to be split into multiple files and spliced together via `include` forms, which have the following syntax, where *file* is a string literal specifying a filesystem pathname for file to be included: | | | | | -------------- | - | --------------------------------------- | | *include-form* | ⟶ | `include` [*file*](#terminal-names) `;` | *file* can be an absolute pathname, one that is relative to the directory of the including file, or one that is relative to one of the directories in the Compact path. Details on the search order and the mechanism for setting the Compact path are given in [Compiler Usage](/compact/compilation-and-tooling/compiler-usage.md). It is a static error if the file is not present or cannot be read. If present and readable, the file must contain a sequence of syntactically valid program elements, and these elements are treated as if they had been present in the including file in place of the `include` form. ## Declaring witnesses for private state management[​](#declaring-witnesses-for-private-state-management "Direct link to Declaring witnesses for private state management") A user's private state should be maintained in some secure way by the TypeScript driver of a smart contract and never stored directly in the public state of the contract. A contract must sometimes prove something about some piece of private state, however, as well as cause an update to the private state. The TypeScript driver of the smart contract can provide pieces of private state to the contract via the arguments of some exported circuit, and it can update the private state based on the return values of the exported circuit. A circuit can also access or update private state as it operates via *witnesses*. Witnesses are callback functions provided by the TypeScript driver. Witnesses must be declared to make them visible to the circuits of a contract. A witness declaration does not include a body, because the implementation is provided by the TypeScript driver. | | | | | --------------------- | - | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *witness-declaration* | ⟶ | `export`opt `witness` [*id*](#terminal-names) [*gparams*](#generic-parameters-and-arguments)opt [*simple-parameter-list*](#contract-types) `:` [*type*](#primitive-types) `;` | Witness declarations can appear anywhere among the program elements of a module or the contract's top level. For instance: ``` witness W(x: Uint<16>): Bytes<32>; ``` defines a witness `W`, to which the contract provides a 16-bit unsigned value and from which the contract receives 32 bytes of some presumably private data. danger Do not assume in your contract that the code of any `witness` function is the code that you wrote in your own implementation. Any DApp may provide any implementation that it wants for your `witness` functions. Results from them should be treated as untrusted input. ## Declaring and maintaining public state[​](#declaring-and-maintaining-public-state "Direct link to Declaring and maintaining public state") A contract declares the shape of its public state through *ledger declarations*. Each ledger declaration defines one piece of information that the contract might store in the public ledger. Multiple ledger declarations can appear in a program, or none. They can appear anywhere among the program elements of a module or the contract's top level. | | | | | -------------------- | - | ------------------------------------------------------------------------------------------- | | *ledger-declaration* | ⟶ | `export`opt `sealed`opt `ledger` [*id*](#terminal-names) `:` [*type*](#primitive-types) `;` | A ledger declaration binds a ledger field name to one of a set of predefined [ledger-state types](#ledger-state-types). For instance: ``` import CompactStandardLibrary; ledger val: Field; export ledger cnt: Counter; sealed ledger u8list: List>; export sealed ledger mapping: Map; ``` All ledger fields are initialized to the [default values of their ledger-state types](#default-values-of-a-type). The contract constructor, if any, runs after the default values are established, allowing the constructor to override the defaults. ### Ledger-state types[​](#ledger-state-types "Direct link to Ledger-state types") The following *ledger-state types* are supported. * *T*, for any regular Compact type *T* * `Counter` * `Set<`*T*`>`, for any Compact type *T* * `Map<`*K*, *T*`>`, for any Compact types *K* and *T* * `Map<`*K*, *V*`>`, for any Compact type *K* and ledger-state type *V* (see the following section) * `List<`*T*`>`, for any Compact type *T* * `MerkleTree<`*n*, *T*`>`, for any *n*, 1 < *n* ≤ 32, and any Compact type *T* * `HistoricMerkleTree<`*n*, *T*`>`, for any *n*, 1 < *n* ≤ 32, and any Compact type *T* * `Kernel`, a special type that yields access to ledger operations that do not depend on a specific ledger state Each ledger type supports a set of operations, which can be invoked with *F*`.`*op*(*e*, ⋯, *e*) where *F* is a field name, *op* is the name of a ledger operation supported by the ledger-state type of *F*, and each *e* is an argument expression. A ledger field that is declared with a Compact type *T* implicitly has the type `Cell<`*T*`>`, which supports several operations, including `read`, `write`, and `reset_to_default`. For example: ``` ledger F: Uint<16>; export circuit putF(x: Uint<16>): [] { F.write(disclose(x)); } export circuit getF(): Uint<16> { return F.read(); } ``` The `read` operation of the `Cell` ledger-state type can be abbreviated to, simply, a reference to the field name, and the `write(`*e*`)` operation can be abbreviated to an assignment of the form *F* `=` *e*. So the above can be written more simply as: ``` ledger F: Uint<16>; export circuit putF(x: Uint<16>): [] { F = disclose(x); } export circuit getF(): Uint<16> { return F; } ``` The `read` operation of the `Counter` type can be abbreviated in the same way, and its `increment` and `decrement` operations can be abbreviated to assignments of the form *F* `+=` *e* and *F* `-=` *e*. For example: ``` import CompactStandardLibrary; ledger F: Counter; export circuit incrF(): [] { F += 1; } export circuit decrF(): [] { F -= 1; } export circuit getF(): Uint<64> { return F; } ``` The selection of an appropriate ledger-state type can reduce a transaction's dependency on the exact contents of the ledger state and thus reduce the chance of a transaction being rejected when the proof is checked on chain. For example, the preceding example could be written using a `Cell` instead: ``` ledger F: Uint<64>; export circuit incrF(): [] { F = F + 1 as Uint<64>; } export circuit decrF(): [] { F = F - 1; } export circuit getF(): Uint<64> { return F; } ``` `incrF` and `decrF` read the value of `F` before operating on it and writing it back to `F`. This read commits the transaction to the current value of the field. If `F` has the value, say, 27 when the transaction is created, `F` must still have the value 27 when the proof is checked on chain. The `Counter` versions, however, do not read the value but merely request that the current value be incremented or decremented; thus, it does not have any such constraint. A comprehensive description of ledger-state types and operations can be found in the Compact [ledger data type documentation](/compact/reference/ledger-adt.md). ### Nested state types in the `Map` type[​](#nested-state-types-in-the-map-type "Direct link to nested-state-types-in-the-map-type") In most cases, ledger-state types cannot be nested within other ledger-state types. However, while `Map` keys must have regular Compact types, `Map` values can have either regular Compact types or ledger-state types (except `Kernel`). Attempting to nest a ledger-state type anywhere but within a `Map` value is a static error. Attempting to nest the `Kernel` type within a `Map` value is also a static error. Here is a small example showing two levels of nesting: ``` import CompactStandardLibrary; ledger fld: Map>; export circuit initNestedMap(b: Boolean): [] { fld.insert(disclose(b), default>); } export circuit initNestedCounter(b: Boolean, n: Field): [] { fld.lookup(b).insert(disclose(n), default); } export circuit incrementNestedCounter1(b: Boolean, n: Field, k: Uint<16>): [] { fld.lookup(b).lookup(n).increment(disclose(k)); } export circuit incrementNestedCounter2(b: Boolean, n: Field, k: Uint<16>): [] { fld.lookup(b).lookup(n) += disclose(k); } export circuit readNestedCounter1(b: Boolean, n: Field): Uint<64> { return fld.lookup(b).lookup(n).read(); } export circuit readNestedCounter2(b: Boolean, n: Field): Uint<64> { return fld.lookup(b).lookup(n); } ``` In this example, * `fld` is bound to a `Map` from `Boolean` values to `Map`s from `Field` values to `Counter`s * `initNestedMap` can be used to create the inner `Map` for a particular outer-`Map` key * `initNestedCounter` can be used to create a `Counter` for a given outer-`Map` key and a given inner-`Map` key * either `incrementNestedCounter1` or `incrementNestedCounter2` can be used to increment an existing `Counter` for a given outer-`Map` key and a given inner-`Map` key * either `readNestedCounter1` or `readNestedCounter2` can be used to read the value of an existing `Counter` for a given outer-`Map` key and a given inner-`Map` key. Notes: * Nested ledger-state values must be initialized before first use. The syntax `default<`*T*`>` can be used to create default ledger-state type values, just as it can be used to create default Compact type values. Attempting to operate on a nested ledger-state value without first initializing it is a dynamic error. * Ledger state type values are not first-class objects, so when accessing a nested value, the entire indirection chain must be used. For example, the following is a static error: ``` export circuit incrementNestedCounter(b: Boolean, n: Field, k: Uint<16>): [] { fld.lookup(b); // ERROR: incomplete chain of indirects } ``` * When the last operation is a write of a base type, increment of a Counter type, or decrement of a Counter type, one can replace the `write`, `increment`, or `decrement` operation with the `=`, `+=`, or `-=` assignment syntax, as illustrated by `incrementNestedCounter1` and `incrementNestedCounter2`, which have the same behavior. * When the last operation is a read of a Counter or base type one can omit the explicit `read()` indirect, as illustrated by `readNestedCounter1` and `readNestedCounter2`, which have the same behavior. * For convenience, local variables can hold default values of ledger-state types, so the following definition of `initNestedMap` is equivalent to the one above. ``` export circuit initNestedMap(b: Boolean): [] { const t = default>; fld.insert(disclose(b), t); } ``` ### Sealed and unsealed ledger fields[​](#sealed-and-unsealed-ledger-fields "Direct link to Sealed and unsealed ledger fields") Any ledger field can be marked *sealed* by prefixing the ledger field declaration with the optional modifier `sealed`. A sealed field cannot be set except during contract initialization. That is, its value can be modified only by the contract constructor (if any), either directly within the body of the constructor or via helper circuits called by the constructor. The `sealed` keyword must come after the `export` keyword (if present) and before the `ledger` keyword, as in the following example: ``` sealed ledger field1: Uint<32>; export sealed ledger field2: Uint<32>; circuit init(x: Uint<32>): [] { field2 = disclose(x); } constructor(x: Uint<16>) { field1 = 2 * disclose(x); init(x); } ``` It is a static error if a sealed ledger field is updated by any code that is reachable from an exported circuit. ## Contract constructor[​](#contract-constructor "Direct link to Contract constructor") A contract can be initialized via a contract constructor defined at the program's top level. | | | | | ------------------------ | - | ---------------------------------------------------------------------------------------------------------- | | *constructor-definition* | ⟶ | `constructor` [*pattern-parameter-list*](#contract-constructor) [*block*](#blocks) | | *pattern-parameter-list* | ⟶ | `(` [*typed-pattern*](#contract-constructor) `,` ⋯ `,` [*typed-pattern*](#contract-constructor) `,`opt `)` | | *typed-pattern* | ⟶ | [*pattern*](#patterns-and-destructuring) `:` [*type*](#primitive-types) | The constructor, if any, is typically used to initialize public state and can also be used to initialize private state through witness calls. At most one contract constructor can be defined for a contract, and it must appear only at the program top level, i.e., it cannot be defined in a module. To initialize ledger fields that are visible only within a module, the constructor can call a circuit that is exported from the module. For example: ``` module PublicState { enum STATE { unset, set } ledger state: STATE; ledger value: Field; export circuit init(v: Field): [] { value = disclose(v); state = STATE.set; } } import PublicState; constructor(v: Field) { init(v); } ``` Each constructor parameter must have an explicit type annotation. The type of each variable binding arising from the binding of identifiers in each parameter pattern to the corresponding pieces of the input is the type of the corresponding part of the declared type's structure. The return type of the constructor is always `[]`. Any attempt to return another type of value using `return` *expr*`;` where the type of *expr* is something other than `[]`, is a static error. ## Circuit definitions[​](#circuit-definitions "Direct link to Circuit definitions") The basic operational element in Compact is the *circuit*. This corresponds closely to a function in most languages but is designed to be compilable into a zero-knowledge circuit. The key limitation of circuits relative to functions in most languages is that circuits cannot be recursive, either directly or indirectly. Compact supports two kinds of circuits: named circuits and anonymous circuits. Named circuits are described here, and anonymous circuits are described in [Circuit and witness calls](#circuit-and-witness-calls). Named circuit definitions have the following syntax: | | | | | -------------------- | - | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | *circuit-definition* | ⟶ | `export`opt `pure`opt `circuit` [*function-name*](#terminal-names) [*gparams*](#generic-parameters-and-arguments)opt [*pattern-parameter-list*](#contract-constructor) `:` [*type*](#primitive-types) [*block*](#blocks) | A circuit definition binds *function-name* to a circuit with the given parameters, return type, and body. The optional `export` modifier indicates that the circuit binding should be exported from the enclosing module or the program itself, if the circuit is defined outside of any module. The optional `pure` modifier indicates that the [circuit is pure](#pure-and-impure-circuits). If any generic parameters are present (*gparams* is present and is nonempty), the circuit is [generic](#generic-parameters-and-arguments) and must be specialized (provided with generic arguments) at the point of call. Circuits can take zero or more parameters. The parameters are all [patterns](#patterns-and-destructuring) containing identifiers to be bound to selected pieces of the argument values. In the simplest case, a pattern is just an identifier and is bound to the argument value as a whole. The bindings established by the parameters are visible within (and only within) the *block* that constitutes the body of the circuit. Each parameter must have an explicit type annotation, and at the point of every call to the circuit, the type of the corresponding argument expression must be a subtype of that type. The type of each variable binding arising from the binding of identifiers in each parameter pattern to the corresponding pieces of the input is the type of the corresponding part of the declared type's structure. For example, in the body of `sumStruct` below: ``` struct S { x: Uint<16>, y: Uint<32> } circuit sumStruct({x, y}: S): Uint<64> { return x + y; } ``` The variable binding established for `x` by the pattern `{x, y}` has type `Uint<16>`, and the variable binding for `y` has type `Uint<32>`. Every named circuit's return type must be explicitly declared, and it is a static error if the circuit can return a value that is not a subtype of that type. The body is evaluated each time the circuit is called. ### Pure and impure circuits[​](#pure-and-impure-circuits "Direct link to Pure and impure circuits") A Compact circuit is considered *pure* if it computes its outputs from its inputs without reference to or modification of public state (via the ledger) or private state (via witnesses). In practice, the compiler considers a circuit to be impure if the body of the circuit contains a ledger operation, an emit operation, a call to any impure circuit, or a call to a witness. Some external circuits defined in `CompactStandardLibrary` are witnesses; calls to these make the caller impure. The remainder are considered pure, so calls to those do not make the caller impure. A Compact program can declare a circuit to be pure by prefixing the circuit definition with the `pure` modifier, which must follow the `export` modifier, if present, e.g.: `pure circuit c(a: Field): Field { `⋯` }` `export pure circuit c(a: Field): Field { `⋯` }` The only effect of the `pure` modifier is that the compiler flags the declaration as an error if its own analysis determines that the circuit is actually impure. The pure modifier allows an application to ensure that the circuit is present in the `PureCircuits` type declaration and via the `pureCircuits` constant in the TypeScript module produced for a (correct) Compact program by the Compact compiler. ## Blocks[​](#blocks "Direct link to Blocks") A *block* is a group of statements enclosed in braces: | | | | | ------- | - | ------------------------------------------------------------------------- | | *block* | ⟶ | `{` [*stmt*](#syntax-of-statements) ⋯ [*stmt*](#syntax-of-statements) `}` | A block can be used in place of a single statement anywhere a single statement is allowed, which is useful for allowing multiple statements to be evaluated by the "then" and "else" parts of an `if` statement or the body of a `for` statement. The body of every circuit definition and the body of the constructor, if any, is always a block. The right-hand side of the arrow in an anonymous circuit can be either a block or an expression. The statements within a block occupy a nested scope: variable bindings created by `const` statements within the block are not visible outside the block, and they can shadow identifier bindings with the same names that exist outside the block. A block is well-typed if the statements within it are well-typed. A block is evaluated by evaluating the statements in sequence. ## Statements[​](#statements "Direct link to Statements") Compact statements are used to perform computations or effects with the help of Compact expressions. Statements either do not have values or (in the case of [expression sequences serving as statements](#expression-sequences-used-as-statements)) the values are ignored. Thus it is not necessary to talk about the type of a statement. Nevertheless, each statement has typing rules that must be followed, such as that the type of the test expression of an `if` statement must be `Boolean`. The first subsection of this section presents a grammar snippet that summarizes the syntax of Compact statements. The remaining subsections describe the typing and evaluation rules of the various kinds of statements. ### Syntax of statements[​](#syntax-of-statements "Direct link to Syntax of statements") | | | | | ------- | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | *stmt* | ⟶ | `if` `(` [*expr-seq*](#syntax-of-expressions) `)` [*stmt*](#syntax-of-statements) | | | \| | [*stmt0*](#syntax-of-statements) | | *stmt0* | ⟶ | [*expr-seq*](#syntax-of-expressions) `;` | | | \| | `const` [*cbinding*](#const-statements) `,` ⋯¹ `,` [*cbinding*](#const-statements) `;` | | | \| | `if` `(` [*expr-seq*](#syntax-of-expressions) `)` [*stmt0*](#syntax-of-statements) `else` [*stmt*](#syntax-of-statements) | | | \| | `for` `(` `const` [*id*](#terminal-names) `of` [*start*](#syntax-of-statements) `..` [*end*](#syntax-of-statements) `)` [*stmt*](#syntax-of-statements) | | | \| | `for` `(` `const` [*id*](#terminal-names) `of` [*expr-seq*](#syntax-of-expressions) `)` [*stmt*](#syntax-of-statements) | | | \| | `return` [*expr-seq*](#syntax-of-expressions) `;` | | | \| | `return` `;` | | | \| | [*block*](#blocks) | | *start* | ⟶ | [*tsize*](#primitive-types) | | *end* | ⟶ | [*tsize*](#primitive-types) | The grammar snippet above shows that a statement (*stmt*) is either a one-armed `if` statement or some other kind of statement (*stmt0*). This structure is used to enforce the restriction that the "then" part of a two-armed `if` cannot be a one-armed `if`. This is often left ambiguous in a language grammar, with a separate note to say that the ambiguity is resolved by associating each "else" part with the closest enclosing `if` statement, but here the constraint is explicit in the grammar. ### Expression sequences used as statements[​](#expression-sequences-used-as-statements "Direct link to Expression sequences used as statements") Any *expression sequence* (*expr-seq*), i.e., comma-separated sequence of one or more expressions to be evaluated in sequence, can be used as a statement. Expression sequences are described in [their own section](#expression-sequences). ### `const` statements[​](#const-statements "Direct link to const-statements") `const` statements create local variable bindings. Every `const` statement takes the following form: `const` *cbinding* `,` ⋯¹ `,` *cbinding* `;` where each *cbinding* takes the following form: | | | | | -------------------------- | -- | ------------------------------------------------------------------------------------ | | *cbinding* | ⟶ | [*optionally-typed-pattern*](#const-statements) `=` [*expr*](#syntax-of-expressions) | | *optionally-typed-pattern* | ⟶ | [*pattern*](#patterns-and-destructuring) | | | \| | [*typed-pattern*](#contract-constructor) | A `const` statement is typed by typing each of its *cbinding* subforms. A *cbinding* subform is typed by typing the expression on the right-hand side of the `=`. If a type *T* is declared on the left-hand side, the type of the expression must be a subtype of *T*, otherwise it is a static error. It is also a static error if the pattern implies a different structure from the type of the expression. For example, it is a static error if the pattern implies that the expression's value is a tuple when the type is actually, say, `Field`. The type of each variable binding arising from the binding of identifiers in each pattern to the corresponding pieces of the input is the type of the corresponding part of the structure of the declared type, if present, otherwise of the inferred type. For example, in the following code, the binding for `x` has type `Boolean`, and the binding for `y` has type `[Uint<64>, Uint<64>]`: ``` witness w(): [Boolean, [Uint<16>, Uint<32>]]; circuit foo(): [Uint<64>, Uint<64>] { const [x, y]: [Boolean, [Uint<64>, Uint<64>]] = w(); return x ? y : [0, 0]; } ``` while in the following, `x` still has type `Boolean` but `y` has (the inferred) type `[Uint<16>, Uint<64>]`. ``` witness w(): [Boolean, [Uint<16>, Uint<32>]]; circuit foo(): [Uint<64>, Uint<64>] { const [x, y] = w(); return x ? y : [0, 0]; } ``` Except where shadowed, the scope of each variable bound by a `const` statement is the entirety of the innermost block containing the `const` statement. It must not be referenced, however, before it is given a binding. Any attempt to do so is a static error. For example, the reference to `x` on the first line of the body in the definition of `foo` below is a static error: ``` circuit foo(a: Uint<16>): Field { const y = x + a; const x = 7; return y; } ``` Similarly, the reference to `x` in the first *cbinding* of the `const` statement below is also a static error: ``` const y = x, x = 7; ``` A `const` statement is evaluated by evaluating the *cbinding* subforms in order so that the variables given values by each *cbinding* are available to be referenced by the cbindings that follow. The evaluation of each *cbinding* involves determining the value *v* of the expression on the right-hand side of the `=`, then giving values to identifiers in the pattern *p* on the left-hand side to the corresponding pieces of *v* as described earlier in [Patterns and destructuring](#patterns-and-destructuring). Any variable bound by `const` may not be reused within a block, although a `const` binding in a nested block might [shadow it](#identifiers-bindings-and-scope). Variables are immutable, although the same variable might take on different values at different times if it is contained within a block of code that is evaluated more than once, such as would be the case for the body of a circuit that is called more than once. ### `if` statements[​](#if-statements "Direct link to if-statements") An `if` statement is used to determine the flow of control through the statements of a circuit or constructor body. A *one-armed* `if` expression has a "test part" (an *expr-seq* enclosed in parentheses) and a "then part" (*then-statement*): `if (`*expr-seq*`)` *then-statement* A *two-armed* `if` statement has a test part, a then part, and an "else part" (*else-statement*): `if (`*expr-seq*`)` *then-statement* `else` *else-statement* The typing of an `if` statement requires only that the type of *expr-seq* must be `Boolean`. Evaluating an `if` expression involves first determining the value *v* of *expr-seq*. If *v* is `true`, *then-statement* is evaluated. Otherwise, *v* must be `false`, in which case *else-statement* (if present), is evaluated. ### `for` statements[​](#for-statements "Direct link to for-statements") `for` statements are used to iterate over a sequence of values. In Compact, in contrast to most languages, the number of iterations can always be determined at compile time. That is, the number of iterations is bounded either by constant numeric bounds or by size of an object of constant size. This restriction is motivated by the need for the compiler to generate finite proving circuits. Compact supports two kinds of `for` statements. The first iterates over vectors, tuples, and byte vectors and takes the following form: `for (const` *x* `of` *expr*`)` *stmt* This kind of `for` statement is typed by typing *expr* and verifying that it is a `Vector` type, a tuple type that [has a vector type](#subtyping-and-least-upper-bounds), or a `Bytes` type. Evaluating this kind of `for` requires determining the vector, tuple, or byte-vector value *v* of *expr* then evaluating *stmt* once for each element of *v* with *x* bound to the value of each element of *v* in turn. The second form iterates over a range of unsigned integer values and takes the following form: `for (const` *i* `of` *start* `..` *end*`)` *stmt* In this form, each of *start* and *end* must be a literal unsigned integer or reference to a generic natural-number parameter, and *end* must be greater than or equal to *start*. Otherwise, it is a static error. This form is always well-typed. Evaluating this kind of `for` requires evaluating *stmt* with *i* bound to *k* for each *k* in the range *start* (inclusive) to *end* (exclusive). `return` statements cannot be used to return from within `for` statements. It is therefore a static error for *stmt* to be a `return` statement or for a `return` statement to appear within *stmt* (except where it appears nested within an anonymous circuit). Iteration can also be accomplished via [`map` and `fold` expressions](#map-and-fold-expressions). ### `return` statements[​](#return-statements "Direct link to return-statements") A `return` statement can be used to exit from the closest enclosing [anonymous circuit](#circuit-and-witness-calls), if any, or otherwise from the enclosing constructor or named circuit, and to return to the caller either an explicit return value, i.e., the value of [*expr-seq*](#expression-sequences) in this form of `return`: `return` *expr-seq*`;` or the default value `[]` in this form of `return`: `return;` A circuit or constructor body can also exit without an explicit `return` statement: any path through the body that does not end in an explicit `return` statement is treated as if ended with `return;`. A `return` statement is always well-typed if it exits from an anonymous circuit without a declared return type. Otherwise, a `return` statement is well-typed if the type of *expr-seq*, or `[]` if no *expr-seq* is present, is a subtype of the expected return type. If the `return` form exits from a named circuit or an anonymous circuit with a declared return type, the expected type is the declared return type, while if it exits from the constructor, the expected return type is `[]`. An implication of these rules is that it is a static error to exit without an explicit return value from a circuit with a declared return type other than `[]`. When a `return` statement is evaluated, the *expr-seq*, if present, is evaluated, the circuit or constructor exits immediately without evaluating any subsequent statements, and it returns to the caller the value of *expr-seq* or `[]` if no *expr-seq* is present. ## Expressions[​](#expressions "Direct link to Expressions") Compact expressions are used to compute values, to cause effects, or both. Every Compact expression must be well-typed (free from static type errors). If any expression within a program contains a static type error, it is a static error: the Compact compiler reports the error and does not produce any target code (TypeScript or zkir) for the program. The static type of a well-typed expression is either a Compact type or a ledger-state type. Every well-typed Compact expression either evaluates to a value or causes a dynamic error, and it might have effects. The evaluation of an expression is defined in terms of the evaluation of its subexpressions. The first subsection of this section provides a grammar snippet that summarizes the syntax of Compact expressions, and the second discusses how the grammar reflects the rules for precedence and associativity of operators. The remaining sections describe the typing and evaluation rules for each kind of expression. ### Syntax of expressions[​](#syntax-of-expressions "Direct link to Syntax of expressions") | | | | | ------------ | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | *expr-seq* | ⟶ | [*expr*](#syntax-of-expressions) | | | \| | [*expr*](#syntax-of-expressions) `,` ⋯¹ `,` [*expr*](#syntax-of-expressions) `,` [*expr*](#syntax-of-expressions) | | *expr* | ⟶ | [*expr0*](#syntax-of-expressions) `?` [*expr*](#syntax-of-expressions) `:` [*expr*](#syntax-of-expressions) | | | \| | [*expr0*](#syntax-of-expressions) `=` [*expr*](#syntax-of-expressions) | | | \| | [*expr0*](#syntax-of-expressions) `+=` [*expr*](#syntax-of-expressions) | | | \| | [*expr0*](#syntax-of-expressions) `-=` [*expr*](#syntax-of-expressions) | | | \| | [*expr0*](#syntax-of-expressions) | | *expr0* | ⟶ | [*expr0*](#syntax-of-expressions) `\|\|` [*expr1*](#syntax-of-expressions) | | | \| | [*expr1*](#syntax-of-expressions) | | *expr1* | ⟶ | [*expr1*](#syntax-of-expressions) `&&` [*expr2*](#syntax-of-expressions) | | | \| | [*expr2*](#syntax-of-expressions) | | *expr2* | ⟶ | [*expr2*](#syntax-of-expressions) `==` [*expr3*](#syntax-of-expressions) | | | \| | [*expr2*](#syntax-of-expressions) `!=` [*expr3*](#syntax-of-expressions) | | | \| | [*expr3*](#syntax-of-expressions) | | *expr3* | ⟶ | [*expr4*](#syntax-of-expressions) `<` [*expr4*](#syntax-of-expressions) | | | \| | [*expr4*](#syntax-of-expressions) `<=` [*expr4*](#syntax-of-expressions) | | | \| | [*expr4*](#syntax-of-expressions) `>=` [*expr4*](#syntax-of-expressions) | | | \| | [*expr4*](#syntax-of-expressions) `>` [*expr4*](#syntax-of-expressions) | | | \| | [*expr4*](#syntax-of-expressions) | | *expr4* | ⟶ | [*expr4*](#syntax-of-expressions) `as` [*type*](#primitive-types) | | | \| | [*expr5*](#syntax-of-expressions) | | *expr5* | ⟶ | [*expr5*](#syntax-of-expressions) `+` [*expr6*](#syntax-of-expressions) | | | \| | [*expr5*](#syntax-of-expressions) `-` [*expr6*](#syntax-of-expressions) | | | \| | [*expr6*](#syntax-of-expressions) | | *expr6* | ⟶ | [*expr6*](#syntax-of-expressions) `*` [*expr7*](#syntax-of-expressions) | | | \| | [*expr7*](#syntax-of-expressions) | | *expr7* | ⟶ | `!` [*expr7*](#syntax-of-expressions) | | | \| | [*expr8*](#syntax-of-expressions) | | *expr8* | ⟶ | [*expr8*](#syntax-of-expressions) `[` [*expr*](#syntax-of-expressions) `]` | | | \| | [*expr8*](#syntax-of-expressions) `.` [*id*](#terminal-names) | | | \| | [*expr8*](#syntax-of-expressions) `.` [*id*](#terminal-names) `(` [*expr*](#syntax-of-expressions) `,` ⋯ `,` [*expr*](#syntax-of-expressions) `,`opt `)` | | | \| | [*expr9*](#syntax-of-expressions) | | *expr9* | ⟶ | [*fun*](#circuit-and-witness-calls) `(` [*expr*](#syntax-of-expressions) `,` ⋯ `,` [*expr*](#syntax-of-expressions) `,`opt `)` | | | \| | `map` `(` [*fun*](#circuit-and-witness-calls) `,` [*expr*](#syntax-of-expressions) `,` ⋯¹ `,` [*expr*](#syntax-of-expressions) `,`opt `)` | | | \| | `fold` `(` [*fun*](#circuit-and-witness-calls) `,` [*expr*](#syntax-of-expressions) `,` [*expr*](#syntax-of-expressions) `,` ⋯¹ `,` [*expr*](#syntax-of-expressions) `,`opt `)` | | | \| | `slice` `<` [*tsize*](#primitive-types) `>` `(` [*expr*](#syntax-of-expressions) `,` [*expr*](#syntax-of-expressions) `)` | | | \| | `[` [*tuple-arg*](#syntax-of-expressions) `,` ⋯ `,` [*tuple-arg*](#syntax-of-expressions) `,`opt `]` | | | \| | `Bytes` `[` [*bytes-arg*](#syntax-of-expressions) `,` ⋯ `,` [*bytes-arg*](#syntax-of-expressions) `,`opt `]` | | | \| | [*tref*](#primitive-types) `{` [*struct-arg*](#syntax-of-expressions) `,` ⋯ `,` [*struct-arg*](#syntax-of-expressions) `,`opt `}` | | | \| | `assert` `(` [*expr*](#syntax-of-expressions) `,` [*str*](#terminal-names) `)` | | | \| | `emit` `(` [*expr*](#syntax-of-expressions) `)` | | | \| | `disclose` `(` [*expr*](#syntax-of-expressions) `)` | | | \| | [*term*](#syntax-of-expressions) | | *term* | ⟶ | [*id*](#terminal-names) | | | \| | `true` | | | \| | `false` | | | \| | [*nat*](#terminal-names) | | | \| | [*str*](#terminal-names) | | | \| | `pad` `(` [*nat*](#terminal-names) `,` [*str*](#terminal-names) `)` | | | \| | `default` `<` [*type*](#primitive-types) `>` | | | \| | `(` [*expr-seq*](#syntax-of-expressions) `)` | | *struct-arg* | ⟶ | [*expr*](#syntax-of-expressions) | | | \| | [*id*](#terminal-names) `:` [*expr*](#syntax-of-expressions) | | | \| | `...` [*expr*](#syntax-of-expressions) | | *bytes-arg* | ⟶ | [*tuple-arg*](#syntax-of-expressions) | | *tuple-arg* | ⟶ | [*expr*](#syntax-of-expressions) | | | \| | `...` [*expr*](#syntax-of-expressions) | ### Precedence and associativity[​](#precedence-and-associativity "Direct link to Precedence and associativity") The structure of the expression grammar unambiguously reflects the precedence and associativity of operators. Each group from *expr-seq* through *term* represents a precedence level, with *expr-seq* at a higher precedence level than *expr*, *expr* at a higher level than *expr0*, and so on. For example, *expr6* (multiplication) is at a higher precedence level and so binds more tightly than *expr5* (addition) because the grammar permits the operands of an addition expression to be multiplication expressions, but not vice versa. For example, `x * y + z` is parsed as the addition of `x * y` and `z` rather than the multiplication of `x` and `y + z`, because the *expr5* production for addition is not reachable from the *expr6* production for multiplication. One can still write `x * (y + z)` because an *expr6* can be a *term* (via the "fall through" productions *expr6* ⟶ *expr7*, *expr7* ⟶ *expr8*, and so on), a *term* can be a parenthesized *expr-seq*, and an *expr-seq* can be an *expr*. The grammar enforces associativity by requiring the left or right operand of an operator or both to be at a higher precedence level. Specifically, left-associativity is expressed by requiring the right operand to be at a higher level while allowing the left operand to be at the same level. For instance, *expr5* ⟶ *expr5* `+` *expr6* enforces the left-associativity of addition, since the left operand must be at a higher level. This means, for example, that `x + y - z` can be treated only as the subtraction of `z` from `x + y` rather than as the addition of `x` and `y - z`. Right-associativity is expressed in the opposite manner, e.g., *expr0* `?` *expr* `:` *expr* enforces the right-associativity of the ternary `?:` operator. Non-associative operators such as the relational operators `<`, `<=`, `>=`, and `>` require both operands to be at a strictly higher level (*expr4* on both sides of *expr3*), preventing chaining like `a < b < c`. The middle operand of the ternary `?:` operator plays no roll in determining precedence and associativity and can be any kind of expression. (The grammar could even have allowed it to be an expression sequence, but Compact follows TypeScript and JavaScript in restricting it to be a single expression.) In fact, the grammar has many examples where a lower precedence expression is embedded in a higher-precedence expression; this does not result in any ambiguity because the operand is not exposed on the left or right side of the expression where it can be confused as an operand of some other operator. ### Parenthesized expressions[​](#parenthesized-expressions "Direct link to Parenthesized expressions") Compact allows parenthesized expressions of the form `(`*e*`)`, where *e* is an expression or, more generally, an expression sequence. Parenthesized expressions can be used to control the order of operations or simply to make the default order of operations explicit. For example, `x + y * z` computes the product of `y` and `z` and adds `x` to the result, because `*` has higher precedence than `+`. `x + (y * z)` computes the same thing but makes the order of operations more clear, while `(x + y) * z` computes the sum of `x` and `y` and multiplies it by `z`. The type of a parenthesized expression is the type of the embedded expression sequence, and its value is the value of the subexpression. ### Expression sequences[​](#expression-sequences "Direct link to Expression sequences") An expression sequence (*expr-seq* in the grammar above) is a comma-separated sequence of one or more expressions. *expr*`,` ⋯`,` *expr* Expression sequences can appear only in a few contexts. When an expression sequence is required in a context where only a single expression is permitted, the expression sequence can be wrapped in parentheses: `(`*expr*`,` ⋯`,` *expr*`)` The type of an expression sequence is the type of its last subexpression. The types of the other subexpressions are ignored and are not constrained in any way. An expression sequence is evaluated by evaluating the subexpressions from left to right, and its value is the value of the last subexpression. The values of the other subexpressions are ignored; these other subexpressions are evaluated solely for their effects. ### Literals[​](#literals "Direct link to Literals") Compact has syntax for Boolean, numeric, and string literal expressions. A **Boolean literal** is one of the reserved words `true` or `false`. The static type of a Boolean literal is `Boolean` and its value is the corresponding Boolean value. A **numeric literal** is a non-negative integer written in decimal, binary, octal, or hexadecimal notation as follows: * decimal: either the single digit `0` or a sequence of one or more decimal digits (`0-9`) starting with a non-zero digit, e.g., `0` or `7091`; * binary: the prefix `0b` or `0B` followed by one or more binary digits (`0` or `1`), e.g., `0b1101001`; * octal: the prefix `0o` or `0O` followed by one or more octal digits (`0-7`), e.g., `0o5073`; or * hexadecimal: the prefix `0x` or `0X` followed by one or more hexadecimal digits (`0-9`, `a-f`, `A-F`), e.g., `0x8f0a`. An occurrence of a numeric literal can arise via specialization of a generic module or circuit in which a reference to a generic natural-number parameter occurs in an expression context. For example, if `foo` is defined as follows: ``` circuit foo<#N>(): Uint<16> { return N; } ``` the call `foo<17>()`, at least in effect, gives rise to a copy of `foo` in which `N` has been replaced by `17`. ``` circuit foo(): Uint<16> { return 17; } ``` This is treated exactly as if the numeric literal appeared in place of the reference to `N` in the source code of the program. It is a static error if the number *n* denoted by a numeric literal exceeds the maximum unsigned value and the maximum field value. If *n* does not exceed the maximum representable unsigned value, the literal's type is `Uint<0..`*k*`>`, *k* `=` *n*+1, and its value is the unsigned integer *n*. If *n* exceeds the maximum representable unsigned value but not the maximum representable field value, the literal must be directly cast to `Field`, i.e., *n* `as Field`. Otherwise it is a static error. The type of *n* `as Field` is `Field`, and its value is the field value *n*. **String literals** can be either simple string literals or `pad` expressions. String literals produce byte vectors; Compact has no dedicated String type. Simple string literals use TypeScript string literal syntax. They can be enclosed in either single (`'`) or double (`"`) quotes, and they can contain escaped characters. The length *n* of a simple string literal is the length of its UTF-8 encoding. The static type of a string literal of length *n* is `Bytes<`*n*`>`, and its value is a byte vector containing its UTF-8 encoding. A `pad` expression `pad(`*n*`,` *s*`)` is also a string literal, where `pad` is a reserved word, *n* is a natural number literal, and *s* is a simple string literal. The length of *s* must be less than or equal to *n*; otherwise, it is a static error. The static type of a padded string literal `pad(`*n*`,` *s*`)` is `Bytes<`*n*`>`, and its value is a byte vector containing the UTF-8 encoding of *s* followed by `0` bytes up to the padded length *n*. ### Default values of a type[​](#default-values-of-a-type "Direct link to Default values of a type") The expression `default<`*T*`>`, where *T* is a Compact type or a ledger-state type, has static type *T* and evaluates to the default value of that type as follows: * `Boolean`: the value of the literal `false` * `Uint<0..`*n*`>` and `Uint<`*n*`>`: `0` * `Field`: `0` * `[`*T1*`, `⋯`, `*Tn*`]`: a tuple with *n* elements, each of which is the default value of the corresponding type *Ti* * `Vector<`*n*`, `*T*`>`: a vector with *n* elements, each of which is the default value of type *T*. * `Bytes<`*n*`>`: a byte vector of length *n*, each element of which is `0`. * `Opaque<"string">`: a zero-length string * `Opaque<"Uint8Array">`: a zero-length `Uint8Array` * Structure types: a struct with each element set to the default value of its type * Enumeration types: the value of *E*`.`*id* where *E* is the name of the enumeration type and *id* is the first element * alias types: the default value of the underlying type * `Counter`: a Counter initialized to `0` * `Set<`*T*`>`: an empty Set * `Map<`*K*`, `*T*`>`: an empty Map * `List<`*T*`>`: an empty List * `MerkleTree<`*n*`, `*T*`>`: an empty Merkle tree * `HistoricMerkleTree<`*n*`, `*T*`>`: an empty historic Merkle tree Default values are not defined for contract types or the `Kernel` ledger-state type, so it is a static error if *T* in `default<`*T*`>` is one of these types. ### Variable references[​](#variable-references "Direct link to Variable references") A variable reference is an identifier reference to a variable binding in scope. The type of a variable reference is the type of the binding to which it refers. Each call to a circuit (or constructor) associates a new set of values with each variable bound by the circuit's (or constructor's) parameters, and each block in the circuit (or constructor) associates a new set of values with each of the `const` bindings created within the block. The value of each variable reference is the value currently associated with the variable. ### Conditional expressions[​](#conditional-expressions "Direct link to Conditional expressions") Compact supports conditional expressions of the form *e0* `?` *e1* `:` *e2* where *e0*, *e1*, and *e2* are expressions. The type of *e0* must be `Boolean`. The types of *e1* and *e2* must be related. That is, the type of *e1* must be a subtype of the type of *e2*, or the type of *e2* must be a subtype of the type of *e1*. The type of the entire expression is the type of *e2* if *e1* is a subtype of *e2* and the type of *e1* if *e2* is a subtype of *e1*. A conditional expression *e0* `?` *e1* `:` *e2* is evaluated by first evaluating *e0*. The value *v* of *e0* determines which of the other subexpressions is evaluated: * if *v* is `true`, then *e1* is evaluated and its value is the value of the entire expression * if *v* is `false`, then *e2* is evaluated and its value is the value of the entire expression The evaluation rules ensure that only one of *e1* and *e2* is evaluated. ### Relational comparison expressions[​](#relational-comparison-expressions "Direct link to Relational comparison expressions") Relational comparison expressions take the form *e1 op e2* where *e1* and *e2* are expressions and *op* is one of Compact's relational operators. The relational operators are **equals** (`==`), **not equals** (`!=`), **less than** (`<`), **greater than** (`>`), **less than or equals** (`<=`), and **greater than or equals** (`>=`). Equals and not equals require the types of *e1* and *e2* to be related. That is, the type of *e1* must be a subtype of the type of *e2*, or the type of *e2* must be a subtype of the type of *e1*. Otherwise, it is a static error. Less than, greater than, less than or equals, and greater than or equals require the types of *e1* and *e2* to be unsigned integer types. Otherwise, it is a static error. (Values of type `Field` cannot be compared with these operators.) The type of the result is `Boolean`. A relational comparison expression *e1 op e2* is evaluated by evaluating *e1*, then evaluating *e2*, then comparing the resulting values as described below. **Equals and not equals** Equality depends on the types of the operands according to the following rules. The rules need not and therefore do not cover cases where one operand is not a subtype of the other, as required by typing rules above. For example, if one operand has type `Boolean`, so does the other; if one operand has a `Bytes` type of length *n*, so does the other; and if one has a specific structure type, so does the other. * **`Boolean`:** the values are equal if both are `true` or both are `false`. * **`Field` and `Uint` types:** the values are equal if the integer values are equal. * **`Bytes`:** the values are equal if the corresponding bytes at each index are equal. * **`Vector` and tuple types:** the values are equal if the corresponding values at each index are equal. * **Structure types:** the values are equal if the values of the corresponding fields are equal. * **Enumeration types:** the values are equal if they are the same enumeration member. * **`Opaque<"string">`:** the values are equal if the run-time values are equal according to JavaScript's strict equality (`===`) operator. * **`Opaque<"Uint8Array">`:** the values are equal if the run-time values have the same length and they are element-wise equal according to JavaScript's strict equality (`===`) operator. Otherwise the values are not equal. For *equal*, the relational comparison expression evaluates to `true` if the values are equal; otherwise it evaluates to `false`. Likewise, for *not equals*, the relational comparison expression evaluates to `false` if the values are equal; otherwise it evaluates to `true`. **Less than, greater than, less than or equals, and greater than or equals** The values are compared according to the corresponding relational operation. The relational comparison expression evaluates to `true` if the relation holds; otherwise it evaluates to `false`. ### Short-circuit logical expressions[​](#short-circuit-logical-expressions "Direct link to Short-circuit logical expressions") Compact supports short-circuit logical expressions of the form *e1 op e2* where *e1* and *e2* are expressions and *op* is one of the logical operators **or** (`||`) or **and** (`&&`). Logical expressions require the types of both subexpressions to be `Boolean`. Otherwise it is a static error. The logical expression itself also has type `Boolean`. Evaluating *e1 op e2* involves first evaluating *e1* to determine its value *v*, then: * For `||`, if *v* is `true`, *e2* is *not* evaluated, and the value of the entire expression is `true`. Otherwise, *e2* *is* evaluated, and its value is the value of the entire expression. * For `&&`, if *v* is `false`, *e2* is *not* evaluated, and the value of the entire expression is `false`. Otherwise, *e2* *is* evaluated, and its value is the value of the entire expression. These are short-circuiting operators because they do not evaluate the second operand if the final value is determined from the first. ### Boolean negation expressions[​](#boolean-negation-expressions "Direct link to Boolean negation expressions") Compact supports unary Boolean negation expressions of the form `!`*e* where *e* is an expression. The type of *e* must be of type `Boolean`, otherwise it is a static error. The Boolean-negation expression itself also has type `Boolean`. A Boolean negation expression `!`*e* is evaluated by evaluating *e* to determine its value *v*. Then if *v* is `true`, the value of the Boolean negation expression is `false`, and If *v* is `false`, the value of the Boolean negation expression is `true`. ### Binary arithmetic expressions[​](#binary-arithmetic-expressions "Direct link to Binary arithmetic expressions") Binary arithmetic expressions have the form *e1 op e2*, where *e1* and *e2* are operand expressions and *op* is one of Compact's binary arithmetic operators. The binary arithmetic operators are **add** (`+`), **subtract** (`-`) and **multiply** (`*`). Arithmetic expressions require the type of each operand to be a numeric type, that is, either a `Field`, a `Uint`, or a type alias for a `Field` or a `Uint`. Putting aside type aliases for now, the type of the result depends on the types of the operands as follows: * If both operands have type `Field`, the result has type `Field`. * If both operands have `Uint` types, i.e., *e1* has type `Uint<0..`*m*`>` for some *m* and *e2* has type `Uint<0..`*n*`>` for some *n*, the type of the result depends on the operation as follows: * for add, the result has type `Uint<0..`*m+n*`>`, * for subtract, the result has type `Uint<0..`*m*`>`, and * for multiply, the result has type `Uint<0..`*m⋅n*`>`. * If one operand has type `Field` and the other has type `Uint<0..`*n*`>` where *n-1* is less than or equal to the maximum field value, the `Uint` operand is implicitly cast to `Field`, and the result has type `Field`. (If *n-1* is greater than the maximum field value, the behavior of the compiler is currently unspecified.) For arithmetic operations with `Uint` result types, it is a static error if the result's bound would be greater than the [maximum unsigned integer, if any](#implementation-specific-limits). Evaluating an arithmetic expression *e1 op e2* involves first evaluating *e1*, then evaluating *e2*. Integer addition, subtraction, or multiplication is then used on the operand values. The overflow and underflow behavior differs for `Field` (either operand has type `Field`) and `Uint` operations (both operands have a `Uint` type): * `Field` arithmetic overflow and underflow wraps around 0; that is, the result of an arithmetic operation whose result is a `Field` is the actual arithmetic value modulo *k*, where *k* is one more than the [maximum field value](#implementation-specific-limits). * `Uint` addition and multiplication cannot overflow: the static type of the result is always large enough to hold the result value. * `Uint` subtraction results in a dynamic error if the resulting value would be negative, i.e., if the value of *e2* is greater the value of *e1*. If the type of either operand is a structural type alias for a `Field` or `Uint` it is treated identically to that `Field` or `Uint`, both in type checking and evaluation. On the other hand, if the type of either operand is a nominal type alias *T* for a `Field` or a `Uint`, the type of the other operand must also have type *T*, and the type of the result also has type *T*. Evaluation proceeds as if the two operands had the underlying `Field` or `Uint` type with the value cast back to *T*, which can result in a dynamic error if *T* is a nominal alias for a type `Uint<0..`*n*`>` and the value is not less than *n*. For example: ``` new type Feet = Uint<32>; circuit foo(x: Feet, y: Feet, scale: Uint<32>): Feet { return (x + y) * (scale as Feet); } ``` computes the sum of `x` and `y` multiplied by `scale`. If the value of this computation fits in 32 bits, `foo` returns the value. Otherwise, the enclosing top-level circuit or constructor halts with a message indicating that the cast of the value to `Feet` failed. ### Tuple creation[​](#tuple-creation "Direct link to Tuple creation") New tuple values are created with expressions of the form `[`*tuple-arg*, ⋯, *tuple-arg*`]` where *tuple-arg*, ⋯, *tuple-arg* is a sequence of zero or more comma-separated tuple arguments. A non-empty sequence can have an optional trailing comma. Each tuple argument is either an expression or a *spread*. If a tuple argument is an expression *e* of type *T*, it contributes a single element of type *T* to the new tuple: the value of *e*. If a tuple argument is a spread `... `*e*, where `...` is the literal three dots (elipsis) token and *e* is an expression, the type *T* of *e* must be a tuple type, a Vector type, or a Bytes type. If *T* is a tuple type `[`*U1*, ⋯, *Un*`]`, the spread contributes *n* new elements of types *U1*, ⋯, *Un* to the new tuple, i.e., the elements of the tuple value of *e*. If *T* is a Vector type `Vector<`*n*, *U*`>`, the spread contributes *n* new elements of type *U* to the new tuple, i.e., the elements of the Vector value of *e*. If *T* is a Bytes type `Bytes<`*n*`>`, the spread contributes *n* new elements of type `Uint<8>` to the new tuple, i.e., the elements of the byte-vector value of *e*. If *T* is neither a tuple type, a Vector type, nor a Bytes type, it is a static error. The type of a tuple-creation expression is the tuple type whose elements are the types contributed by each of the tuple arguments in order. A tuple-creation expression is evaluated by evaluating the tuple arguments from left to right and creating a new tuple whose elements are the values contributed by each of the tuple arguments in order. The length of the new tuple is the total number of contributed elements, which can be less than or greater than number of tuple arguments. ### Byte-vector creation[​](#byte-vector-creation "Direct link to Byte-vector creation") New byte vectors are created with expressions of the form `Bytes [`*tuple-arg*, ⋯, *tuple-arg*`]`. Bytes creation is essentially the same as [tuple creation](#tuple-creation) except that the types of the contributed elements must all be subtypes of `Uint<8>` (if not, it is a static error), and the result is a new byte vector of type `Bytes<`*n*`>` where *n* is the number of contributed elements. ### Tuple, vector, and byte-vector references[​](#tuple-vector-and-byte-vector-references "Direct link to Tuple, vector, and byte-vector references") Compact allows references to individual elements of sequence values (tuples, vectors, and byte vectors) via the syntax *e*`[`*index*`]` where *e* is an expression and *index* is a numeric literal, generic natural-number parameter reference, or an expression that can be reduced to a numeric constant at compile time as described below. The type of *e* must be a sequence type, i.e., a tuple type, a vector type, or a Bytes type. The type of *index* must be `Uint<`*n*`>` for any *n*. The eventual constant value of *index* must be less than the length of the sequence value as determined by its type. Violating any of these constraints is a static error. The unsigned integer value of *index* must be computable at compile time via the following rules, or it is a static error. * Any *index* can be a constant, i.e., a numeric literal or a generic natural-number parameter reference. * If the type of *e* is a tuple type that [has a vector type](#subtyping-and-least-upper-bounds), the rule for vector types below applies, with *e* treated as having the vector type. If the type of *e* is a tuple type that does not have a vector type, however, *index* must be a constant. This restriction allows the compiler to compute a type for tuple reference expressions without first attempting to reduce *index* to a numeric value. * If the type of *e* is a vector or byte-vector type, *index* must be a *constant-valued* expression, where a constant-valued expression is: * a constant, * a reference to a generic natural-number parameter, * a reference to a variable bound to a constant-valued expression, * a reference to a variable bound in the header of a `for` loop, or * the result of adding, subtracting, or multiplying two constant-valued expressions. The type of a byte-vector reference is `Uint<8>`. The type of a vector reference where the vector has element type *T* is *T*. The type of a tuple reference where the tuple has type `[`*T1*, ⋯, *Tn*`]` and *index* is the constant *i* or the value *i* of a generic natural-number parameter is *Ti*. Otherwise, the tuple type must have a vector type `Vector<`*n*, *T*`>` and the type of the tuple reference is *T*. The value of a sequence reference is the value of the *ith* (zero-based) element of the result of evaluating *e*, where *i* is the (eventually) compile-time constant value of *index*. ### Tuple, vector, and byte-vector slices[​](#tuple-vector-and-byte-vector-slices "Direct link to Tuple, vector, and byte-vector slices") *Slicing* a sequence value such as a tuple, vector or byte vector produces a subsequence of the original value. It is similar to a sequence reference but extracts a sequence of values rather than a single value from the sequence value. Slice expressions take the form `slice<`*k*`>(`*e*, *index*`)`, where `slice` is a keyword, *k* is a constant or numeric generic parameter reference specifying the fixed size of the slice, *e* is an expression, and *index* is a numeric literal, a generic natural-number parameter reference, or an expression that can be reduced to a numeric constant at compile time as described above in the section on [sequence references](#tuple-vector-and-byte-vector-references). It is a static error if *index* + *k* exceeds the length of the sequence value. The type of a byte-vector slice is `Bytes<`*k*`>`. The type of a vector slice where the vector has element type *T* is `Vector<`*k*, *T*`>`. The type of a tuple slice where the tuple has type `[`*T1*, ⋯, *Tn*`]` and *index* is the constant *i* or the value *i* of a generic natural-number parameter is the subsequence `[`*Ti*, ⋯, *Tj*`]` starting with element *i* (zero-based) and ending with element *j=i+k-1* of `[`*T1*, ⋯, *Tn*`]`. Otherwise, the tuple type must [have a vector type](#subtyping-and-least-upper-bounds) `Vector<`*n*, *T*`>` and the type of the slice is `Vector<`*k*, *T*`>`. The value of a `slice` expression `slice<`*k*`>(`*e*, *index*`)` is the subsequence of the original tuple, vector, or byte vector from *i* (zero-based, inclusive) through *i+k* (zero-based, exclusive) of the result of evaluating *e*, where *i* is the (eventually) compile-time constant value of *index*. For example, if `getMiddle` is defined as follows: ``` export circuit getMiddle(x: Bytes<5>): Bytes<3> { return slice<3>(x, 1); } ``` The call ``` getMiddle(Bytes[17, 18, 19, 20, 21]) ``` evaluates to the equivalent of ``` Bytes[18, 19, 20] ``` ### Structure creation[​](#structure-creation "Direct link to Structure creation") Structure values are created with structure-creation expressions of the form *T* `{`*struct-arg*, ⋯, *struct-arg*`}`, where *T* is a structure type name *S* or specialized generic structure type *S*`<`*garg*, ⋯, *garg*`>`, and *struct-arg*, ⋯, *struct-arg* is a sequence of zero or more comma-separated structure arguments. A structure argument can be one of three things: * a **positional** argument, which takes the form of an expression *e*, * a **named** argument, which takes the form *id*`:` *e*, where *id* is a field name and *e* is an expression, or * a **spread** argument, which takes the form `...`*e*, where `...` is the literal three dots (ellipsis) token and *e* is an expression. The sequence of structure arguments within a structure-creation expression can consist either of: * zero or more positional arguments followed by zero or more named arguments, or * a spread argument followed by zero or more named arguments. In the first case, the values of the *n* positional arguments become the values of the first *n* fields of the created structure and must be given in the same order as the fields in the structure declaration. The named elements specify the values of the remaining fields by name; that is, the value of *e* in the named argument *id*`:` *e* becomes the value of the field named *id*. In the second case, the expression *e* in the spread argument `...`*e* must have the same structure type *T* as the one being created, and each field of the created structure is given the value of the corresponding field from the value of *e* if not overridden by one of the named arguments. Named arguments need not appear in any particular order. It is possible for only positional or only named arguments to be present. It is also possible, though not useful, for only a spread argument to be present. The examples below demonstrate the use of positional and spread field values: ``` struct S { a: Uint<32>, b: Boolean, c: Bytes<8> } circuit f(x: Uint<32>, y: Boolean, z: Bytes<8>): S { const s1 = S { c: z, a: x, b: y }; // Alternatively, s1 can be created with the positional syntax S { x, y, z } // or a mix of positional and named field values S { x, c: z, b: y }. const s2 = S { ...s1, b: true }; // s2 is created using the spread syntax. So, s2 has the same field values // as s1 except that b is true. const s3 = S { ...s2, c: 'abcdefgh' }; // s3 is also created using the spread syntax. s3 has the same field values // as s2 except that c is 'abcdefgh'. return s3; } ``` The structure type name must be bound to a structure type in scope. If the structure is generic, it must be fully specialized with generic arguments enclosed in angle brackets. The static type of a non-generic structure-creation expression is the named structure type, while the static type of a generic structure-creation expression is a structure with the same name as the generic type and field types obtained by substituting the generic arguments for the generic parameters in the structure's declaration. **If a spread argument is not present:** The number of structure arguments must match the number of fields in the corresponding structure declaration: a value must be given for every field. Positional arguments must appear before named arguments. A field name must not occur more than once among the named arguments, and each field name that does occur must be the name of a field in the corresponding structure declaration whose value is not given positionally. The type of a positional field subexpression must be a subtype of the declared type of the (positionally) corresponding field in the structure declaration. Similarly, the type of a named field subexpression must be a subtype of the declared type of the corresponding (named) field in the structure declaration. **If a spread argument is present:** The spread argument must come first in the sequence of structure arguments. The type of the spread subexpression must be the same as the structure to be created. There must not be any positional arguments. A field name must not occur more than once among the named arguments, and each field name that does occur must be the name of a field in the corresponding structure declaration. The type of a named field subexpression must be a subtype of the declared type of the corresponding (named) field in the structure declaration. Violating any of the above constraints is a static error. A structure-creation expression is evaluated by evaluating the structure argument expressions in order from left to right and constructing a structure value whose fields values are based on the corresponding structure arguments: if there is a positional or named argument for a field, the field's value is the value of the expression, otherwise there must be a spread argument and the field's value is the value of the corresponding field in the (structure) value of the spread expression. ### Structure field access[​](#structure-field-access "Direct link to Structure field access") A structure field access is an expression of the form *e*`.`*id* where *e* is an expression with a structure type *T* and *id* is an identifier. It is a static error if *T* does not have a field named *id*. The type of any structure field access *e*`.`*id* where *e* has type *T* is the type of the *id* field of *T*. The value of any structure field access *e*`.`*id* is the result of evaluating the subexpression *e* and extracting the value of the resulting structure's *id* field. Some expressions of the form *e*`.`*id* can also be [enumeration member selection](#enumeration-member-selection) or [ledger-state operations](#ledger-state-operations). *e*`.`*id* is recognized as a structure field access only when the type of *e* is a structure type. ### Enumeration member selection[​](#enumeration-member-selection "Direct link to Enumeration member selection") An expression of the form *E*`.`*id* where *E* is the name of an enumeration type and *id* is an identifier is an enumeration member selection. It is a static error if *E* does not have a member named *id*. The type of any enumeration member selection *E*`.`*id* is *E*. *E*`.`*id* is a constant. That is, the value of any enumeration member selection *E*`.`*id* is *E*`.`*id*. Some expressions of the form *E*`.`*id* can also be [structure field accesses](#structure-field-access) or [ledger-state operations](#ledger-state-operations). *E*`.`*id* is recognized as an enumeration member selection only when the type of *e* is an enumeration type. ### Circuit and witness calls[​](#circuit-and-witness-calls "Direct link to Circuit and witness calls") Circuits and witnesses, collectively referred to as functions, are called via expressions of the form *fun*`(`*e*, ⋯, *e*`)`, where *fun* is a function expression and *e*, ⋯, *e* is a sequence of zero or more comma-separated argument expressions. The function expression *fun* can take one of the following forms: | | | | | ---------------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------- | | *fun* | ⟶ | [*id*](#terminal-names) [*gargs*](#generic-parameters-and-arguments)opt | | | \| | [*arrow-parameter-list*](#circuit-and-witness-calls) [*return-type*](#circuit-and-witness-calls)opt `=>` [*block*](#blocks) | | | \| | [*arrow-parameter-list*](#circuit-and-witness-calls) [*return-type*](#circuit-and-witness-calls)opt `=>` [*expr*](#syntax-of-expressions) | | | \| | `(` [*fun*](#circuit-and-witness-calls) `)` | | *arrow-parameter-list* | ⟶ | `(` [*optionally-typed-pattern*](#const-statements) `,` ⋯ `,` [*optionally-typed-pattern*](#const-statements) `,`opt `)` | | *return-type* | ⟶ | `:` [*type*](#primitive-types) | In the simplest form, *fun* is just a identifier *id* referring to a witness or named circuit. When *id* refers to a generic witness or circuit, it must be fully specialized via generic parameters. *fun* can also be an *anonymous circuit*, also known as an *arrow circuit*. This form consists of a parameter list `(`*optionally-typed-pattern*, ⋯, *optionally-typed-pattern*`)` followed by an optional return type `:` *type*, an arrow (`=>`), and a body, which can be a *block* or an *expr*. Each *optionally-typed-pattern* is a [pattern](#patterns-and-destructuring) with an optional type annotation `:` *type*. Finally, *fun* can be a parenthesized function `(`*fun*`)`. Because circuits and witnesses are not first class, *fun* cannot be a variable name or arbitrary expression. Anonymous circuits cannot have generic parameters. Since they appear only in contexts where they are directly called, the circuit would have to be immediately specialized, in which case only one specialization can exist and the non-generic version would be clearer. The *underlying function* of a function expression is a non-parenthesized function expression. For a function name it is the function name, for an anonymous circuit it is the anonymous circuit, and for a parenthesized function it is the underlying function of the parenthesized function expression. Type checking a function call depends on the form of the underlying function. * **For a named function:** Function names may be *overloaded*: more than one function of the same name may be present in the scope of a call to that function. A call whose underlying function is a name can thus have zero or more candidate functions, i.e., all of those that have the given name and are present in the scope of the call. A candidate function is not necessarily compatible with the number and kinds of the generic parameter values nor with the number and types of the argument expressions provided at the call site. It is compatible if and only if the number of generic parameters is the same as the number of generic arguments, each generic argument is of the required kind (numeric or type), the number of declared parameters is the same as the number of argument expressions, and the type of each argument is a subtype of the declared type of the corresponding parameter. If exactly one candidate is compatible, the call is made to that candidate. It is a static error if there is not exactly one compatible candidate. The static type of a call to a named function is the declared return type of the called function. * **For an anonymous circuit:** Parameters are type-checked or inferred as follows: * If there is a type annotation for a parameter, it is a static error if the type of the corresponding argument expression is not a subtype of the type annotation. * If there is no type annotation for a parameter, the parameter's type is inferred as the type of the corresponding argument expression. Within the body of the anonymous circuit, the type of each variable binding arising from the binding of identifiers in each parameter pattern to the corresponding pieces of the corresponding argument is the type of the corresponding part of the structure of the declared or inferred parameter type. If there is a return-type annotation, it is a static error if the body can return a type of value that is not a subtype of the return-type annotation. A return statement of the form `return;` implicitly returns a value of type `[]`, as does every control flow path through a body that does not explicitly end with a return statement. If there is no return-type annotation, then a return type is inferred from the body as the least upper bound of the types of the values that can be returned from the body (explicitly or implicitly). It is a static error if these types do not have a least upper bound. The static type of a call to an anonymous circuit is the declared or inferred return type. Calls are evaluated by evaluating the argument expressions in order from left to right. Then, if a circuit is being called, the statements in the body of the circuit are executed with the parameter names bound to the corresponding argument values. The value of a circuit call is the value returned from the execution of the body. If a witness is being called, the contract invokes the externally provided witness function with the argument values. The value of a witness call is the value returned by the witness function. ### Cross-contract calls[​](#cross-contract-calls "Direct link to Cross-contract calls") The circuits named in contract types can be called through references to contract values, in expressions of the form *E*`.`*id*`(`*e*, ⋯, *e*`)`, where * *E* is an expression whose value has a contract type *T*, * *id* is one of the circuit names declared in *T*, and * *e*, ⋯, *e* is a comma-separated sequence of zero or more argument expressions. For example, using the `Adder` type defined in [the section describing contract types](#contract-types), a cross-contract call to the `setAddAmount` circuit could look like this: ``` export circuit setUpDoubleAdd(a: Adder, n: Uint<64>): [] { a.setAddAmount(n + n); } ``` Cross-contract calls cannot have generic parameters, because the declarations of circuits in contract types cannot be generic. Type checking a cross-contract call involves verifying that the circuit named in the call is one of the circuits named in *T* and verifying that the named circuit is compatible with number and types of the argument expressions. The number of argument expressions must be the same as the number of declared parameters for *id*, and the type of each argument must be a subtype of the declared type of the corresponding parameter. It is a static error if if *id* is not the name of a circuit in *T* or if the sequence of argument eqpressions is not compactible with the declaration of *id* in *T*. The static type of a cross-contract call is the declared return type of *id* in *T*. Current limitations on cross-contract calls When computing the set of exported circuits for the purpose of determining whether a contract satisfies a contract type, the current compiler eliminates from consideration any circuits that call witnesses. A called contract may define witness functions, and they may be called by other circuits, but they cannot be called directly or indirectly by the exported circuits that satisfy a contract type. This implies that every cross-contract call is to a circuit whose only access to private data is through the values given as its arguments. Furthermore, the current implementation of cross-contract calls provides no means of discovering any code for called circuits, other than the code provided by the calling application. The code that is generated at the site of a call to one of `T`'s circuits expects to find the implementation of those circuits in the JavaScript file `../T/contract/index.js`. This effectively limits any DApp to a single implementation of each contract type. What this generally means is that an application provides circuits that satisfy a contract type `T` by compiling a contract defined in `T.compact`, and the resulting compilation artifacts are made available alongside those of any callers of `T`'s circuits. The real dependency, however, is not on the source file, but instead on the generated JavaScript file. If any cycles are present in the call graph of cross-contract calls, the behavior is undefined. This implies that contracts cannot implement either direct or indirect recursion using calls through references to contract values. This is a restriction on the *implementation* of contracts. For example, suppose a circuit in `S.compact` makes a cross-contract call to a circuit defined in a contract type `T`. If the application uses an implementation of `T` in which the called circuit itself makes another call to a circuit defined in a contract type `S`, the compiler may reject the program, or the call may fail at execution time in the deployed application. ### Map and fold expressions[​](#map-and-fold-expressions "Direct link to Map and fold expressions") Compact supports expressions that perform the higher-order operations *map* and (left-to-right) *fold* over vectors, tuples that have vector types (not arbitrary tuples), and byte vectors. Map expressions have the form `map(`*fun*, *e*, ⋯¹, *e*`)` where `map` is a keyword, *fun* is a circuit or witness, and each *e* is an expression. The `map` operator creates a vector containing the results of applying *fun* to the corresponding elements of the sequence values of the expressions. Fold expressions have the form `fold(`*fun*, *init*, *e*, ⋯¹, *e*`)` where `fold` is a keyword, *fun* is a circuit or witness, *init* is an expression, and each *e* is an expression. The `fold` operator accumulates a value starting with the value of *init* and updating it by applying *fun* to the current value and the corresponding elements of the sequence values of the expressions in turn. A detailed description of the circuit or witness *fun* is given in [Circuit and witness calls](#circuit-and-witness-calls) above. A map expression is type-checked by checking the type of the witness or circuit *fun* to find its declared or inferred parameter types and its declared or inferred return type *R*. *fun* must have at least one parameter, and the map expression must have the same number of sequence-value subexpressions as the number of parameters of *fun*. Each of the sequence-value subexpressions must have a vector or byte-vector type, and all these types must have the same length *n*. If the type of the *ith* parameter to *fun* is *T*, then the *ith* sequence-value subexpression must have the vector type `Vector<`*n*, *S*`>` where *S* is a subtype of *T*, or it must be the byte-vector type `Bytes<`*n*`>` and `Uint<8>` must be a subtype of *T*. The type of the `map` expression is `Vector<`*n*, *R*`>`; `map` produces a vector regardless of whether the input sequence-value subexpressions are vectors, tuples, byte vectors, or some combination. A fold expression is type-checked by checking the type of the witness or circuit *fun* to find its parameter types and its return type *R*. *fun* must have at least two parameters, and the type of the first parameter must be the same type as the return type *R*. The fold expression must have one fewer sequence-value subexpression than the number of parameters of *fun*. The first subexpression *init* gives the initial value for the fold. It must have a type which is a subtype *R*. Each of the sequence-value subexpressions must have a vector or byte-vector type, and all these types must have the same length *n*. If the type of parameter *i*+1 of *fun* is *T*, then the type of the *ith* sequence-value subexpression must have the vector type `Vector<`*n*, *S*`>` where *S* is a subtype of *T*, or it must be the byte-vector type `Bytes<`*n*`>` and `Uint<8>` must be a subtype of *T*. The type of the entire expression is *R*. Map expressions are evaluated by evaluating the sequence-value subexpressions from left to right to produce the input sequence values. The witness or circuit *fun* is then applied in turn, from index 0 up to index *n*-1, to arguments taken from the input sequence values. The result is a vector of length *n* where each *ith* element is the result of applying *fun* to the *ith* elements of the corresponding input sequence values. Fold expressions are evaluated by evaluating the initial value expression *init* and then evaluating the sequence-value subexpressions from left to right. The values of the sequence-value expressions are the input sequence values. The witness or circuit *fun* is then applied in turn, from index 0 up to index *n*-1, to an accumulator value argument and arguments taken from the input sequence values. The 0th (initial) accumulator value is the value of the expression *init*, and each subsequent *i+1th* accumulator value is the result of applying *fun* to the *ith* accumulator value and to the *ith* elements of the corresponding input sequence values. The result is the *nth* (final) accumulator value where *n* is the length of the input vectors. ### Type cast expressions[​](#type-cast-expressions "Direct link to Type cast expressions") Values of one type can be cast to another, when allowed, via a *cast*, which takes the form *e* `as` *T* where *e* is an expression and *T* is a type. The effects of casting an expression *e* of type *T* to another type *U* depend on the specific types involved. For some types *T* and *U*, the cast is not allowed, which is a static error. Even if the cast is allowed, some values of type *T* might not be representable as values of type *U*. In such cases, a run-time check of the value of *e* is required and can result in a dynamic error. In cases where the run-time representation of *T* is different from the run-time representation of *U*, the value of *e* must be converted at run time from the one representation to the other. The type of any (allowed) cast *e* `as` *T* is, naturally, *T*. Evaluation of a cast proceeds by evaluation of its subexpression, followed by any checks and conversions required by the cast. If a check fails, a dynamic error is reported. TypeScript casts of the form `<`*T*`>`*e* are not supported in Compact. The following rules govern when casts are allowed, when casts might cause dynamic errors, and when casts might require run-time conversions. Any cast not covered by one of the rules is not allowed. #### Upcasts[​](#upcasts "Direct link to Upcasts") * Upcasts, i.e., casts from a type to a [supertype](#subtyping-and-least-upper-bounds) (e.g., from `Vector<3, Uint<8>>` to `Vector<3, Uint<16>>`), are always allowed, never result in dynamic errors, and, except in the case where the type and the supertype are the same, might require run-time conversions. Upcasts are never required: it is always possible to use a value of type *T* as a value of a supertype of *T*. This rule is straightforward, but some implications regarding tuple and vector types are worth noting: * Since `Vector<`*n*, *T*`>` is the same type as `[`*T*, ⋯, *T*`]` of length *n*, a cast from either of these types to the other is allowed but not required. * If a tuple type `[`*T1*, ⋯, *Tn*`]` [has a vector type](#subtyping-and-least-upper-bounds) `Vector<`*n*, *S*`>`, then since the tuple type is a subtype of the vector type, a cast from the tuple type to the vector type is allowed but not required. For example, values of type `[Uint<8>, Uint<16>]` can be used where values of type `Vector<2, Uint<16>>` are required. * Since a vector type `Vector<`*n*, *T*`>` is a subtype of any tuple type `[`*S1*, ⋯, *Sn*`]` where *T* is a subtype of each *S*, a cast from the vector type to the tuple type is allowed but not required. For example, values of type `Vector<2, Uint<8>>` can be used where values of type `[Uint<8>, Uint<16>]` are required. #### Downcasts of `Field` and `Uint` types[​](#downcasts-of-field-and-uint-types "Direct link to downcasts-of-field-and-uint-types") * Any `Uint` downcast, i.e., any cast from `Uint<0..`*m*`>` to `Uint<0..`*n*`>`, *m* > *n*, is allowed, requires a run-time check, and might require a run-time conversion. The same applies to any `Field` to `Uint` casts where the maximum `Field` value exceeds the maximum value of the `Uint` type. (If the maximum value of the `Uint` type exceeds the maximum `Field` value, the behavior of the compiler is currently unspecified.) #### Casts of `Boolean` to and from `Field` and `Uint`[​](#casts-of-boolean-to-and-from-field-and-uint "Direct link to casts-of-boolean-to-and-from-field-and-uint") * Any cast from `Boolean` to `Field` or any `Uint` type is allowed, sometimes requires a run-time check, and requires a run-time conversion (of `false` to `0` and `true` to `1`). A run-time check is required for `Uint<0..1>`. * Any casts from `Field` or any `Uint` type to `Boolean` is allowed, cannot result in a dynamic error, and requires a simple run-time conversion (of `0` to `false` and any other value to `true`). #### Casts of Enum types to and from `Field` and `Uint`[​](#casts-of-enum-types-to-and-from-field-and-uint "Direct link to casts-of-enum-types-to-and-from-field-and-uint") * Any cast from an enum type to `Field` or any `Uint` type is allowed, sometimes requires a run-time check, and might require a run-time conversion. A run-time check is required for a cast from an enum type with *n* elements to `Uint<0..`*m*`>`, *n* > *m*. * Any cast from `Field` or any `Uint` type to an enum type is allowed, sometimes requires a run-time check, and might require a run-time conversion. A run-time check is required for casts from `Field`. For an enum type with *n* elements, a run-type check is required for casts from `Uint<0..`*m*`>`, *m* > *n*. #### Casts of `Bytes` to and from `Field` and `Uint`[​](#casts-of-bytes-to-and-from-field-and-uint "Direct link to casts-of-bytes-to-and-from-field-and-uint") * Any cast from `Bytes<`*m*`>`, *m* != 0, to `Field` or any `Uint` type is allowed, requires a run-time check, and requires a run-time conversion. That is, the byte-vector value of the expression is converted into a `Field` or `Uint` value with the least-significant byte of the result corresponding to the first byte in the byte vector. A dynamic error occurs if the result exceeds the maximum value of the `Field` or `Uint` type. * Any cast from `Field` or any `Uint` type to `Bytes<`*m*`>`, *m* != 0, is allowed, requires a run-time check, and requires a run-time conversion. That is, the integer value of the expression is converted into a byte vector with the first byte of the byte vector corresponding to the least-significant byte of the integer. A dynamic error occurs if the result does not fit in *m* bytes. #### Casts of `Bytes` to and from `Vector` and tuple types[​](#casts-of-bytes-to-and-from-vector-and-tuple-types "Direct link to casts-of-bytes-to-and-from-vector-and-tuple-types") * Any cast from `Bytes<`*m*`>` to `Vector<`*m*, `Field>` or `Vector<`*m*, `Uint<0..`*k*`>>`, *k* ≥ 256 is allowed, cannot cause a dynamic error, but does require a run-time conversion. * Any cast from `Bytes<`*m*`>` to tuple type `[`*T1*, ⋯, *Tm*`]`, where each *Ti* is `Field` or `Uint<0..`*k*`>` for some *k* ≥ 256 is allowed, cannot cause a dynamic error, but does require a run-time conversion. * Any cast from `Vector<`*m*, `Uint<0..`*k*`>>`, *k* ≤ 256, to `Bytes<`*m*`>` is allowed, cannot cause a dynamic error, but does require a run-time conversion. * Any cast from tuple type `[`*T1*, ⋯, *Tm*`]` to `Bytes<`*m*`>`, where each *Ti* is `Uint<0..`*k*`>` for some *k* ≤ 256 is allowed, cannot cause a dynamic error, but does require a run-time conversion. ### Ledger state operations[​](#ledger-state-operations "Direct link to Ledger state operations") A Compact program interacts with its public state by invoking operations upon the ledger. There are two different forms of ledger operations. **Kernel operations** are operations that do not depend on specific ledger state. They can be invoked by expressions of the form *id*`.`*op*`(`*e*, ⋯, *e*`)`, where *id* is the name of a ledger field declared to have the special ledger-state type `Kernel`, *op* is the name of a builtin kernel operation, and *e*, ⋯, *e* is a comma-separated sequence of zero or more argument expressions. The `CompactStandardLibrary` predefines the ledger field name `kernel` to have ledger-state type `Kernel`, so for example, the built-in `self` operation can be called from a circuit as follows: ``` import CompactStandardLibrary; circuit f(): ContractAddress { return kernel.self(); } ``` The static type of a kernel operation expression is the return type of the corresponding kernel operation according to the the Compact [ledger data type documentation](/compact/reference/ledger-adt.md). Kernel operations are evaluated by evaluating the argument subexpressions in order from left to right and then invoking the corresponding kernel operation with the argument values. **Ledger-state operations** are operations on the contract's declared public ledger-state. In its simplest form, a ledger-state operation is an expression *F*`.`*op*`(`*e*, ⋯, *e*`)`, where *F* is a ledger field name [declared via a `ledger` field declaration](#declaring-and-maintaining-public-state), *op* is the name of a ledger-state operator, and each *e* is an argument expression. *F* can also be another ledger-state operation, allowing ledger-state operations to be chained when the result of a ledger-state operation might itself have a ledger-state type. Compact also supports shorthands for certain ledger-state operations; these are described below in [Ledger-state-operation shorthands](#ledger-state-operation-shorthands). The static type of a ledger-state operation is the return type of the corresponding ledger-state operation according to the the Compact [ledger data type documentation](/compact/reference/ledger-adt.md). This might be a Compact type or it might be a ledger-state type. A ledger-state operation whose return type is a ledger-state type *must* be chained, i.e., immediately subject to another ledger-state operation. It is a static error if this is not the case. A ledger-state operation *F*`.`*op*`(`*e*, ⋯, *e*`)` is evaluated by evaluating *F* if *F* is itself a ledger-state operation, then evaluating the argument subexpressions from left to right, and then invoking the operation *op* with the argument values on the portion of the public ledger state identified by *F*. ### Ledger-state-operation shorthands[​](#ledger-state-operation-shorthands "Direct link to Ledger-state-operation shorthands") Compact supports several shorthands for common ledger-state operations. The simplest of these is a shorthand for the ledger-state operation *F*`.read()` where *F* is a ledger-state field name or itself another ledger-state operation. If the type of *F* is a ledger-state type that supports the `read` operation, *F*`.read()` can be abbreviated, simply, to *F*. The other shorthands all take the form of assignment statements and abbreviate the ledger operations *F*`.write(`*e*`)`, *F*`.increment(`*e*`)`, and `F.decrement(`*e*`)`, where *e* is an expression. If the type of *F* is a ledger-state type that supports the `write` operation, *F*`.write(`*e*`)` can be abbreviated *F* `=` *e*. Similarly, if the type of *F* is a ledger-state type that supports the `increment` operation, *F*`.increment(`*e*`)` can be abbreviated *F* `+=` *e*, and if the type of *F* is a ledger-state type that supports the `decrement` operation, *F*`.decrement(`*e*`)` can be abbreviated *F* `-=` *e*. The typing and evaluation rules for the abbreviations are identical to expressions they abbreviate. ### Asserts[​](#asserts "Direct link to Asserts") An assertion has the form `assert(`*e*, *msg*`)` where *e* is an expression and *msg* is a string message. *e* must have a Boolean type, otherwise it is a static error. The type of every `assert` form is `[]`. Evaluation proceeds by evaluating *e*. If the value of *e* is true (the assertion succeeds), the `assert` form produces the value `[]`. If, however, the value of *e* is false (the assertion fails), it is a dynamic error, i.e., the `assert` form halts computation of the enclosing top-level circuit or constructor with the message *msg*. Each assertion is checked at run time and constrained in-circuit. ### Emitting events[​](#emitting-events "Direct link to Emitting events") Events are emitted via the form `emit(`*e*`)` where *e* is an expression whose type is a standard event type. [The Compact standard library](/compact/reference/compact-standard-library) provides detailed descriptions of the standard event types. The type of every `emit` form is `[]`. An attempt to `emit` the value of an expression that does not have a standard event type is a static error. An attempt to `emit` an event, directly or indirectly, via the contract constructor is a static error. Evaluation of `emit(`*e*`)` proceeds by evaluating *e*, computing its canonical byte encoding, and emitting a structured `VersionedLogItem` with three fields: * `version`, the event format version (presently `1`), * `eventType`, identifying the declared event type by its tag, and * `data`, containing the byte encoding. The canonical byte encoding of an event is created via the equivalent of `serialize<`*T*`, #`*n*`>`. A generic `serialize` circuit is defined in the Compact standard library along with a `deserialize` counterpart. While events are serialized implictly via `emit`, they must be deserialized explicitly via a call to `deserialize`. For example, in the code below, the circuit `deserializeShieldedSpend` can be used to decode events emitted by `spend`. ``` import CompactStandardLibrary; export circuit spend(n: Bytes<32>): [] { emit(ShieldedSpend { nullifier: disclose(n) }); } export circuit deserializeShieldedSpend(x: Bytes<32>): ShieldedSpend { return deserialize(x); } ``` The emitted item is appended, in order of evaluation, to the events list of the enclosing exported circuit's context, where it can be read from TypeScript via the `events` field of `CircuitContext` (see [Interacting with Compact from TypeScript](#interacting-with-compact-from-typescript)). ### Explicit disclosure[​](#explicit-disclosure "Direct link to Explicit disclosure") Private data can enter a Compact contract via the arguments to exported circuits and via the return values of witnesses. Compact supports *selective disclosure*, in which the contract decides which private data, if any, should be disclosed in the transcripts and public state of the contract, and how that private data should be encoded. Compact itself has no information about the nature of any private data and whether and how it is necessary to disclose it, the decision to do so rests with the contract developer. Compact does, however, require that such disclosure be explicitly declared to prevent unintentional disclosure, so that privacy is the default and disclosure is the exception. The mechanism for explicitly declaring disclosure is simple: disclosure of private data (exported circuit arguments, witness return values, and anything derived from private data) must be acknowledged by wrapping an expression whose value contains private data in a `disclose()` wrapper before storing it in the public state, returning it from an exported circuit, or using it in conditional expressions that might affect what is stored in the public state or returned from an exported circuit. For example, the following contract attempts to disclose private data without explicitly declaring the disclosure when it stores the value of the exported parameter `x` into the ledger field `F`: ``` ledger F: Uint<16>; export circuit setf(x: Uint<16>): [] { F = x; } ``` Compiling this program produces the following error message in Version 1.0 of the Compact compiler: ``` Exception: testfile.compact line 3 char 5: potential witness-value disclosure must be declared but is not: witness value potentially disclosed: the value of parameter x of exported circuit setf at line 2 char 21 nature of the disclosure: ledger operation might disclose the witness value via this path through the program: the right-hand side of = at line 3 char 5 ``` The remedy in this case is simple: wrap the reference to `x` in a `disclose()` wrapper. ``` ledger F: Uint<16>; export circuit setf(x: Uint<16>): [] { F = disclose(x); } ``` The `disclose()` wrapper does not cause disclosure in itself; in fact, it has no effect other than telling the compiler that it is okay to disclose the value of the wrapped expression. Equivalently, it tells the compiler to pretend that the value of the wrapped expression does not contain witness data whether it actually does or not. The compiler works hard to ensure there are no false alarms and also to provide precise and accurate information about the nature of the disclosure and how it occurs. Often, the same value is disclosed along different paths, and the nature of the disclosure might be more obscure, particularly if it involves indirect disclosure via conditional expressions. Detailed advice about how to understand and remedy disclosures is beyond the scope of this document, but a few things are worth noting: * It is often sufficient to correct first disclosure issue reported at a given disclosure if multiple disclosures are listed. * Whenever feasible, the `disclose()` wrapper should be placed as close to the actual disclosure site as possible. * When disclosing a hashed or otherwise obfuscated variant of witness data, place the disclosure somewhere on the path between input and disclosure *after* the obfuscation to help prevent disclosure of the unobfuscated input. * When calling a circuit in another contract (i.e., making a cross-contract call using a reference to a value with a contract type), if the called circuit is not declared to be `pure` in the contract type, the call's arguments must be explicitly disclosed somewhere along the path to the call, because the called circuit might make its arguments publicly visible. The contract reference itself must also be explicitly disclosed, because a cross-contract call reveals the address of the called contract. More details are given in [Explicit Disclosure in Compact: The Midnight "Witness Protection Program"](/compact/reference/explicit-disclosure.md). ## Interacting with Compact from TypeScript[​](#interacting-with-compact-from-typescript "Direct link to Interacting with Compact from TypeScript") This section discusses how TypeScript-coded DApps can interact with contracts written in Compact. The first subsection discusses the artifacts generated by the compiler from a valid Compact program: * A TypeScript equivalent of the Compact source program * Zero-knowledge (zkir) circuits and proving keys * A JSON info file describing the contract's exports The second subsection discusses the structure of the generated TypeScript code, while the third discusses the TypeScript representation of Compact datatypes. ### Products of the compiler[​](#products-of-the-compiler "Direct link to Products of the compiler") When given a well-formed Compact program with no static errors, the Compact compiler generates several artifacts that permit TypeScript-coded DApps to create and interact with instances of Compact contracts. Each of these artifacts is placed into one of four subdirectories of the output directory as described below: * `compiler`: * `contract-info.json`: a JSON-formatted file containing information about the exports of the Compact program. It also contains version information: the compiler version used to compile it, the language version supported by that compiler version, and the runtime version required by the generated code. * `contract`: * `index.d.ts`: a TypeScript definition file describing the exports of the generated TypeScript code * `index.js`: a JavaScript file implementing the export entities * `index.js.map`: a source-map file that relates key elements of the generated JavaScript code back to the Compact source file * `zkir`: * One file *circuit-name*.zkir for each circuit *circuit-name* that requires a proof. Proofs are required for exported circuits that touch (read, write, or update) the public ledger. * One file *circuit-name*.bzkir for each circuit *circuit-name* that requires a proof. These files are not generated if the `--skip-zkir` flag is supplied when running the compiler. * `keys`: * One file *circuit-name*.prover and one file *circuit-name*.verifier for each circuit *circuit-name* that requires a proof. These files are not generated if the `--skip-zkir` flag is supplied when running the compiler. ### Exports of the generated TypeScript code[​](#exports-of-the-generated-typescript-code "Direct link to Exports of the generated TypeScript code") The generated TypeScript code exports a set of type declarations, classes, and objects that allow TypeScript DApps to interact with the contract: * The TypeScript type corresponding to each program-defined type exported from the contract's top level. * A `PureCircuits` type that describes the set of pure circuits exported from the contract's top level. * A `pureCircuits` object of type `PureCircuits` that provides access to the pure circuits as pure functions. * A `Witnesses` type, which describes the types external witnesses must satisfy to instantiate the contract. * A `Circuits` type, which describes the set of all exported circuits. * An `ImpureCircuits` type, which describes the set of impure circuits exported from the contract's top level. * A `ProvableCircuits` type, which describes the set of circuits exported from the contract's top level that have verifier keys (i.e., exported circuits that touch the public ledger). * A class `Contract = Witnesses>`, which provides access to implementations of all circuits exported from the contract's top level as well as a mechanism for creating initial public and private state. * A `Ledger` type and corresponding `ledger` object `ledger(state: runtime.StateValue | runtime.ChargedState): Ledger` that provides accessors for each ledger field that supports the `read` operator and various TypeScript-specific operators that cannot be called from Compact, such as iterators. Instances of the `Contract` class are constructed via `new Contract(w)` where `w` is an instance of `W` and contains one member for each witness expected by the Compact program, namely a TypeScript function that implements the witness. An instance of `Contract` provides access to all of the circuits via the `circuits` member: ``` circuits: Circuits ``` as well as just the impure circuits and just those requiring proofs via: ``` impureCircuits: ImpureCircuits provableCircuits: ProvableCircuits ``` and the initial public and private state via: ``` initialState(context: runtime.ConstructorContext, x: T, ⋯): runtime.ConstructorResult ``` where `x` ⋯ are the contract constructor parameters and `T` ⋯ are the [TypeScript equivalents](#typescript-representation-of-compact-types) of their declared types. Wherever the type parameter `PS` appears, the TypeScript use site should supply the type of the contract's private state. References to `runtime` refer to the `@midnight/compact-runtime` library, which all contracts depend upon and which implements key built-in behaviors. The `runtime` types mentioned here are described in [Compact runtime API](/api-reference/compact-runtime.md). Each circuit exported from a Compact program's top level is implemented by a TypeScript function of the same name and made available via the `circuits` member of the `Contract` class. The TypeScript counterpart of a Compact circuit has one more parameter than the Compact circuit, a *circuit context* parameter that represents the current public and private state, and it returns a *wrapped* value that encapsulates the circuit's return value along with a possibly updated context and information needed to create a transaction. The context parameter has type `runtime.CircuitContext`; it appears first and is followed by the circuit's parameters, whose types are the [TypeScript equivalents](#typescript-representation-of-compact-types) of the declared Compact parameter types. The wrapped return value has type `runtime.CircuitResults`, where `R` is the TypeScript equivalent of the declared Compact return type. Similarly, each witness function provided by TypeScript as part of the `w` parameter of the `Contract` constructor should accept a *witness context* argument of type `runtime.WitnessContext`. This argument comes first, followed by one argument for each of the declared `witness` parameters, each having the TypeScript equivalent of its declared Compact type. The function should return a wrapped value of type `[PS, R]`, where `R` is the TypeScript equivalent of the declared `witness` return value. The context parameter encapsulates the current public and private state, and the wrapped return value encapsulates the witness's return value along with the possibly updated private state. The return value does not encapsulate possibly updated public state because witnesses are not permitted to alter the public state. The context arguments and wrapped return values are used to thread the public and private state into and out of circuits and witnesses, allowing the contract code to be written in a *functional* style that prevents state changes from becoming permanent in the event of an assertion violation or dynamic error. The subset of functions implementing exported impure circuits is also made available via the `impureCircuits` member of the `Contract` class, and the subset of functions requiring proofs is made available via the `provableCircuits` member. Like those made available via the `circuits` member, these also require the additional context argument and return wrapped return values. Functions implementing exported pure circuits are made available via the constant `pureCircuits` object. These functions *do not* require the additional context argument, nor do they return wrapped values: pure circuits do not access public state, and they do not call witnesses, so the TypeScript functions have no need to participate in the threading of public and private state. Functions implementing pure circuits are also available via the `circuits` object; these functions *do* require the additional context argument and return a wrapped return value, though they essentially ignore the context and simply return it unchanged as part of the wrapped return value. This is convenient while debugging a DApp: commenting out the portions of a circuit that make it impure does not prevent the DApp from continuing to access it via the `circuits` object. It is more efficient and usually more convenient, however, for circuits that are intended to be and remain pure to be accessed via the `pureCircuits` object. ### TypeScript representation of Compact types[​](#typescript-representation-of-compact-types "Direct link to TypeScript representation of Compact types") Compact's primitive types are represented in TypeScript/JavaScript as follows: * `Boolean` — `boolean` * `Field` — `bigint`, with run-time bounds checks * `Uint<`*n*`>` or `Uint<0..`*n*`>` — `bigint`, with run-time bounds checks * `Vector<`*n*, *T*`>` — the TypeScript array type *S*`[]`, with run-time length checks, where *S* is the TypeScript representation of type *T* * `[`*T1*, ⋯, *Tn*`]` — the TypeScript tuple type `[`*S1*, ⋯, *Sn*`]` where each *Si* is the TypeScript representation of *Ti* * `Bytes<`*n*`>` — `Uint8Array`, with run-time length checks * `Opaque<"string">` — `string` * `Opaque<"Uint8Array">` — `Uint8Array` Other `Opaque` types are currently not supported. Program-defined types are represented in TypeScript as follows: * `enum` instances — a `number`, with run-time membership checks * `struct` instances with fields *x1*`:` *T1*, ⋯, *xn*`:` *Tn* — an object `{` *x1*`:` *S1*, ⋯, *xn*`:` *Sn* `}` where each *Si* is the TypeScript representation of *Ti* * Type aliases — same as the TypeScript representation of the underying type * `contract` instances — an object `{ bytes: Uint8Array }` representing the contract's address, the same TypeScript representation as the `ContractAddress` struct from the Compact standard library To maintain type safety, the JavaScript code generated by Compact verifies at run time that values passed by an outside caller to an exported circuit or returned from a witness have the expected TypeScript/JavaScript types and, where appropriate, fall within the expected bounds: * `Field` values are limited by a maximum field value. * `Uint` values are limited by the declared bounds. * `Bytes`, `Vector`, and tuple values are limited by their lengths. * Enum values are limited by the maximum index for the enum elements. The generated JavaScript code also verifies that outside callers provide exactly the expected number of arguments to exported circuits. These checks are necessary even when the caller or witness is written in properly typed TypeScript because some Compact types have size and range limits that are not expressible via the TypeScript type system. They are also necessary because compile-time type checks are easily defeated in TypeScript and are nonexistent when a caller or witness is coded in JavaScript. ## Implementation-specific limits[​](#implementation-specific-limits "Direct link to Implementation-specific limits") Compact compiler version 1.0 limits certain datatype values and sizes: * The maximum value of a `Field` value is 52435875175126190479447740508185965837690552500527637822603658699938581184512. This value is dictated by the scalar field size of the ZK proving system. * The maximum value of a `Uint` value is 452312848583266388373324160190187140051835877600158453279131187530910662655. This value is 256k-1 where *k* is the number of bytes (31) that fits in a `Field`. * The maximum length of a vector or byte vector is 16777216. This value is chosen as a reasonable upper bound that helps prevent the compiler from looping indefinitely on programs that operate on excessively large vector and byte-vector types. Consequently, this value dictates the possible range for a `for` loop. These limits may change in future versions of the compiler. ## External resources[​](#external-resources "Direct link to External resources") ### Compact formal grammar[​](#compact-formal-grammar "Direct link to Compact formal grammar") See [here](/compact/reference/compact-grammar.md). ### Compact keywords and reserved words[​](#compact-keywords-and-reserved-words "Direct link to Compact keywords and reserved words") See [here](/compact/reference/compact-keywords.md). ### Compact ledger-state types and operations[​](#compact-ledger-state-types-and-operations "Direct link to Compact ledger-state types and operations") See [here](/compact/reference/ledger-adt.md). ### Runtime API[​](#runtime-api "Direct link to Runtime API") See [here](/api-reference/compact-runtime.md) ### Compiler usage[​](#compiler-usage "Direct link to Compiler usage") See [here](/compact/compilation-and-tooling/compiler-usage.md). ### Explicit disclosure in Compact[​](#explicit-disclosure-in-compact "Direct link to Explicit disclosure in Compact") See [here](/compact/reference/explicit-disclosure.md). ### Writing a contract in Compact[​](#writing-a-contract-in-compact "Direct link to Writing a contract in Compact") See [here](/compact/reference/writing.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Explicit disclosure in Compact: The Midnight "Witness Protection Program" ## Introduction[​](#introduction "Direct link to Introduction") Midnight supports the development of applications that preserve privacy whenever possible while allowing selective disclosure of private information as necessary. Selective disclosure differs from traditional blockchains, in which everything is public, or strict privacy-preserving blockchains, in which everything is private. Midnight's selective disclosure allows banks, for example, to disclose data required for regulatory purposes while keeping other account information private. The decision to disclose private information, including information derived from private information, must rest with each Midnight DApp because disclosure requirements are inherently situation-specific. However, because private information should be disclosed only as necessary, Midnight's Compact language requires disclosure to be explicitly declared. That is, a Compact program must explicitly declare its intention to disclose data that might be private before storing it in the public ledger, returning it from an exported circuit, or passing it to another contract. This makes privacy the default and disclosure an explicit exception, reducing the risk of accidental disclosure. The contract produced from a Compact program is a zero-knowledge (zk) proof coupled with updates to be made to the public ledger. A zk-proof proves some property about one or more pieces of data, referred to as *witnesses* or *witness data*, without disclosing anything about the witness data except that the property holds for them. In Compact, witness data comes primarily from external callback functions declared as witnesses in a Compact contract and provided to the contract by a DApp. Witness data can also come into a contract via exported circuit arguments and via the arguments to the contract constructor, if any. Also, any value derived from witness data is also considered to be witness data. Because witness data may contain private information, it should ordinarily be used only for constructing the zk-proof and not disclosed in any way, but exceptions sometimes need to be made. When exceptions are made, the disclosure must be explicitly declared. ## Explicitly declaring disclosure[​](#explicitly-declaring-disclosure "Direct link to Explicitly declaring disclosure") Explicitly declaring intent to disclose witness data in Compact is straightforward, requiring only the addition of a `disclose()` wrapper around any expression whose value may contain witness data to be disclosed, as illustrated by the following trivial program: ``` import CompactStandardLibrary; witness getBalance(): Bytes<32>; export ledger balance: Bytes<32>; export circuit recordRalance(): [] { balance = disclose(getBalance()); } ``` Without the `disclose()` wrapper, the compiler rejects the program with an informative error message. For example, attempting to compile this Compact program: ``` import CompactStandardLibrary; witness getBalance(): Bytes<32>; export ledger balance: Bytes<32>; export circuit recordBalance(): [] { balance = getBalance(); // missing disclose() wrapper } ``` causes the compiler to abort with the following error message: ``` Exception: /tmp/q3.compact line 6 char 11: potential witness-value disclosure must be declared but is not: witness value potentially disclosed: the return value of witness getBalance at line 2 char 1 nature of the disclosure: ledger operation might disclose the witness value via this path through the program: the right-hand side of = at line 6 char 11 ``` The error message lists the sources of all witness data disclosed at this point, so the programmer knows that adding a `disclose()` wrapper will declare all of them disclosed. Placing a `disclose()` wrapper does not cause disclosure in itself; in fact, it has no effect other than telling the compiler that it is okay to disclose the value of the wrapped expression. Equivalently, it tells the compiler to pretend that the value of the wrapped expression does not contain witness data whether it actually does or not. ## Following indirect witness data assignments[​](#following-indirect-witness-data-assignments "Direct link to Following indirect witness data assignments") In many cases, disclosure is not so direct, yet the requirement to explicitly declare disclosure always holds. For example, obfuscating the disclosure as follows: ``` import CompactStandardLibrary; struct S { x: Field; } witness getBalance(): Bytes<32>; export ledger balance: Bytes<32>; circuit obfuscate(x: Field): Field { // seriously bad obfuscation return x + 73; } export circuit recordBalance(): [] { const s = S { x: getBalance() as Field }; const x = obfuscate(s.x); balance = x as Bytes<32>; } ``` still causes the compiler to abort, with a similar error message: ``` Exception: /tmp/q3.compact line 13 char 11: potential witness-value disclosure must be declared but is not: witness value potentially disclosed: the return value of witness getBalance at line 3 char 1 nature of the disclosure: ledger operation might disclose the result of an addition involving the witness value via this path through the program: the binding of s at line 11 char 3 the argument to obfuscate at line 12 char 13 the computation at line 7 char 10 the binding of x at line 12 char 3 the right-hand side of = at line 13 char 11 ``` In this case, the disclosure, if intentional, can be declared by placing a `disclose()` wrapper around the call to `getBalance()`, around the right-hand-side of the `balance` assignment, or anywhere else along the path from the point of call to the point of disclosure. For example, it could be added to the body of the `obfuscate` circuit around the reference to its argument. ``` import CompactStandardLibrary; struct S { x: Field; } witness getBalance(): Bytes<32>; export ledger balance: Bytes<32>; circuit obfuscate(x: Field): Field { // seriously bad obfuscation return disclose(x) + 73; } export circuit recordBalance(): [] { const s = S { x: getBalance() as Field }; const x = obfuscate(s.x); balance = x as Bytes<32>; } ``` The best practice is most often to put the `disclose()` wrapper as close to the disclosure point as possible to avoid accidental disclosure if the data travels along multiple paths. For a structured value (such as a tuple, vector, or struct), however, the `disclose()` wrapper should be placed only around the portions of the value that are expected to contain witness data to avoid accidental disclosure in the other portions of the value. Also, in the case of a witness that always returns non-private data or private data that has been sufficiently obfuscated via some cryptographically sound mechanism, it makes sense to place the `disclose()` wrapper directly on the call to the witness. ## Indirect disclosure via conditional expression[​](#indirect-disclosure-via-conditional-expression "Direct link to Indirect disclosure via conditional expression") The preceding example illustrates that subjecting witness data to arithmetic, converting it from one representation to another, and passing it into and out of other circuits does not hide potential disclosure from the compiler. The compiler also detects indirect disclosure via conditional expressions. For example: ``` import CompactStandardLibrary; witness getBalance(): Uint<64>; export circuit balanceExceeds(n: Uint<64>): Boolean { return getBalance() > n; } ``` causes the compiler to abort with the following message: ``` Exception: /tmp/q3.compact line 5 char 3: potential witness-value disclosure must be declared but is not: witness value potentially disclosed: the return value of witness getBalance at line 2 char 1 nature of the disclosure: the value returned from exported circuit balanceExceeds might disclose the result of a comparison involving the witness value via this path through the program: the comparison at line 5 char 10 ``` The message aids the programmer by noting the indirect nature of the disclosure. This example also illustrates that disclosure does not occur just when witness data is stored in the ledger but also when returned from an exported circuit. ## Safe Compact standard library routines[​](#safe-compact-standard-library-routines "Direct link to Safe Compact standard library routines") The compiler recognizes that certain Compact standard library routines sufficiently disguise witness data so that explicit declaration of disclosure is not required. For an expression `e` whose value contains witness data, the compiler will treat `transientCommit(e)` as if it does not contain witness data, while it will treat `transientHash(e)` as if it does. ## How explicit disclosure is implemented[​](#how-explicit-disclosure-is-implemented "Direct link to How explicit disclosure is implemented") We refer to the portion of the compiler that detects and reports undeclared disclosure of witness data as the "witness protection program". The witness-protection program is implemented as an *abstract interpreter*, where the abstract values are not actual run-time values but information about witness data that will be contained within the actual run-time values. The abstract interpreter evaluates the program as if the abstract values were actual values. The operations performed by the interpreter are modified, however, to propagate (or not) information about witness data from the operation inputs to the operation outputs. If at some point the interpreter encounters an undeclared disclosure, e.g., a ledger store, of an abstract value containing witness data, the compiler halts and produces an appropriate error message. ## Conclusion[​](#conclusion "Direct link to Conclusion") The `disclose()` wrapper in Compact enforces deliberate programming decisions when dealing with potentially sensitive private witness data and data derived from private information. Explicit disclosure requires Compact program assignments to declare an intention to use data that might be private before storing it in the public ledger, returning it from an exported circuit, or passing it to another contract. This makes privacy the default and disclosure an explicit exception, reducing the risk of accidental disclosure. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Ledger data types Compact language version 0.26.0, compiler version 0.34.0. ## Kernel[​](#kernel "Direct link to Kernel") This ADT is a special ADT defining various built-in operations and valid only as a top-level ADT type. ### balance[​](#balance "Direct link to balance") ``` balance(token_type: Either, Bytes<32>>): Uint<128> ``` Returns the current contract's balance of the unshielded token of the given token type. The balance is not updated during contract execution as a result of unshielded sends and receives. It is always fixed to the value provided at the start of execution. ### balanceGreaterThan[​](#balancegreaterthan "Direct link to balanceGreaterThan") ``` balanceGreaterThan(token_type: Either, Bytes<32>>, amount: Uint<128>): Boolean ``` Checks whether the current balance of the unshielded token of the given type is greater than the given amount. ### balanceLessThan[​](#balancelessthan "Direct link to balanceLessThan") ``` balanceLessThan(token_type: Either, Bytes<32>>, amount: Uint<128>): Boolean ``` Checks whether the current balance of the unshielded token of the given type is less than the given amount. ### blockTimeGreaterThan[​](#blocktimegreaterthan "Direct link to blockTimeGreaterThan") ``` blockTimeGreaterThan(time: Uint<64>): Boolean ``` Checks whether the current block time (measured in seconds since the Unix epoch) is greater than the given amount. ### blockTimeLessThan[​](#blocktimelessthan "Direct link to blockTimeLessThan") ``` blockTimeLessThan(time: Uint<64>): Boolean ``` Checks whether the current block time (measured in seconds since the Unix epoch) is less than the given amount. ### checkpoint[​](#checkpoint "Direct link to checkpoint") ``` checkpoint(): [] ``` Marks all execution up to this point as being a single atomic unit, allowing partial transaction failures to be split across it. ### claimContractCall[​](#claimcontractcall "Direct link to claimContractCall") ``` claimContractCall(addr: Bytes<32>, entry_point: Bytes<32>, comm: Field): [] ``` Require the presence of another contract call in the containing transaction, with a match address, entry point hash, and communication commitment, that is not claimed by any other call. ### claimUnshieldedCoinSpend[​](#claimunshieldedcoinspend "Direct link to claimUnshieldedCoinSpend") ``` claimUnshieldedCoinSpend(token_type: Either, Bytes<32>>, address: Either, amount: Uint<128>): [] ``` Claims an unshielded coin spend - authorizes an unshielded coin of the given token type to be transferred to the given address. ### claimZswapCoinReceive[​](#claimzswapcoinreceive "Direct link to claimZswapCoinReceive") ``` claimZswapCoinReceive(note: Bytes<32>): [] ``` Requires the presence of a commitment in the containing transaction and that no other call claims it as a receive. ### claimZswapCoinSpend[​](#claimzswapcoinspend "Direct link to claimZswapCoinSpend") ``` claimZswapCoinSpend(note: Bytes<32>): [] ``` Requires the presence of a commitment in the containing transaction and that no other call claims it as a spend. ### claimZswapNullifier[​](#claimzswapnullifier "Direct link to claimZswapNullifier") ``` claimZswapNullifier(nul: Bytes<32>): [] ``` Requires the presence of a nullifier in the containing transaction and that no other call claims it. ### incUnshieldedInputs[​](#incunshieldedinputs "Direct link to incUnshieldedInputs") ``` incUnshieldedInputs(token_type: Either, Bytes<32>>, amount: Uint<128>): [] ``` Increments the unshielded input for the token of the given token type by the given amount - used when receiving tokens. ### incUnshieldedOutputs[​](#incunshieldedoutputs "Direct link to incUnshieldedOutputs") ``` incUnshieldedOutputs(token_type: Either, Bytes<32>>, amount: Uint<128>): [] ``` Increments the unshielded output for the token of the given token type by the given amount - used when sending tokens. ### mintShielded[​](#mintshielded "Direct link to mintShielded") ``` mintShielded(domain_sep: Bytes<32>, amount: Uint<64>): [] ``` Mints a given amount of shielded coins with a token type derived from the contract's address, and a given domain separator. ### mintUnshielded[​](#mintunshielded "Direct link to mintUnshielded") ``` mintUnshielded(domain_sep: Bytes<32>, amount: Uint<64>): [] ``` Mints a given amount of unshielded coins with a token type derived from the contract's address, and a given domain separator. ### self[​](#self "Direct link to self") ``` self(): ContractAddress ``` Returns the current contract's address. ContractAddress is defined in CompactStandardLibrary. ## Cell\[​](#cellvalue_type "Direct link to Cell") This ADT is a single Cell containing a value of type value\_type and is used implicitly when the ledger field type is an ordinary Compact type. Programmers cannot write Cell explicitly when declaring a ledger field.. ### read[​](#read "Direct link to read") ``` read(): value_type ``` Returns the current contents of this Cell. *available from Typescript as a getter on the ledger field* ### resetToDefault[​](#resettodefault "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Cell to the default value of its type. ### write[​](#write "Direct link to write") ``` write(value: value_type): [] ``` Overwrites the content of this Cell with the given value. ### writeCoin[​](#writecoin "Direct link to writeCoin") ``` writeCoin(coin: ShieldedCoinInfo, recipient: Either): [] ``` Writes a ShieldedCoinInfo to this Cell, which is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this write fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ## Counter[​](#counter "Direct link to Counter") This ADT is a simple counter. ### decrement[​](#decrement "Direct link to decrement") ``` decrement(amount: Uint<16>): [] ``` Decrements the counter by a given amount. Decrementing below zero results in a run-time error. ### increment[​](#increment "Direct link to increment") ``` increment(amount: Uint<16>): [] ``` Increments the counter by the given amount. ### lessThan[​](#lessthan "Direct link to lessThan") ``` lessThan(threshold: Uint<64>): Boolean ``` Returns if the counter is less than the given threshold value. ### read[​](#read-1 "Direct link to read") ``` read(): Uint<64> ``` Retrieves the current value of the counter. *available from Typescript as a getter on the ledger field* ### resetToDefault[​](#resettodefault-1 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Counter to its default value of 0. ## Set\[​](#setvalue_type "Direct link to Set") This ADT is an unbounded set of values of type value\_type. ### insert[​](#insert "Direct link to insert") ``` insert(elem: value_type): [] ``` Updates this Set to include a given element. ### insertCoin[​](#insertcoin "Direct link to insertCoin") ``` insertCoin(coin: ShieldedCoinInfo, recipient: Either): [] ``` Inserts a ShieldedCoinInfo into this Set, which is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this insertion fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ### isEmpty[​](#isempty "Direct link to isEmpty") ``` isEmpty(): Boolean ``` Returns whether this Set is the empty set. *available from Typescript as `isEmpty(): boolean`* ### member[​](#member "Direct link to member") ``` member(elem: value_type): Boolean ``` Returns if an element is contained within this Set. *available from Typescript as `member(elem: value_type): boolean`* ### remove[​](#remove "Direct link to remove") ``` remove(elem: value_type): [] ``` Update this Set to not include a given element. ### resetToDefault[​](#resettodefault-2 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Set to the empty set. ### size[​](#size "Direct link to size") ``` size(): Uint<64> ``` Returns the number of unique entries in this Set. *available from Typescript as `size(): bigint`* ### \[Symbol.iterator][​](#symboliterator "Direct link to \[Symbol.iterator]") *callable only from TypeScript* ``` [Symbol.iterator](): Iterator ``` Iterates over the entries in this Set. ## Map\[​](#mapkey_type-value_type "Direct link to Map") This ADT is an unbounded set of mappings between values of type key\_type and values of type value\_type. ### insert[​](#insert-1 "Direct link to insert") ``` insert(key: key_type, value: value_type): [] ``` Updates this Map to include a new value at a given key. ### insertCoin[​](#insertcoin-1 "Direct link to insertCoin") ``` insertCoin(key: key_type, coin: ShieldedCoinInfo, recipient: Either): [] ``` Inserts a ShieldedCoinInfo into this Map at a given key, where the ShieldedCoinInfo is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this insertion fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ### insertDefault[​](#insertdefault "Direct link to insertDefault") ``` insertDefault(key: key_type): [] ``` Updates this Map to include the value type's default value at a given key. ### isEmpty[​](#isempty-1 "Direct link to isEmpty") ``` isEmpty(): Boolean ``` Returns if this Map is the empty map. *available from Typescript as `isEmpty(): boolean`* ### lookup[​](#lookup "Direct link to lookup") ``` lookup(key: key_type): value_type ``` Looks up the value of a key within this Map. The returned value may be another ADT. *available from Typescript as `lookup(key: key_type): value_type`* ### member[​](#member-1 "Direct link to member") ``` member(key: key_type): Boolean ``` Returns if a key is contained within this Map. *available from Typescript as `member(key: key_type): boolean`* ### remove[​](#remove-1 "Direct link to remove") ``` remove(key: key_type): [] ``` Updates this Map to not include a given key. ### resetToDefault[​](#resettodefault-3 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Map to the empty map. ### size[​](#size-1 "Direct link to size") ``` size(): Uint<64> ``` Returns the number of entries in this Map. *available from Typescript as `size(): bigint`* ### \[Symbol.iterator][​](#symboliterator-1 "Direct link to \[Symbol.iterator]") *callable only from TypeScript* ``` [Symbol.iterator](): Iterator<[key_type, value_type]> ``` Iterates over the key-value pairs contained in this Map. ## List\[​](#listvalue_type "Direct link to List") This ADT is an unbounded list of values of type value\_type. ### head[​](#head "Direct link to head") ``` head(): Maybe ``` Retrieves the head of this List, returning a Maybe, ensuring this call succeeds on the empty list. Maybe is defined in CompactStandardLibrary (compact-runtime from Typescript). *available from Typescript as `head(): Maybe`* ### isEmpty[​](#isempty-2 "Direct link to isEmpty") ``` isEmpty(): Boolean ``` Returns if this List is the empty list. *available from Typescript as `isEmpty(): boolean`* ### length[​](#length "Direct link to length") ``` length(): Uint<64> ``` Returns the number of elements contained in this List. *available from Typescript as `length(): bigint`* ### popFront[​](#popfront "Direct link to popFront") ``` popFront(): [] ``` Removes the first element from the front of this list. ### pushFront[​](#pushfront "Direct link to pushFront") ``` pushFront(value: value_type): [] ``` Pushes a new element onto the front of this list. ### pushFrontCoin[​](#pushfrontcoin "Direct link to pushFrontCoin") ``` pushFrontCoin(coin: ShieldedCoinInfo, recipient: Either): [] ``` Pushes a ShieldedCoinInfo onto the front of this List, where the ShieldedCoinInfo is transformed into a QualifiedShieldedCoinInfo at runtime by looking up the relevant Merkle tree index. This index must have been allocated within the current transaction or this push fails. ShieldedCoinInfo, ContractAddress, Either, and ZswapCoinPublicKey are defined in CompactStandardLibrary. **available only for QualifiedShieldedCoinInfo value\_type** ### resetToDefault[​](#resettodefault-4 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this List to the empty list. ### \[Symbol.iterator][​](#symboliterator-2 "Direct link to \[Symbol.iterator]") *callable only from TypeScript* ``` [Symbol.iterator](): Iterator ``` Iterates over the entries in this List. ## MerkleTree\[​](#merkletreenat-value_type "Direct link to MerkleTree") This ADT is a bounded Merkle tree of depth nat where 2 `<=` nat `<= 32` containing values of type value\_type. ### checkRoot[​](#checkroot "Direct link to checkRoot") ``` checkRoot(rt: MerkleTreeDigest): Boolean ``` Tests if the given Merkle tree root is the root for this Merkle tree. MerkleTreeDigest is defined in CompactStandardLibrary (compact-runtime from Typescript). *available from Typescript as `checkRoot(rt: MerkleTreeDigest): boolean`* ### insert[​](#insert-2 "Direct link to insert") ``` insert(item: value_type): [] ``` Inserts a new leaf at the first free index in this Merkle tree. ### insertHash[​](#inserthash "Direct link to insertHash") ``` insertHash(hash: Bytes<32>): [] ``` Inserts a new leaf with a given hash at the first free index in this Merkle tree. ### insertHashIndex[​](#inserthashindex "Direct link to insertHashIndex") ``` insertHashIndex(hash: Bytes<32>, index: Uint<64>): [] ``` Inserts a new leaf with a given hash at a specific index in this Merkle tree. ### insertIndex[​](#insertindex "Direct link to insertIndex") ``` insertIndex(item: value_type, index: Uint<64>): [] ``` Inserts a new leaf at a specific index in this Merkle tree. ### insertIndexDefault[​](#insertindexdefault "Direct link to insertIndexDefault") ``` insertIndexDefault(index: Uint<64>): [] ``` Inserts a default value leaf at a specific index in this Merkle tree. This can be used to emulate a removal from the tree. ### isFull[​](#isfull "Direct link to isFull") ``` isFull(): Boolean ``` Returns if this Merkle tree is full and further items cannot be directly inserted. *available from Typescript as `isFull(): boolean`* ### resetToDefault[​](#resettodefault-5 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Merkle tree to the empty Merkle tree. ### findPathForLeaf[​](#findpathforleaf "Direct link to findPathForLeaf") *callable only from TypeScript* ``` findPathForLeaf(leaf: value_type): MerkleTreePath | undefined ``` Finds the path for a given leaf in a Merkle tree. Be warned that this is O(n) and should be avoided for large trees. Returns undefined if no such leaf exists. MerkleTreePath is defined in compact-runtime. ### firstFree[​](#firstfree "Direct link to firstFree") *callable only from TypeScript* ``` firstFree(): bigint ``` Retrieves the first (guaranteed) free index in the Merkle tree. ### pathForLeaf[​](#pathforleaf "Direct link to pathForLeaf") *callable only from TypeScript* ``` pathForLeaf(index: bigint, leaf: value_type): MerkleTreePath ``` Returns the Merkle path, given the knowledge that a specified leaf is at the given index. It is an error to call this if this leaf is not contained at the given index. MerkleTreePath is defined in compact-runtime. ### root[​](#root "Direct link to root") *callable only from TypeScript* ``` root(): MerkleTreeDigest ``` Retrieves the root of the Merkle tree. MerkleTreeDigest is defined in compact-runtime. ## HistoricMerkleTree\[​](#historicmerkletreenat-value_type "Direct link to HistoricMerkleTree") This ADT is a bounded Merkle tree of depth nat where 2 `<=` nat `<=` 32 containing values of type value\_type, with history. ### checkRoot[​](#checkroot-1 "Direct link to checkRoot") ``` checkRoot(rt: MerkleTreeDigest): Boolean ``` Tests if the given Merkle tree root is one of the past roots for this Merkle tree. MerkleTreeDigest is defined in CompactStandardLibrary (compact-runtime from Typescript). *available from Typescript as `checkRoot(rt: MerkleTreeDigest): boolean`* ### insert[​](#insert-3 "Direct link to insert") ``` insert(item: value_type): [] ``` Inserts a new leaf at the first free index in this Merkle tree. ### insertHash[​](#inserthash-1 "Direct link to insertHash") ``` insertHash(hash: Bytes<32>): [] ``` Inserts a new leaf with a given hash at the first free index in this Merkle tree. ### insertHashIndex[​](#inserthashindex-1 "Direct link to insertHashIndex") ``` insertHashIndex(hash: Bytes<32>, index: Uint<64>): [] ``` Inserts a new leaf with a given hash at a specific index in this Merkle tree. ### insertIndex[​](#insertindex-1 "Direct link to insertIndex") ``` insertIndex(item: value_type, index: Uint<64>): [] ``` Inserts a new leaf at a specific index in this Merkle tree. ### insertIndexDefault[​](#insertindexdefault-1 "Direct link to insertIndexDefault") ``` insertIndexDefault(index: Uint<64>): [] ``` Inserts a default value leaf at a specific index in this Merkle tree. This can be used to emulate a removal from the tree. ### isFull[​](#isfull-1 "Direct link to isFull") ``` isFull(): Boolean ``` Returns if this Merkle tree is full and further items cannot be directly inserted. *available from Typescript as `isFull(): boolean`* ### resetHistory[​](#resethistory "Direct link to resetHistory") ``` resetHistory(): [] ``` Resets the history for this Merkle tree, leaving only the current root valid. ### resetToDefault[​](#resettodefault-6 "Direct link to resetToDefault") ``` resetToDefault(): [] ``` Resets this Merkle tree to the empty Merkle tree. ### findPathForLeaf[​](#findpathforleaf-1 "Direct link to findPathForLeaf") *callable only from TypeScript* ``` findPathForLeaf(leaf: value_type): MerkleTreePath | undefined ``` Finds the path for a given leaf in a Merkle tree. Be warned that this is O(n) and should be avoided for large trees. Returns undefined if no such leaf exists. MerkleTreePath is defined in compact-runtime. ### firstFree[​](#firstfree-1 "Direct link to firstFree") *callable only from TypeScript* ``` firstFree(): bigint ``` Retrieves the first (guaranteed) free index in the Merkle tree. ### history[​](#history "Direct link to history") *callable only from TypeScript* ``` history(): Iterator ``` An iterator over the roots that are considered valid past roots for this Merkle tree. MerkleTreeDigest is defined in compact-runtime. ### pathForLeaf[​](#pathforleaf-1 "Direct link to pathForLeaf") *callable only from TypeScript* ``` pathForLeaf(index: bigint, leaf: value_type): MerkleTreePath ``` Returns the Merkle path, given the knowledge that a specified leaf is at the given index. It is an error to call this if the index is out of bounds. MerkleTreePath is defined in compact-runtime. ### root[​](#root-1 "Direct link to root") *callable only from TypeScript* ``` root(): MerkleTreeDigest ``` Retrieves the root of the Merkle tree. MerkleTreeDigest is defined in compact-runtime. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Writing a contract This page walks through the construction of a simple smart contract, which manages a publicly accessible value and supports the operations `get`, `set`, and `clear`. Because the value is public, anyone can call `get`, but if the value is currently set, only the user that last called `set` can `clear` it, and it must be `clear`ed before `set`ting it again. To start, the contract specifies the version of the language it is using, imports Midnight's standard libraries, and declares an `enum` for the state it may currently be in: ``` pragma language_version 0.16; import CompactStandardLibrary; enum State { UNSET, SET } ``` In addition to the `enum` declaration, custom data can also be defined with `struct`s. Details can be found in the [language reference](/compact/reference/compact-reference.md#program-defined-types). ## The `ledger` section[​](#the-ledger-section "Direct link to the-ledger-section") A key part of a Compact smart contract is the `ledger` section, which describes the state kept on chain. This example stores a key that can be used to identify the user who is permitted to `clear` the value, the value itself (this example uses a 64-bit unsigned integer), and what state the contract is in. In addition to these, it is necessary to add a `round` counter, which is useful to retain anonymity, as discussed below. Each field in a smart contract's on-chain state is declared with a `ledger` declaration. A constructor can be used to initialize the ledger fields when the contract is deployed. In this case, the ledger declarations are as follows: ``` export ledger authority: Bytes<32>; export ledger value: Uint<64>; export ledger state: State; export ledger round: Counter; constructor(sk: Bytes<32>, v: Uint<64>) { authority = disclose(publicKey(round, sk)); value = disclose(v); state = State.SET; } circuit publicKey(round: Field, sk: Bytes<32>): Bytes<32> { return persistentHash>>( [pad(32, "midnight:examples:lock:pk"), round as Bytes<32>, sk]); } ``` In addition to the `ledger` section, the `constructor` also demonstrates basic interaction with the state contained in it, using the field names to refer to the items in the ledger's state. Many ledger types also support *operations* as demonstrated in `clear`. ## The `circuit` definitions[​](#the-circuit-definitions "Direct link to the-circuit-definitions") The example above already demonstrates use of a `circuit` to calculate the `publicKey` of a user. A `circuit` in Compact is equivalent to a function in many programming languages, but it is restricted to fixed computational bounds at compile time. A smart contract's `circuit`s can also be its main entry points; they are what users can call directly in transactions. Of the three entry points mentioned above, `get` is *unrestricted* and is simply implemented as follows: ``` export circuit get(): Uint<64> { assert(state == State.SET, "Attempted to get uninitialized value"); return value; } ``` Here `export` marks this circuit as an entry point to the smart contract, and `assert` ensures that it can only be used when the contract is in the correct state. The [language reference](/compact/reference/compact-reference.md#circuit-definitions) details permissible contents of `circuit`s. ## Local state and computations[​](#local-state-and-computations "Direct link to Local state and computations") The third context mentioned was the local machine of the user. This is explicitly programmable in the form of the DApp running on the user's machine. Compact can 'call out' to the local context through *witnesses*\[^1], which are declared in a similar way to circuits. In this case, retrieving a user's *secret key* requires such a witness, because the secret must be kept local to a user's machine. The code for this follows: ``` witness secretKey(): Bytes<32>; export circuit set(v: Uint<64>): [] { assert(state == State.UNSET, "Attempted to set initialized value"); const sk = secretKey(); const pk = publicKey(round, sk); authority = disclose(pk); value = disclose(v); state = State.SET; } export circuit clear(): [] { assert(state == State.SET, "Attempted to clear uninitialized value"); const sk = secretKey(); const pk = publicKey(round, sk); assert(authority == pk, "Attempted to clear without authorization"); state = State.UNSET; round.increment(1); } ``` Note that the `witness` is not implemented in the Compact source code. Instead, the implementation is the responsibility of the TypeScript code of the DApp. It's important to note that each user could reasonably use a different implementation for the `witness`, so its results cannot be trusted inherently by the contract. ## The full contract[​](#the-full-contract "Direct link to The full contract") All put together, the full example is: ``` pragma language_version 0.16; import CompactStandardLibrary; enum State { UNSET, SET } export ledger authority: Bytes<32>; export ledger value: Uint<64>; export ledger state: State; export ledger round: Counter; constructor(sk: Bytes<32>, v: Uint<64>) { authority = disclose(publicKey(round, sk)); value = disclose(v); state = State.SET; } circuit publicKey(round: Field, sk: Bytes<32>): Bytes<32> { return persistentHash>>( [pad(32, "midnight:examples:lock:pk"), round as Bytes<32>, sk]); } export circuit get(): Uint<64> { assert(state == State.SET, "Attempted to get uninitialized value"); return value; } witness secretKey(): Bytes<32>; export circuit set(v: Uint<64>): [] { assert(state == State.UNSET, "Attempted to set initialized value"); const sk = secretKey(); const pk = publicKey(round, sk); authority = disclose(pk); value = disclose(v); state = State.SET; } export circuit clear(): [] { assert(state == State.SET, "Attempted to clear uninitialized value"); const sk = secretKey(); const pk = publicKey(round, sk); assert(authority == pk, "Attempted to clear without authorization"); state = State.UNSET; round.increment(1); } ``` ## Basic confidentiality[​](#basic-confidentiality "Direct link to Basic confidentiality") It may not be immediately apparent what is held confidential in this example and what is enforced in the contract. Thankfully, both are well-defined: * all data that is not a ledger field and is not an argument or return value of a ledger operation is kept confidential * all computation that is not done in a `witness` function is enforced to be correct. In particular, observe that this keeps the `secretKey` output confidential, while enforcing that *its hash* is the correct value in the case of `clear`. This is also the reason for the `round` parameter: The `pk` "public key" *isn't* confidential, and would allow linkability between the same user publishing data in multiple rounds. By adding a round parameter into the public key computation, this linkability is broken. Despite the terms "secret key" and "public key", these two keys are *not* public key cryptography: they are simply a binary string and its hash. This is due to zero-knowledge circuits being able to have similar effects to digital signatures, relying only on the preimage resistance of hashes. This pattern of hashing an arbitrary binary string and using it as a key is quite powerful. A similar concept that can be very useful is the use of *commitment schemes*, where arbitrary data is hashed together with a random *nonce*. The result can be safely placed into the ledger's state, without revealing the original data. (Note that the nonce *must* not be reused. If it is, you can link the commitments with the same nonces and values.) At a later point, the commitment can be "opened" by revealing the value and nonce, or a contract can simply prove (`assert`) that it *has* the correct value and nonce, without ever revealing them. The `CompactStandardLibrary` module provides the following circuits for such uses: ``` circuit transientHash(value: T): Field; circuit transientCommit(value: T, rand: Field): Field; circuit persistentHash(value: T): Bytes<32>; circuit persistentCommit(value: T, rand: Bytes<32>): Bytes<32>; ``` The `*Hash` variants are the basic hash function, with `*Commit` being a commitment function to arbitrary data. The `transient*` functions should only be used when the values are *not* kept in state, while `persistent*` outputs being suitable for storage in a contract's `ledger` state. ## Next steps[​](#next-steps "Direct link to Next steps") [Compact reference](/compact/reference/compact-reference.md) provides a compelete and detailed overview of the Compact language. Alternatively, you may wish to jump to a [more detailed example](/examples/dapps/bboard.md) that showcases some more interesting things you can do with a DApp on Midnight. While this section has focused on the Compact language, the section about how Midnight works provides more detail about Midnight's ledger and how it functions. \[^1] The name *witness* comes from zero-knowledge literature; the etymology is roughly that it's the evidence you need to believe a statement. In this example, it's the evidence you need to believe that a `clear` was permissible. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Smart contract security Compact smart contracts on Midnight combine privacy-preserving computation with cryptographic guarantees. The compiler enforces certain rules and restrictions, but much of the responsibility for secure contract interaction is up to the developer implementing the smart contract. For this reason, it is very important for smart contract developers to understand common pitfalls and adhere to security best practices. ## Security model overview[​](#security-model-overview "Direct link to Security model overview") Compact enforces security through multiple layers: * **Privacy by default**: Private data must be explicitly disclosed before appearing on-chain * **Compile-time validation**: The compiler prevents accidental disclosure of witness data * **zero-knowledge proofs**: All circuit computations are cryptographically verified without revealing inputs * **Bounded execution**: Fixed computational bounds prevent resource exhaustion attacks * **Immutable deployments**: Contracts cannot tamper with deployed state, transactions always produce a new output state ### Three execution contexts[​](#three-execution-contexts "Direct link to Three execution contexts") Compact contracts operate across three distinct security contexts: 1. **Public ledger**: On-chain state visible to all network observers 2. **zero-knowledge circuits**: On-chain functions that validate operations using proofs without revealing private inputs 3. **Local computation**: Arbitrary code execution on user machines via witness functions Understanding these components and their boundaries is crucial for writing secure contracts. ### Sealed vs. unsealed ledger fields[​](#sealed-vs-unsealed-ledger-fields "Direct link to Sealed vs. unsealed ledger fields") Ledger fields can be optionally marked as `sealed` to make them immutable after contract initialization. A sealed field can only be set during contract deployment by the constructor or helper circuits that the constructor calls. After initialization, no exported circuit can modify sealed fields. * **Unsealed fields** (default) - Exported circuits can modify these during contract execution * **Sealed fields** - Can only be set during initialization; immutable afterward ``` sealed ledger field1: Uint<32>; export sealed ledger field2: Uint<32>; circuit init(x: Uint<32>): [] { field2 = x; // Valid: called by constructor } constructor(x: Uint<16>) { field1 = 2 * x; // Valid: in constructor init(x); // Valid: helper circuit } export circuit modify(): [] { field1 = 10; // ❌ Compilation error: sealed field } ``` Use sealed fields for configuration values, contract parameters, or any data that should remain constant after deployment. The compiler enforces this at compile time, preventing accidental modification in exported circuits. ### Witness functions and off-chain computation[​](#witness-functions-and-off-chain-computation "Direct link to Witness functions and off-chain computation") Witnesses are off-chain functions invoked from on-chain Compact circuits. This enables on-chain verification of off-chain compute. Compact holds only the function declaration and the implementation is written in the TypeScript frontend: ``` // Compact declaration witness localSecretKey(): Bytes<32>; witness getUserBalance(): Uint<64>; ``` TypeScript implementation of the witness functions: ``` // TypeScript implementation export const witnesses = { localSecretKey: ({ privateState }: WitnessContext) => [privateState, privateState.secretKey], getUserBalance: ({ privateState }: WitnessContext) => [privateState, privateState.balance], }; ``` Witness security Witness implementations run outside zero-knowledge circuits and are *not* cryptographically verified. Each user provides their own witness implementation, so contract logic must never trust witness values without validation. It is best practice for DApp developers to isolate functions requiring access to private state to witnesses, but this is not enforced programmatically. Due to the strong adherence to the "private by default" model, private state data can also be supplied directly to circuit inputs(internal or exported) and still remain private. ### ownPublicKey() is a witness function[​](#ownpublickey-is-a-witness-function "Direct link to ownPublicKey() is a witness function") The built-in Compact function `ownPublicKey()` returns the Zswap coin public key of the user executing the circuit, however, it is technically a witness function. `ownPublicKey()` cannot be trusted without prior verification of the caller and especially not as a caller verification mechanism. warning Do not use `ownPublicKey()` for verification of the caller in Compact circuits! It should only be used after the caller has already been verified through another mechanism. ## Privacy-preserving fundamentals[​](#privacy-preserving-fundamentals "Direct link to Privacy-preserving fundamentals") Compact's privacy model is built on the principle that sensitive data remains hidden by default. Strong understanding of how privacy works in Compact is necessary for building secure contracts that protect user data when interacting with the public ledger. ### Explicit disclosure requirement[​](#explicit-disclosure-requirement "Direct link to Explicit disclosure requirement") Compact enforces a "private by default" model where all circuit inputs and values derived from witness functions remain private unless explicitly disclosed. The compiler tracks private data flow and requires the `disclose()` wrapper before allowing it to be: * Stored in public ledger state * Returned from exported circuits ``` witness secretKey(): Bytes<32>; // value, _sk and pk are private by default export circuit set(value: Uint<64>): [] { const _sk = secretKey(); const pk = persistentHash(Vector<2, Bytes<32>>([pad(32, "domain"), _sk])); // Must explicitly disclose before storing in ledger authority = disclose(pk); storedValue = disclose(value); } ``` Attempting to store data publicly or return it from an exported circuit without `disclose()` results in a compilation error: ``` Exception: potential witness-value disclosure must be declared but is not: witness value potentially disclosed: the return value of witness secretKey at line 1 nature of the disclosure: assignment to ledger field 'authority' ``` Prefacing identifier names intended to remain private with an underscore is a best practice in cryptography to allow developers to track which values they need to keep private. Compact provides significant built-in privacy, but it still requires a rigorous attention to detail by the DApp developer. note `disclose()` itself *does not* make a value public, it serves to notify the compiler that this value is safe to store publicly and bypass the private by default mechanism. ### Best practice: Place disclose() strategically[​](#best-practice-place-disclose-strategically "Direct link to Best practice: Place disclose() strategically") Position `disclose()` as close to the disclosure point as possible to prevent accidental disclosure through multiple code paths: ``` // ✅ Good: Disclose at the point of use export circuit store(flag: Boolean): [] { const secret = getSecret(); const derived = computeValue(secret); // Still private result = disclose(flag) ? disclose(derived) : 0; // Specific explicit disclosure } // ❌ Bad: Early disclosure increases risk export circuit store(flag: Boolean): [] { const secret = disclose(getSecret()); // Disclosed too early const derived = computeValue(secret); result = disclose(flag) ? derived : 0; } ``` ## Cryptographic primitives[​](#cryptographic-primitives "Direct link to Cryptographic primitives") Compact provides cryptographic primitives through the standard library for hashing, commitments, and privacy-preserving operations. Understanding when to use each primitive is essential for building secure smart contracts. These hashing and commitment functions enable you to publicly post a hash on-chain and later prove properties about the committed value (or reveal it) without having disclosed it initially. ### Hash functions[​](#hash-functions "Direct link to Hash functions") Compact provides two hash functions with different guarantees. These are most useful for hashing binary data that has a unique fingerprint and is not easily derivable by a malicious actor on its own. * **`transientHash(value: T): Field`** - Circuit-optimized hash for temporary consistency checks; not guaranteed to persist between protocol upgrades * **`persistentHash(value: T): Bytes<32>`** - SHA-256 hash suitable for deriving state data; guaranteed to remain consistent across upgrades Use `persistentHash` for any values stored in ledger state or used for authentication. ### Commitment schemes[​](#commitment-schemes "Direct link to Commitment schemes") Commitments allow you to hash values, such as a number, which may be easy for a malicious actor to derive with a brute force attack. Compact commitment functions are paired with a random (salt) value that renders the simple value impossible to guess, unless the random value is also guessed. * **`transientCommit(value: T, rand: Field): Field`** - Circuit-efficient commitment for temporary use; not guaranteed to persist between protocol upgrades * **`persistentCommit(value: T, rand: Bytes<32>): Bytes<32>`** - SHA-256-based commitment for persistent storage; guaranteed to remain consistent across upgrades Commitment schemes and hashing functions provide two security properties: * **Hiding** - The hash reveals nothing about the original value; observers cannot determine what you committed * **Binding** - After creating a commitment, you cannot change the value; the commitment permanently binds to the original data. These are one-way, deterministic functions in that the value under the hash is hidden forever and can never be revealed. In order to verify information under a hash or commitment, have the user provide the same value for verification, run it through the same function and compare the hashes to ensure they match. If they do not match, the user provided a different value. ``` export ledger valueCommitment: Bytes<32>; export circuit commitToValue(value: Uint<64>, rand: Bytes<32>): [] { const commitment = persistentCommit(value, rand); valueCommitment = commitment; } export circuit revealValue(value: Uint<64>, rand: Bytes<32>): [] { const commitment = persistentCommit(value, rand); assert(commitment == valueCommitment, "Invalid commitment opening"); // Value is now verified without prior public disclosure } ``` The result of a `persistentCommit` operation does not require `disclose()` because the use of a random salt value allows the compiler to consider the return value as sufficiently private for storage publicly. It is very important that the random value provided is sufficient and unique in its randomness. Randomness reuse Never reuse randomness across commitments. Reusing a random value with different commitment values enables linking the commitments, breaking a degree of privacy. If the random value is compromised the extent of the potential data that can be compromised is limited to a single value. ### Double-spend prevention with nullifiers[​](#double-spend-prevention-with-nullifiers "Direct link to Double-spend prevention with nullifiers") Nullifiers prevent double-spending of coins or consumption of private state elements without revealing which specific coin was spent. A nullifier is a one-way hash that uniquely identifies a resource without revealing it: ``` export ledger usedNullifiers: Set>; circuit nullifier(secretKey: Bytes<32>): Bytes<32> { return persistentHash>>([ pad(32, "nullifier-domain"), secretKey ]); } export circuit spend(secretKey: Bytes<32>): [] { const nul = nullifier(secretKey); assert(!usedNullifiers.member(nul), "Already spent"); usedNullifiers.insert(disclose(nul)); } ``` Use domain separation (different prefixes like `"nullifier-my-dapp-1"` vs `"commitment-my-dapp-2"`) to prevent hash collision attacks across different purposes. ### Best practice: Use appropriate cryptographic primitives[​](#best-practice-use-appropriate-cryptographic-primitives "Direct link to Best practice: Use appropriate cryptographic primitives") Choose the right primitive for your use case: | Primitive | Use case | Persistence | Disclosure protection | | ------------------ | -------------------------------- | ------------ | --------------------- | | `transientHash` | Temporary checks | No guarantee | No | | `transientCommit` | Temporary hiding | No guarantee | Yes | | `persistentHash` | State derivation, authentication | Guaranteed | No | | `persistentCommit` | Long-term hiding | Guaranteed | Yes | ### Best practice: Use domain separation[​](#best-practice-use-domain-separation "Direct link to Best practice: Use domain separation") Prevent hash collision attacks by using distinct domain separators for different purposes: ``` circuit publicKey(_sk: Bytes<32>): Bytes<32> { return persistentHash>>([ pad(32, "commitment-domain"), _sk ]); } circuit nullifier(sk: Bytes<32>): Bytes<32> { return persistentHash>>([ pad(32, "nullifier-domain"), // Different domain sk ]); } ``` ## Input validation and access control[​](#input-validation-and-access-control "Direct link to Input validation and access control") Compact contracts should validate all inputs and enforce authorization for circuit execution when required by the use case. *This is a very important responsibility that lies with the Compact developer.* A particular circuits access control is only as good as the developer makes it. The language provides built-in mechanisms for enabling these security features. ### Assert statements[​](#assert-statements "Direct link to Assert statements") Use `assert` to validate all inputs, state transitions, and access requirements: ``` export circuit updateBalance(recipient: Bytes<32>, amount: Uint<64>): [] { // Validate state assert(state == State.ACTIVE, "Contract not active"); // Validate inputs assert(amount > 0, "Amount must be greater than zero"); assert(amount <= balance, "Insufficient balance"); // Validate authorization const _sk = secretKey(); const pk = publicKey(_sk); assert(pk == owner, "Unauthorized"); // Update balance balance = balance - amount; } ``` Assertions provide: * **Pre-condition checks** - Verify contract state before operations * **Input validation** - Reject invalid parameters early * **Authorization** - Enforce access control through cryptographic verification * **Invariant preservation** - Maintain contract consistency ### Best practice: Validate all inputs[​](#best-practice-validate-all-inputs "Direct link to Best practice: Validate all inputs") Never trust witness data or circuit parameters without validation: ``` export circuit updateBalance(amount: Uint<64>): [] { // Validate bounds assert(amount > 0, "Amount must be greater than zero"); assert(amount <= MAX_TRANSFER, "Amount exceeds limit"); // Validate state assert(balance >= amount, "Insufficient balance"); // Validate authorization const _sk = secretKey(); assert(isAuthorized(_sk), "Unauthorized"); balance = balance - amount; } ``` ### Best practice: Handle errors securely[​](#best-practice-handle-errors-securely "Direct link to Best practice: Handle errors securely") Error messages should not leak sensitive information: ``` // ✅ Good: Generic error message export circuit withdraw(amount: Uint<64>): [] { const authorized = checkAuth(); assert(authorized, "Operation not permitted"); } // ❌ Bad: Leaks private state export circuit withdraw(amount: Uint<64>): [] { const sk = secretKey(); const balance = getBalance(); assert(balance >= amount, "Balance " ++ balance ++ " insufficient"); } ``` ### Authentication patterns[​](#authentication-patterns "Direct link to Authentication patterns") Compact circuits can emulate digital signatures using hash-based authentication. This pattern can enable a "DApp specific public key" that is only traceable within a specific DApp. This can enable certain use cases, but may put limitations on others. This pattern allows `publicKey` to be called once and establish an authority for access to other circuits in the contract throughout its lifecycle. ``` circuit publicKey(_sk: Bytes<32>): Bytes<32> { const hash = persistentHash>>([ pad(32, "midnight:auth:pk"), _sk ]); return hash; } export circuit setAuthorized(): [] { const _sk = secretKey(); const pk = publicKey(_sk); authority = disclose(pk); } // only authority can call authorizedOperation export circuit authorizedOperation(newLedgerValue: Bytes<32>): [] { const _sk = secretKey(); const pk = publicKey(_sk); assert(disclose(pk) == authority, "Authorization failed"); // Perform authorized operation ledgerValue = disclose(newLedgerValue); } ``` To break the linkability of transactions, include a round counter in the hashing function of `publicKey` that makes the public key only valid for the desired chain of calls. This requires calling `publicKey` at the start of the chain and incrementing the counter at the end, invalidating the old public key. For an example of this pattern, see [Writing a contract](/compact/reference/writing.md#the-full-contract). ownPublicKey Never use `ownPublicKey()` for verification of the caller of a particular Compact circuit. `ownPublicKey()` is technically a witness function and each user frontend is capable of producing a malicious return from an `ownPublicKey()` call. Only use this function after the caller has already been verified. ## Testing and validation[​](#testing-and-validation "Direct link to Testing and validation") Thorough testing is essential for identifying security vulnerabilities before deployment. For comprehensive testing strategies, debugging techniques, and test examples, see the [Testing and debugging guide](/compact/testing). ## Next steps[​](#next-steps "Direct link to Next steps") * Review the [explicit disclosure guide](/compact/reference/explicit-disclosure.md) for advanced privacy patterns * Test your contracts on the [Preprod network](/nodes/node-endpoints.md) before production deployment --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact standard library **CompactStandardLibrary** ∙ [Detailed API reference](/compact/standard-library/exports.md) This API provides standard types and circuits for use in Compact programs. Key parts of the API are: * Common data types: * [`Maybe`](/compact/standard-library/exports.md#maybe) * [`Either`](/compact/standard-library/exports.md#either) * [`NativePoint`](/compact/standard-library/exports.md#nativepoint) * [`Secp256k1Point`](/compact/standard-library/exports.md#secp256k1point) * [`MerkleTreeDigest`](/compact/standard-library/exports.md#merkletreedigest) * [`MerkleTreePathEntry`](/compact/standard-library/exports.md#merkletreepathentry) * [`MerkleTreePath`](/compact/standard-library/exports.md#merkletreepath) * [`ContractAddress`](/compact/standard-library/exports.md#contractaddress) * [`ZswapCoinPublicKey`](/compact/standard-library/exports.md#zswapcoinpublickey) * [`UserAddress`](/compact/standard-library/exports.md#useraddress) * Coin management data types: * [`ShieldedCoinInfo`](/compact/standard-library/exports.md#shieldedcoininfo) * [`QualifiedShieldedCoinInfo`](/compact/standard-library/exports.md#qualifiedshieldedcoininfo) * [`ShieldedSendResult`](/compact/standard-library/exports.md#shieldedsendresult) * Common functions: * [`some`](/compact/standard-library/exports.md#some) * [`none`](/compact/standard-library/exports.md#none) * [`left`](/compact/standard-library/exports.md#left) * [`right`](/compact/standard-library/exports.md#right) * Hashing functions: * [`transientHash`](/compact/standard-library/exports.md#transienthash) * [`transientCommit`](/compact/standard-library/exports.md#transientcommit) * [`persistentHash`](/compact/standard-library/exports.md#persistenthash) * [`persistentCommit`](/compact/standard-library/exports.md#persistentcommit) * [`degradeToTransient`](/compact/standard-library/exports.md#degradetotransient) * [`upgradeFromTransient`](/compact/standard-library/exports.md#upgradefromtransient) * [`keccak256`](/compact/standard-library/exports.md#keccak256) * Elliptic curve types and functions: * [`JubjubPoint`](/compact/standard-library/exports.md#jubjubpoint) * [`JubjubScalar`](/compact/standard-library/exports.md#jubjubscalar) * [`constructJubjubPoint`](/compact/standard-library/exports.md#constructjubjubpoint) * [`jubjubPointX`](/compact/standard-library/exports.md#jubjubpointx) * [`jubjubPointY`](/compact/standard-library/exports.md#jubjubpointy) * [`Secp256k1Point`](/compact/standard-library/exports.md#secp256k1point) * [`Secp256k1Base`](/compact/standard-library/exports.md#secp256k1base) * [`Secp256k1Scalar`](/compact/standard-library/exports.md#secp256k1scalar) * [`secp256k1PointX`](/compact/standard-library/exports.md#secp256k1pointx) * [`secp256k1PointY`](/compact/standard-library/exports.md#secp256k1pointy) * [`ecAdd`](/compact/standard-library/exports.md#ecadd) * [`ecNeg`](/compact/standard-library/exports.md#ecneg) * [`ecMul`](/compact/standard-library/exports.md#ecmul) * [`ecMulGenerator`](/compact/standard-library/exports.md#ecmulgenerator) * [`hashToCurve`](/compact/standard-library/exports.md#hashtocurve) * secp256k1 field arithmetic functions: * [`neg`](/compact/standard-library/exports.md#neg) * [`inv`](/compact/standard-library/exports.md#inv) * Merkle tree functions: * [`merkleTreePathRoot`](/compact/standard-library/exports.md#merkletreepathroot) * [`merkleTreePathRootNoLeafHash`](/compact/standard-library/exports.md#merkletreepathrootnoleafhash) * Coin management functions: * [`tokenType`](/compact/standard-library/exports.md#tokentype) * [`nativeToken`](/compact/standard-library/exports.md#nativetoken) * [`ownPublicKey`](/compact/standard-library/exports.md#ownpublickey) * [`createZswapInput`](/compact/standard-library/exports.md#createzswapinput) * [`createZswapOutput`](/compact/standard-library/exports.md#createzswapoutput) * [`mintShieldedToken`](/compact/standard-library/exports.md#mintshieldedtoken) * [`evolveNonce`](/compact/standard-library/exports.md#evolvenonce) * [`receiveShielded`](/compact/standard-library/exports.md#receiveshielded) * [`sendShielded`](/compact/standard-library/exports.md#sendshielded) * [`sendImmediateShielded`](/compact/standard-library/exports.md#sendimmediateshielded) * [`mergeCoin`](/compact/standard-library/exports.md#mergecoin) * [`mergeCoinImmediate`](/compact/standard-library/exports.md#mergecoinimmediate) * [`shieldedBurnAddress`](/compact/standard-library/exports.md#shieldedburnaddress) * [`mintUnshieldedToken`](/compact/standard-library/exports.md#mintunshieldedtoken) * [`sendUnshielded`](/compact/standard-library/exports.md#sendunshielded) * [`receiveUnshielded`](/compact/standard-library/exports.md#receiveunshielded) * [`unshieldedBalance`](/compact/standard-library/exports.md#unshieldedbalance) * [`unshieldedBalanceLt`](/compact/standard-library/exports.md#unshieldedbalancelt) * [`unshieldedBalanceGte`](/compact/standard-library/exports.md#unshieldedbalancegte) * [`unshieldedBalanceGt`](/compact/standard-library/exports.md#unshieldedbalancegt) * [`unshieldedBalanceLte`](/compact/standard-library/exports.md#unshieldedbalancelte) * [`shieldedburnaddress`](/compact/standard-library/exports.md#shieldedburnaddress) * Block time functions: * [`blockTimeLt`](/compact/standard-library/exports.md#blocktimelt) * [`blockTimeGte`](/compact/standard-library/exports.md#blocktimegte) * [`blockTimeGt`](/compact/standard-library/exports.md#blocktimegt) * [`blockTimeLte`](/compact/standard-library/exports.md#blocktimelte) * Cryptographic signature types and functions: * [`JubjubSchnorrSignature`](/compact/standard-library/exports.md#jubjubschnorrsignature) * [`jubjubSchnorrVerify`](/compact/standard-library/exports.md#jubjubschnorrverify) * [`Secp256k1EcdsaSignature`](/compact/standard-library/exports.md#secp256k1ecdsasignature) * [`secp256k1EcdsaVerify`](/compact/standard-library/exports.md#secp256k1ecdsaverify) * [`secp256k1EthereumAddress`](/compact/standard-library/exports.md#secp256k1ethereumaddress) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Detailed API reference ## Top-level exports and native types and functions[​](#top-level-exports-and-native-types-and-functions "Direct link to Top-level exports and native types and functions") Exporting a type or circuit from the top level of a contract makes its definition visible and usable from the contract's TypeScript API. Exporting a circuit from the top level of a contract additionally makes it one of the contract's endpoints for on-chain transactions. Many of the the types and functions defined in the standard library are **native** types and functions. These are ones that have special handling of some kind in the Compact compiler. As a consequence of this special handling, they cannot currently be exported from the top level of a contract. It is a compiler error to try to export these types and functions. You can, however, export type aliases for native types and export circuits that wrap native functions. For example: ``` import { JubjubPoint as nativeJubjubPoint, ecAdd as nativeEcAdd } from CompactStandardLibrary; export type JubjubPoint = nativeJubjubPoint; export pure circuit ecAdd(a: JubjubPoint, b: JubjubPoint): JubjubPoint { return nativeEcAdd(a, b); } ``` The generated TypeScript API will include definitions for `JubjubPoint` and `ecAdd`. Note that the standard library's `ecAdd` is polymorphic (it works with other curve types besides Jubjub) but the exported version only works for `JubjubPoint`. ## Structure types[​](#structure-types "Direct link to Structure types") ### `Maybe`[​](#maybe "Direct link to maybe") Encapsulates an optionally present value. If `isSome` is `false`, `value` should be `default` by convention. ``` struct Maybe { isSome: Boolean; value: T; } ``` ### `Either`[​](#either "Direct link to either") Disjoint union of `A` and `B`. Iff `isLeft` if `true`, `left` should be populated, otherwise `right`. The other should be `default< >` by convention. ``` struct Either { isLeft: Boolean; left: A; right: B; } ``` ### `JubjubSchnorrSignature`[​](#jubjubschnorrsignature "Direct link to jubjubschnorrsignature") A Schnorr signature over the JubJub embedded curve. Contains an announcement point and a scalar response, used with [`jubjubSchnorrVerify`](#jubjubschnorrverify). ``` struct JubjubSchnorrSignature { announcement: JubjubPoint; response: Field; } ``` ### `JubjubSchnorrSignature`[​](#jubjubschnorrsignature-1 "Direct link to jubjubschnorrsignature-1") A Schnorr signature over the JubJub embedded curve. Contains an announcement point and a scalar response, used with [`jubjubSchnorrVerify`](#jubjubschnorrverify). ``` struct JubjubSchnorrSignature { announcement: JubjubPoint; response: Field; } ``` ### `Secp256k1EcdsaSignature`[​](#secp256k1ecdsasignature "Direct link to secp256k1ecdsasignature") An ECDSA signature over the secp256k1 curve, used with [`secp256k1EcdsaVerify`](#secp256k1ecdsaverify). The `r` and `s` components are `Secp256k1Scalar`s. ``` struct Secp256k1EcdsaSignature { r: Secp256k1Scalar; s: Secp256k1Scalar; } ``` ### `MerkleTreeDigest`[​](#merkletreedigest "Direct link to merkletreedigest") The root hash of a Merkle tree, represented by a single `Field`. ``` struct MerkleTreeDigest { field: Field; } ``` ### `MerkleTreePathEntry`[​](#merkletreepathentry "Direct link to merkletreepathentry") An entry in a Merkle tree path, indicating if the path leads left or right, and the root of the sibling node. Primarily used in [`MerkleTreePath`](#merkletreepath) ``` struct MerkleTreePathEntry { sibling: MerkleTreeDigest; goesLeft: Boolean; } ``` ### `MerkleTreePath`[​](#merkletreepath "Direct link to merkletreepath") A path in a depth `n` Merkle tree, leading to a leaf of type `T`. Primarily used for [`merkleTreePathRoot`](#merkletreepathroot). This can be constructed from `witness`es that use the compiler output's `findPathForLeaf` and `pathForLeaf` functions. ``` struct MerkleTreePath<#n, T> { leaf: T; path: Vector; } ``` ### `ContractAddress`[​](#contractaddress "Direct link to contractaddress") The address of a contract, used as a recipient in [`sendShielded`](#sendshielded), [`sendImmediateShielded`](#sendimmediateshielded), [`createZswapOutput`](#createzswapoutput), and [`mintShieldedToken`](#mintshieldedtoken). ``` struct ContractAddress { bytes: Bytes<32>; } ``` ### `ShieldedCoinInfo`[​](#shieldedcoininfo "Direct link to shieldedcoininfo") The description of a newly created shielded coin, used in outputting shielded coins, or spending/receiving shielded coins that originate in the current transaction. `nonce` can be deterministically derived with [`evolveNonce`](#evolvenonce). Used in: * [`receiveShielded`](#receiveshielded) * [`sendImmediateShielded`](#sendimmediateshielded) * [`mergeCoin`](#mergecoin) * [`mergeCoinImmediate`](#mergecoinimmediate) * [`createZswapOutput`](#createzswapoutput) ``` struct ShieldedCoinInfo { nonce: Bytes<32>; color: Bytes<32>; value: Uint<128>; } ``` ### `QualifiedShieldedCoinInfo`[​](#qualifiedshieldedcoininfo "Direct link to qualifiedshieldedcoininfo") The description of an existing shielded coin in the ledger, ready to be spent. Used in: * [`sendShielded`](#sendshielded) * [`mergeCoin`](#mergeCoin) * [`mergeCoinImmediate`](#mergecoinimmediate) * [`createZswapInput`](#createzswapinput) ``` struct QualifiedShieldedCoinInfo { nonce: Bytes<32>; color: Bytes<32>; value: Uint<128>; mtIndex: Uint<64>; } ``` ### `ZswapCoinPublicKey`[​](#zswapcoinpublickey "Direct link to zswapcoinpublickey") The public key used to output a [`ShieldedCoinInfo`](#shieldedcoininfo) to a user, used as a recipient in [`sendShielded`](#sendshielded), [`sendImmediateShielded`](#sendimmediateshielded), and [`createZswapOutput`](#createzswapoutput). ``` struct ZswapCoinPublicKey { bytes: Bytes<32>; } ``` ### `ShieldedSendResult`[​](#shieldedsendresult "Direct link to shieldedsendresult") The output of [`sendShielded`](#sendshielded) and [`sendImmediateShielded`](#sendimmediateshielded), detailing the created shielded coin, and the change from spending the input, if applicable. ``` struct ShieldedSendResult { change: Maybe; sent: ShieldedCoinInfo; } ``` ### `UserAddress`[​](#useraddress "Direct link to useraddress") The public key of a user, used as a recipient in [`sendUnshielded`](#sendunshielded) and [`mintUnshieldedToken`](#mintunshieldedtoken). ``` struct UserAddress { bytes: Bytes<32>; } ``` ## Events[​](#events "Direct link to Events") Events are struct types that can be emitted using an `emit` operation. ### `ShieldedSpend`[​](#shieldedspend "Direct link to shieldedspend") Shielded coin consumed, new coin created for a user recipient. Serialized size is 32. ``` struct ShieldedSpend { nullifier: Bytes<32> // indexed } ``` ### `ShieldedReceive`[​](#shieldedreceive "Direct link to shieldedreceive") A contract accepts an incoming shielded coin. `contractAddress` set when received by a contract, absent for user recipients. Serialized size is 578. ``` struct ShieldedReceive { commitment: Bytes<32>, // indexed ciphertext: Maybe>, contractAddress: Maybe> } ``` ### `ShieldedMint`[​](#shieldedmint "Direct link to shieldedmint") New shielded tokens created. `tokenType` derived by the consumer from `domainSep` + `ContractLog.address`. Serialized size is 81. ``` struct ShieldedMint { commitment: Bytes<32>, // indexed domainSep: Bytes<32>, // indexed amount: Maybe> } ``` ### `ShieldedBurn`[​](#shieldedburn "Direct link to shieldedburn") Shielded coin sent to the burn address. Supply tracking — tokens permanently removed from circulation. Serialized size is 49. ``` struct ShieldedBurn { nullifier: Bytes<32>, // indexed amount: Maybe> } ``` ### `UnshieldedSpend`[​](#unshieldedspend "Direct link to unshieldedspend") Public token sent from a sender. Serialized size is 145. ``` struct UnshieldedSpend { sender: Either, // indexed domainSep: Bytes<32>, // indexed tokenType: Bytes<32>, // indexed amount: Uint<128> } ``` ### `UnshieldedReceive`[​](#unshieldedreceive "Direct link to unshieldedreceive") Public token sent to a recipient. Serialized size is 145. ``` struct UnshieldedReceive { recipient: Either, // indexed domainSep: Bytes<32>, // indexed tokenType: Bytes<32>, // indexed amount: Uint<128> } ``` ### `UnshieldedMint`[​](#unshieldedmint "Direct link to unshieldedmint") New unshielded tokens created. Serialized size is 80. ``` struct UnshieldedMint { domainSep: Bytes<32>, // indexed tokenType: Bytes<32>, // indexed amount: Uint<128> } ``` ### `UnshieldedBurn`[​](#unshieldedburn "Direct link to unshieldedburn") Unshielded coin sent to the burn address. Serialized size is 113. ``` struct UnshieldedBurn { sender: Either, // indexed tokenType: Bytes<32>, // indexed amount: Uint<128> } ``` ### `Paused`[​](#paused "Direct link to paused") Contract operations suspended. Serialized size is 0. ``` struct Paused {} ``` ### `Unpaused`[​](#unpaused "Direct link to unpaused") Contract operations resumed. Serialized size is 0. ``` struct Unpaused {} ``` ### `Misc`[​](#misc "Direct link to misc") Miscellaneous event type. Serialized size is 288. ``` struct Misc { name: Bytes<32>, payload: Bytes<256> } ``` ## Circuits[​](#circuits "Direct link to Circuits") ### `some`[​](#some "Direct link to some") Constructs a [`Maybe`](#maybe) containing an element of type `T` ``` circuit some(value: T): Maybe; ``` ### `none`[​](#none "Direct link to none") Constructs a [`Maybe`](#maybe) containing nothing ``` circuit none(): Maybe; ``` ### `left`[​](#left "Direct link to left") Construct an [`Either`](#either) containing the `A` item of the disjoint union ``` circuit left(value: A): Either; ``` ### `right`[​](#right "Direct link to right") Constructs an [`Either`](#either) containing the `B` item of the disjoint union ``` circuit right(value: B): Either; ``` ### `transientHash`[​](#transienthash "Direct link to transienthash") Builtin transient hash compression function This function is a circuit-efficient compression function from arbitrary values to field elements, which is not guaranteed to persist between upgrades. It should not be used to derive state data, but can be used for consistency checks. Although this function returns a hash of its inputs, it is not considered sufficient to protect its input from disclosure. If its input contains any value returned from a witness, the program must acknowledge disclosure (via a `disclose` wrapper) if the result can be stored in the public ledger, returned from an exported circuit, or passed to another contract via a cross-contract call. ``` circuit transientHash(value: T): Field; ``` ### `transientCommit`[​](#transientcommit "Direct link to transientcommit") Builtin transient commitment function This function is a circuit-efficient commitment function over arbitrary types, and a field element commitment opening, to field elements, which is not guaranteed to persist between upgrades. It should not be used to derive state data, but can be used for consistency checks. Unlike `transientHash`, this function is considered sufficient to protect its input from disclosure, under the assumption that the `rand` argument is sufficiently random. Thus, even if its input contains a value or values returned from one or more witnesses, the program need not acknowledge disclosure (via a `disclose` wrapper) if the result can be stored in the public ledger, returned from an exported circuit, or passed to another contract via a cross-contract call. ``` circuit transientCommit(value: T, rand: Field): Field; ``` ### `persistentHash`[​](#persistenthash "Direct link to persistenthash") Builtin persistent hash compression function This function is a non-circuit-optimised compression function from arbitrary values to a 256-bit bytestring. It is guaranteed to persist between upgrades, and to consistently use the SHA-256 compression algorithm. It *should* be used to derive state data, and not for consistency checks where avoidable. The note about disclosing under `transientHash` also applies to this function. ``` circuit persistentHash(value: T): Bytes<32>; ``` ### `persistentCommit`[​](#persistentcommit "Direct link to persistentcommit") Builtin persistent commitment function This function is a non-circuit-optimised commitment function from arbitrary values representable in Compact, and a 256-bit bytestring opening, to a 256-bit bytestring. It is guaranteed to persist between upgrades, and use the SHA-256 compression algorithm. It *should* be used to derive state data, and not for consistency checks where avoidable. The note about disclosing under `transientCommit` also applies to this function. ``` circuit persistentCommit(value: T, rand: Bytes<32>): Bytes<32>; ``` ### `degradeToTransient`[​](#degradetotransient "Direct link to degradetotransient") This function "degrades" the output of a [`persistentHash`](#persistenthash) or [`persistentCommit`](#persistentcommit) to a field element, which can then be used in [`transientHash`](#transienthash) or [`transientCommit`](#transientcommit). ``` circuit degradeToTransient(x: Bytes<32>) : Field; ``` ### `upgradeFromTransient`[​](#upgradefromtransient "Direct link to upgradefromtransient") This function "upgrades" a field element to the output of a [`persistentHash`](#persistenthash) or [`persistentCommit`](#persistentcommit). ``` circuit upgradeFromTransient(x: Field): Bytes<32>; ``` ### `keccak256`[​](#keccak256 "Direct link to keccak256") This function hashes its input using the Keccak-256 algorithm. It returns the 32-byte digest. ``` circuit keccak256(value: T): Bytes<32>; ``` ### `JubjubPoint`[​](#jubjubpoint "Direct link to jubjubpoint") This is a native type. The type of points on the embedded elliptic curve. It represents a pair of affine x- and y-coordinates. The coordinates are native `Field` (BLS12-381) values. ### `JubjubScalar`[​](#jubjubscalar "Direct link to jubjubscalar") This is a native type. The type of numeric values between 0 (inclusive) and the order of the prime-order subgroup of the Jubjub embedded elliptic curve (exclusive). It is the type of the scalars used to multiply Jubjub curve points. The maximum value (one less that the field order) is (decimal) 6554484396890773809930967563523245729705921265872317281365359162392183254198 and (hexadecimal) 0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb6. ### `constructJubjubPoint`[​](#constructjubjubpoint "Direct link to constructjubjubpoint") This is a native circuit. This function constructs a [`JubjubPoint`](#jubjubpoint) from its x- and y-coordinates. Neither the standard library nor the Compact JavaScript runtime package will actually verify that a constructed point actually lies on the Jubjub curve. The behavior of constructing or operating on an invalid Jubjub curve point is undefined. You will not normally be able to construct proofs involving invalid Jubjub curve points. ``` circuit constructJubjubPoint(x: Field, y: Field): JubjubPoint; ``` ### `jubjubPointX`[​](#jubjubpointx "Direct link to jubjubpointx") This is a native circuit. This function extracts the x-coordinate from a [`JubjubPoint`](#jubjubpoint). ``` circuit jubjubPointX(pt: JubjubPoint): Field; ``` ### `jubjubPointY`[​](#jubjubpointy "Direct link to jubjubpointy") This is a native circuit. This function extracts the y-coordinate from a [`JubjubPoint`](#jubjubpoint). ``` circuit jubjubPointY(pt: JubjubPoint): Field; ``` ### `Secp256k1Point`[​](#secp256k1point "Direct link to secp256k1point") This is a native type. The type of points on the secp256k1 elliptic curve. It represents a pair of affine x- and y-coordinates. The coordinates are `Secp256k1Base` values. Secp256k1 points cannot be created in Compact, but they can be passed as circuit arguments and returned from witness functions. The behavior of operating on an invalid secp256k1 curve point is undefined. You will not normally be able to construct proofs involving invalid secp256k1 curve points. The (additive) identity point does not have a representation as a pair of coordinates. It is represented in Compact as `default`. ### `Secp256k1Base`[​](#secp256k1base "Direct link to secp256k1base") This is a native type. The type of values between 0 (inclusive) and the order of the base field of the secp256k1 elliptic curve (exclusive). It is the type of the affine coordinates of a point on that curve. The maximum value (one less than the field order) is (decimal) 115792089237316195423570985008687907853269984665640564039457584007908834671662 and (hexadecimal) 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e. ### `Secp256k1Scalar`[​](#secp256k1scalar "Direct link to secp256k1scalar") This is a native type. The type of numeric values betwen 0 (inclusive) and the order of the secp256k1 group (exclusive). This is the type of the scalars used to multiply secp256k1 curve points. The maximum value (one less than the field order) is (decimal) 115792089237316195423570985008687907852837564279074904382605163141518161494336 and (hexadecimal) 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140. ### `secp256k1PointX`[​](#secp256k1pointx "Direct link to secp256k1pointx") This is a native type. This function extracts the affine x-coordinate from a [`Secp256k1Point`](#secp256k1point). ``` circuit secp256k1PointX(pt: Secp256k1Point): Secp256k1Base; ``` ### `secp256k1PointY`[​](#secp256k1pointy "Direct link to secp256k1pointy") This is a native type. This function extracts the affine y-coordinate from a [`Secp256k1Point`](#secp256k1point). ``` circuit secp256k1PointY(pt: Secp256k1Point): Secp256k1Base; ``` ### `ecAdd`[​](#ecadd "Direct link to ecadd") This function adds two elliptic curve points. It is polymorphic for the following types: * [`JubjubPoint`](#jubjubpoint)s * [`Secp256k1Point`](#secp256k1point)s. ``` circuit ecAdd(a: JubjubPoint, b: JubjubPoint): JubjubPoint; circuit ecAdd(a: Secp256k1Point, b: Secp256k1Point): Secp256k1Point; ``` ### `ecNeg`[​](#ecneg "Direct link to ecneg") This function negates an elliptic [`JubjubPoint`](#jubjubpoint). On the JubJub twisted Edwards curve, the negation of `(x, y)` is `(-x, y)`. ``` circuit ecNeg(a: JubjubPoint): JubjubPoint; ``` ### `ecMul`[​](#ecmul "Direct link to ecmul") This function multiplies an elliptic curve point by a scalar. It is polymorphic for the following types: * [`JubjubPoint`](#jubjubpoint)s * [`Secp256k1Point`](#secp256k1point)s. ``` circuit ecMul(a: JubjubPoint, b: JubjubScalar): JubjubPoint; circuit ecMul(a: Secp256k1Point, b: Secp256k1Scalar): Secp256k1Point; ``` ### `ecMulGenerator`[​](#ecmulgenerator "Direct link to ecmulgenerator") This function multiplies the primary group generator of a curve by a scalar. It is polymorphic for the following types: * [`JubjubPoint`](#jubjubpoint)s * [`Secp256k1Point`](#secp256k1point)s. ``` circuit ecMulGenerator(b: JubjubScalar): JubjubPoint; circuit ecMulGenerator(b: Secp256k1Scalar): Secp256k1Point; ``` ### `neg`[​](#neg "Direct link to neg") Negates a field element, i.e. returns the value `y` such that `add(x, y)` is `0` in the field. Polymorphic function that works over types: * `Secp256k1Scalar` * `Secp256k1Base` ``` circuit neg(x: Secp256k1Scalar): Secp256k1Scalar; circuit neg(x: Secp256k1Base): Secp256k1Base; ``` ### `inv`[​](#inv "Direct link to inv") Returns the multiplicative inverse of a field element, i.e. the value `y` such that `mul(x, y)` is `1` in the field. Polymorphic function that works over types: * `Secp256k1Scalar` * `Secp256k1Base` ``` circuit inv(x: Secp256k1Scalar): Secp256k1Scalar; circuit inv(x: Secp256k1Base): Secp256k1Base; ``` ### `hashToCurve`[​](#hashtocurve "Direct link to hashtocurve") This function maps arbitrary types to [`JubjubPoint`](#nativepoint)s. Outputs are guaranteed to have unknown discrete logarithm with respect to the group base, and any other output, but are not guaranteed to be unique (a given input can be proven correct for multiple outputs). Inputs of different types `T` may have the same output, if they have the same field-aligned binary representation. ``` circuit hashToCurve(value: T): JubjubPoint; ``` ### `jubjubSchnorrVerify`[​](#jubjubschnorrverify "Direct link to jubjubschnorrverify") Verifies a Schnorr signature over the JubJub embedded curve. Takes a message as a vector of `N` field elements, a [`JubjubSchnorrSignature`](#jubjubschnorrsignature), and a verification key (a [`JubjubPoint`](#nativepoint) on the embedded curve). Returns true if the signature is valid; false if the signature does not verify. To actually enforce that a signature is valid in a Compact circuit, use an `assert` that the result is true. ``` circuit jubjubSchnorrVerify<#N>( msg: Vector, signature: JubjubSchnorrSignature, pk: JubjubPoint ): Boolean; ``` ### `jubjubSchnorrVerify`[​](#jubjubschnorrverify-1 "Direct link to jubjubschnorrverify-1") Verifies a Schnorr signature over the JubJub embedded curve. Takes a message as a vector of `n` field elements, a [`JubjubSchnorrSignature`](#jubjubschnorrsignature), and a verification key (a [`JubjubPoint`](#nativepoint) on the embedded curve). Asserts that the signature is valid; fails if the signature does not verify. ``` circuit jubjubSchnorrVerify<#n>(msg: Vector, signature: JubjubSchnorrSignature, vk: JubjubPoint): []; ``` ### `secp256k1EcdsaVerify`[​](#secp256k1ecdsaverify "Direct link to secp256k1ecdsaverify") Verifies an ECDSA signature over the secp256k1 curve. Takes a 32-byte message hash, a [`Secp256k1EcdsaSignature`](#secp256k1ecdsasignature), and a public key (a [`Secp256k1Point`](#secp256k1point)). Returns true if the signature is valid; false otherwise. The circuit takes `msgHash` as given and does not constrain it to any message. The caller is expected to bind it to the actual message by hashing that message in-circuit (e.g. with [`keccak256`](#keccak256) for Ethereum-style signatures or [`persistentHash`](#persistenthash) for Bitcoin-style ones). To actually enforce that a signature is valid in a Compact circuit, use an `assert` that the result is true. ``` circuit secp256k1EcdsaVerify(msgHash: Bytes<32>, sig: Secp256k1EcdsaSignature, pk: Secp256k1Point): Boolean; ``` ### `secp256k1EthereumAddress`[​](#secp256k1ethereumaddress "Direct link to secp256k1ethereumaddress") Derives the 20-byte Ethereum-style address of a secp256k1 public key, i.e. the low 20 bytes of the Keccak-256 hash of the [`Secp256k1Point`](#secp256k1point). ``` circuit secp256k1EthereumAddress(pk: Secp256k1Point): Bytes<20>; ``` ### `merkleTreePathRoot`[​](#merkletreepathroot "Direct link to merkletreepathroot") Derives the Merkle tree root of a [`MerkleTreePath`](#merkletreepath), which should match the root of the tree that this path originated from. ``` circuit merkleTreePathRoot<#n, T>(path: MerkleTreePath): MerkleTreeDigest; ``` ### `merkleTreePathRootNoLeafHash`[​](#merkletreepathrootnoleafhash "Direct link to merkletreepathrootnoleafhash") Derives the Merkle tree root of a [`MerkleTreePath`](#merkletreepath), which should match the root of the tree that this path originated from. As opposed to [`merkleTreePathRoot`](#merkletreepathroot), this variant assumes that the tree leaves have already been hashed externally. ``` circuit merkleTreePathRootNoLeafHash<#n>(path: MerkleTreePath>): MerkleTreeDigest; ``` ### `nativeToken`[​](#nativetoken "Direct link to nativetoken") Returns the token type of the native token ``` circuit nativeToken(): Bytes<32>; ``` ### `tokenType`[​](#tokentype "Direct link to tokentype") Transforms a domain separator for the given contract into a globally namespaced token type. A contract can issue tokens for its domain separators, which lets it create new tokens, but due to collision resistance, it cannot mint tokens for another contract's token type. This is used as the `color` field in [`ShieldedCoinInfo`](#shieldedcoininfo) and as arguments to functions like [`sendUnshielded`](#sendunshielded) and [`receiveUnshielded`](#receiveunshielded). ``` circuit tokenType(domainSep: Bytes<32>, contract: ContractAddress): Bytes<32>; ``` ### `mintShieldedToken`[​](#mintshieldedtoken "Direct link to mintshieldedtoken") Creates a new shielded coin, minted by this contract, and sends it to the given recipient. Returns the corresponding [`ShieldedCoinInfo`](#shieldedcoininfo). This requires inputting a unique nonce to function securely, it is left to the user how to produce this. To mint a shielded token to the current contract, pass `right(kernel.self())` as the `recipient`. ``` circuit mintShieldedToken( domainSep: Bytes<32>, value: Uint<64>, nonce: Bytes<32>, recipient: Either ): ShieldedCoinInfo; ``` ### `evolveNonce`[​](#evolvenonce "Direct link to evolvenonce") Deterministically derives a [`ShieldedCoinInfo`](#shieldedcoininfo) nonce from a counter index, and a prior nonce. ``` circuit evolveNonce( index: Uint<128>, nonce: Bytes<32> ): Bytes<32>; ``` ### `shieldedBurnAddress`[​](#shieldedburnaddress "Direct link to shieldedburnaddress") Returns a payment address that guarantees any shielded coins sent to it are burned. ``` circuit shieldedBurnAddress(): Either; ``` ### `receiveShielded`[​](#receiveshielded "Direct link to receiveshielded") Receives a shielded coin, adding a validation condition requiring this coin to be present as an output addressed to this contract, and not received by another call ``` circuit receiveShielded(coin: ShieldedCoinInfo): []; ``` ### `sendShielded`[​](#sendshielded "Direct link to sendshielded") Sends given value from a shielded coin owned by the contract to a recipient. Any change is returned and should be managed by the contract. Note that this does not currently create coin ciphertexts, so sending to a user public key except for the current user will not lead to this user being informed of the coin they've been sent. To send a shielded token to the current contract, pass `right(kernel.self())` as the `recipient`. ``` circuit sendShielded(input: QualifiedShieldedCoinInfo, recipient: Either, value: Uint<128>): ShieldedSendResult; ``` ### `sendImmediateShielded`[​](#sendimmediateshielded "Direct link to sendimmediateshielded") Like [`sendShielded`](#sendshielded), but for coins created within this transaction ``` circuit sendImmediateShielded(input: ShieldedCoinInfo, target: Either, value: Uint<128>): ShieldedSendResult; ``` ### `mergeCoin`[​](#mergecoin "Direct link to mergecoin") Takes two coins stored on the ledger, and combines them into one ``` circuit mergeCoin(a: QualifiedCoinInfo, b: QualifiedCoinInfo): CoinInfo; ``` ### `mergeCoinImmediate`[​](#mergecoinimmediate "Direct link to mergecoinimmediate") Takes one coin stored on the ledger, and one created within this transaction, and combines them into one ``` circuit mergeCoinImmediate(a: QualifiedCoinInfo, b: CoinInfo): CoinInfo; ``` ### `ownPublicKey`[​](#ownpublickey "Direct link to ownpublickey") Returns the [`ZswapCoinPublicKey`](#zswapcoinpublickey) of the end-user creating this transaction. ``` circuit ownPublicKey(): ZswapCoinPublicKey; ``` ### `createZswapInput`[​](#createzswapinput "Direct link to createzswapinput") Notifies the context to create a new Zswap input originating from this call. Should typically not be called manually, prefer [`sendShielded`](#sendshielded) and [`sendImmediateShielded`](#sendimmediateshielded) instead. The note about disclosing under `transientHash` also applies to this function. ``` circuit createZswapInput(coin: QualifiedShieldedCoinInfo): []; ``` ### `createZswapOutput`[​](#createzswapoutput "Direct link to createzswapoutput") Notifies the context to create a new Zswap output originating from this call. Should typically not be called manually, prefer [`sendShielded`](#sendshielded) and [`sendImmediateShielded`](#sendimmediateShielded), and [`receiveShielded`](#receiveshielded) instead. The note about disclosing under `transientHash` also applies to this function. ``` circuit createZswapOutput(coin: ShieldedCoinInfo, recipient: Either): []; ``` ### `mintUnshieldedToken`[​](#mintunshieldedtoken "Direct link to mintunshieldedtoken") Creates a new unshielded coin, minted by this contract, and sends it to the given recipient. Returns the corresponding coin color. To mint an unshielded token to the current contract, pass `left(kernel.self())` as the `recipient`. ``` export circuit mintUnshieldedToken( domainSep: Bytes<32>, value: Uint<64>, recipient: Either ): Bytes<32>; ``` ### `sendUnshielded`[​](#sendunshielded "Direct link to sendunshielded") Sends the given amount of the given unshielded token (identified by the color) to the given recipient. No change is returned from this function. To send an unshielded token to the current contract, pass `left(kernel.self())` as the `recipient`. ``` export circuit sendUnshielded(color: Bytes<32>, amount: Uint<128>, recipient: Either): []; ``` ### `receiveUnshielded`[​](#receiveunshielded "Direct link to receiveunshielded") Receives the given amount of the unshielded token identified by the color. ``` circuit receiveUnshielded(color: Bytes<32>, amount: Uint<128>): []; ``` ### `unshieldedBalance`[​](#unshieldedbalance "Direct link to unshieldedbalance") Returns the contract's balance of the unshielded token of the given type. Note that this balance is not updated during contract execution as a result of unshielded sends and receives. It is always fixed to the value provided at the start of execution. Also note that using this function means transaction application will fail unless the token balance at the time of transaction construction is exactly the same as the balance at the time of transaction application. Unless you want to require that, prefer to use the balance comparison functions [`unshieldedBalanceLt`](#unshieldedbalancelt), [`unshieldedBalanceGte`](#unshieldedbalancegte), [`unshieldedBalanceGt`](#unshieldedbalancegt), and [`unshieldedBalanceLte`](#unshieldedbalancelte). ``` circuit unshieldedBalance(color: Bytes<32>): Uint<128>; ``` ### `unshieldedBalanceLt`[​](#unshieldedbalancelt "Direct link to unshieldedbalancelt") Returns true if the unshielded balance of the contract for the given token type is less than the given value. ``` circuit unshieldedBalanceLt(color: Bytes<32>, amount: Uint<128>): Boolean; ``` ### `unshieldedBalanceGte`[​](#unshieldedbalancegte "Direct link to unshieldedbalancegte") Returns true if the unshielded balance of the contract for the given token type is greater than or equal to the given value. ``` circuit unshieldedBalanceGte(color: Bytes<32>, amount: Uint<128>): Boolean; ``` ### `unshieldedBalanceGt`[​](#unshieldedbalancegt "Direct link to unshieldedbalancegt") Returns true if the unshielded balance of the contract for the given token type is greater than the given value. ``` circuit unshieldedBalanceGt(color: Bytes<32>, amount: Uint<128>): Boolean ``` ### `unshieldedBalanceLte`[​](#unshieldedbalancelte "Direct link to unshieldedbalancelte") Returns true if the unshielded balance of the contract for the given token type is less than or equal to the given value. ``` circuit unshieldedBalanceLte(color: Bytes<32>, amount: Uint<128>): Boolean; ``` ### `blockTimeLt`[​](#blocktimelt "Direct link to blocktimelt") Returns true if the current block time is less than the given value. ``` circuit blockTimeLt(time: Uint<64>): Boolean; ``` ### `blockTimeGte`[​](#blocktimegte "Direct link to blocktimegte") Returns true if the current block time is greater than or equal to the given value. ``` circuit blockTimeGte(time: Uint<64>): Boolean; ``` ### `blockTimeGt`[​](#blocktimegt "Direct link to blocktimegt") Returns true if the current block time is greater than the given value. ``` circuit blockTimeGt(time: Uint<64>): Boolean; ``` ### `blockTimeLte`[​](#blocktimelte "Direct link to blocktimelte") Returns true if the current block time is less than or equal to the given value. ``` circuit blockTimeLte(time: Uint<64>): Boolean; ``` ### `serialize`[​](#serializet-n "Direct link to serializet-n") Returns the canonical byte encoding of for a given value of event type. Note that `serialize` can only be instantiated for an event type and its canonical serialized size. ``` circuit serialize (x: T): Bytes; ``` ### `deserialize`[​](#deserializet-n "Direct link to deserializet-n") Reconstructs a value of type event from its canonical byte encoding. Note that `deserialize` can only be instantiated for an event type and its canonical serialized size. ``` circuit deserialize (x: Bytes): T; ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Test and debug Testing Compact smart contracts requires a comprehensive approach that validates both functional correctness and security properties. ## Why test smart contracts?[​](#why-test-smart-contracts "Direct link to Why test smart contracts?") Compact smart contracts execute across multiple contexts (on-chain ledger, zero-knowledge circuits, and local witnesses), requiring different testing strategies for each layer. Proper testing ensures your contract behaves correctly, maintains privacy guarantees, and handles edge cases appropriately. This guide covers the following testing strategies: * **Circuit logic testing**: Validate that individual circuits produce correct outputs and state transitions. * **Privacy verification**: Confirm that private data does not leak through public outputs. * **Authorization testing**: Ensure access control mechanisms prevent unauthorized operations. * **Integration testing**: Test complete transaction flows on test networks. * **Performance testing**: Verify proof generation completes within acceptable timeframes. ## Input validation patterns[​](#input-validation-patterns "Direct link to Input validation patterns") Validate all inputs at circuit boundaries to prevent invalid state transitions and security vulnerabilities. Proper input validation ensures your contract behaves correctly and rejects malicious or malformed inputs. ### Comprehensive validation example[​](#comprehensive-validation-example "Direct link to Comprehensive validation example") This example demonstrates multiple validation techniques applied to a transfer circuit: ``` const MAX_AMOUNT: Uint<64> = 1000000; const MIN_AMOUNT: Uint<64> = 1; ledger balance: Uint<64>; export circuit transfer(recipient: Bytes<32>, amount: Uint<64>): [] { // Bounds checking assert(amount >= MIN_AMOUNT, "Amount too small"); assert(amount <= MAX_AMOUNT, "Amount exceeds maximum"); // State validation assert(balance >= amount, "Insufficient funds"); // Format validation assert(recipient != Bytes<32>{}, "Invalid recipient"); // Execute transfer balance = balance - amount; } ``` ## Unit test circuits[​](#unit-test-circuits "Direct link to Unit test circuits") Unit tests validate individual circuit behavior in isolation. Test both success paths and failure conditions to ensure your contract handles all scenarios correctly. ### Test circuit execution[​](#test-circuit-execution "Direct link to Test circuit execution") The following example tests the basic increment operation for the [Counter contract](/tutorials/counter/smart-contract). This demonstrates unit testing at the circuit level without requiring a full blockchain deployment: ``` import { describe, it, expect } from '@jest/globals'; import { Contract } from '../managed/counter/contract/index.js'; import { witnesses, type CounterPrivateState } from '../witnesses.js'; describe('Counter circuit', () => { it('should increment counter value', async () => { const contract = new Contract(witnesses); const privateState: CounterPrivateState = { privateCounter: 0 }; // Create circuit context const context = { privateState, ledgerState: { round: 0n } }; // Call increment circuit const result = contract.impureCircuits.increment(context); // Verify ledger state updated expect(result.newLedgerState.round).toBe(1n); }); }); ``` ### Test state transitions[​](#test-state-transitions "Direct link to Test state transitions") Test that your contract enforces valid state machine transitions and rejects invalid ones. The [bulletin board](/tutorials/bboard/smart-contract.md) contract demonstrates two-state validation: ``` import { Contract } from '../managed/bboard/contract/index.js'; import { witnesses, type BBoardPrivateState } from '../witnesses.js'; import { State } from '../managed/bboard/contract/index.js'; describe('Bulletin board state transitions', () => { it('should enforce valid state transitions', async () => { const contract = new Contract(witnesses); const privateState: BBoardPrivateState = { secretKey: new Uint8Array(32) }; // Initial state - board is vacant const context = { privateState, ledgerState: { state: State.VACANT, message: { is_some: false, value: '' }, sequence: 0n, owner: new Uint8Array(32) } }; // Valid transition: post to vacant board const postResult = contract.impureCircuits.post(context, 'Hello'); expect(postResult.newLedgerState.state).toBe(State.OCCUPIED); expect(postResult.newLedgerState.message.value).toBe('Hello'); // Invalid transition: post to occupied board should fail expect(() => { contract.impureCircuits.post(postResult.newContext, 'World'); }).toThrow('Board is occupied'); }); }); ``` ### Test boundary conditions[​](#test-boundary-conditions "Direct link to Test boundary conditions") Test edge cases and boundary values to ensure your contract handles limits correctly: ``` import { Contract } from '../managed/counter/contract/index.js'; import { witnesses, type CounterPrivateState } from '../witnesses.js'; describe('Boundary conditions', () => { it('should handle Counter operations correctly', async () => { const contract = new Contract(witnesses); const privateState: CounterPrivateState = { privateCounter: 0 }; // Test normal increment const context = { privateState, ledgerState: { round: 0n } }; const result = contract.impureCircuits.increment(context); expect(result.newLedgerState.round).toBe(1n); // Test multiple increments let currentContext = result.newContext; for (let i = 0; i < 10; i++) { const nextResult = contract.impureCircuits.increment(currentContext); currentContext = nextResult.newContext; } expect(currentContext.ledgerState.round).toBe(11n); }); it('should validate input bounds with assertions', async () => { // Example of testing bounds validation in circuit const MAX_AMOUNT = 1000000n; const balance = 500000n; // This would be tested in your circuit's assert statements expect(() => { if (MAX_AMOUNT + 1n > balance) { throw new Error('Amount exceeds maximum'); } }).toThrow('Amount exceeds maximum'); }); }); ``` ## Integration test[​](#integration-test "Direct link to Integration test") Integration tests validate complete transaction flows on test networks (Preview or Preprod). These tests ensure your contract interacts correctly with the Midnight blockchain, proof servers, and other system components. ### Transaction finalization test[​](#transaction-finalization-test "Direct link to Transaction finalization test") Test that transactions complete successfully and update on-chain state. This verifies the full transaction lifecycle from submission to confirmation: ``` it('should handle transaction finalization correctly', async () => { // Submit transaction const tx = await deployedContract.callTx.increment(); // Wait for transaction confirmation const receipt = await tx.wait(); expect(receipt.status).toBe('APPLIED_TO_CHAIN'); expect(receipt.found).toBe(true); // Verify state updated on-chain const contractState = await providers.publicDataProvider.contractStateObservable( deployedContract.deployTxData.public.contractAddress, { type: 'latest' } ).toPromise(); expect(contractState.data.round).toBeGreaterThan(0n); }); ``` ## Privacy verification[​](#privacy-verification "Direct link to Privacy verification") Privacy tests ensure that private witness data does not appear in public transaction outputs or blockchain state. These tests are critical for verifying that zero-knowledge proofs properly protect sensitive information. ### Test disclosure behavior[​](#test-disclosure-behavior "Direct link to Test disclosure behavior") Verify that only explicitly disclosed values appear in public state. The `disclose()` function in Compact marks witness values for public inclusion: ``` import { Contract } from '../managed/bboard/contract/index.js'; import { witnesses, type BBoardPrivateState } from '../witnesses.js'; import { State } from '../managed/bboard/contract/index.js'; it('should only disclose explicitly disclosed values', async () => { const contract = new Contract(witnesses); const secretKey = new Uint8Array(32); crypto.getRandomValues(secretKey); const privateState: BBoardPrivateState = { secretKey }; const context = { privateState, ledgerState: { state: State.VACANT, message: { is_some: false, value: '' }, sequence: 0n, owner: new Uint8Array(32) } }; // Call circuit that uses secret key via witness const result = contract.impureCircuits.post(context, 'Message'); // Owner field should contain disclosed public key hash, not secret key expect(result.newLedgerState.owner).toBeDefined(); expect(result.newLedgerState.owner).not.toEqual(secretKey); // Message should be disclosed (it's a public field) expect(result.newLedgerState.message.value).toBe('Message'); // Secret key remains in private state, not ledger expect(result.newContext.privateState.secretKey).toEqual(secretKey); }); ``` ## Negative test[​](#negative-test "Direct link to Negative test") Negative tests verify that contracts correctly reject invalid operations and unauthorized access. These tests are essential for ensuring your contract's security properties. ### Test assertion failures[​](#test-assertion-failures "Direct link to Test assertion failures") Test that circuits reject operations when preconditions are not met. Assert statements in Compact enforce invariants at runtime: ``` import { Contract } from '../managed/bboard/contract/index.js'; import { witnesses, type BBoardPrivateState } from '../witnesses.js'; import { State } from '../managed/bboard/contract/index.js'; describe('Assertion handling', () => { it('should reject takeDown on vacant board', async () => { const contract = new Contract(witnesses); const privateState: BBoardPrivateState = { secretKey: new Uint8Array(32) }; const vacantContext = { privateState, ledgerState: { state: State.VACANT, message: { is_some: false, value: '' }, sequence: 0n, owner: new Uint8Array(32) } }; // Attempt to take down when board is vacant expect(() => { contract.impureCircuits.takeDown(vacantContext); }).toThrow('Board is vacant'); }); it('should enforce authorization for takeDown', async () => { const ownerKey = new Uint8Array(32); const attackerKey = new Uint8Array(32); crypto.getRandomValues(ownerKey); crypto.getRandomValues(attackerKey); const vacantState = { state: State.VACANT, message: { is_some: false, value: '' }, sequence: 0n, owner: new Uint8Array(32) }; // Post with owner key const ownerPrivateState: BBoardPrivateState = { secretKey: ownerKey }; const postResult = contract.impureCircuits.post( { privateState: ownerPrivateState, ledgerState: vacantState }, 'Message' ); // Attempt takeDown with different key const attackerPrivateState: BBoardPrivateState = { secretKey: attackerKey }; expect(() => { contract.impureCircuits.takeDown({ privateState: attackerPrivateState, ledgerState: postResult.newLedgerState }); }).toThrow('Not authorized'); }); }); ``` ### Test double-spend prevention[​](#test-double-spend-prevention "Direct link to Test double-spend prevention") Test that nullifiers prevent reusing the same resource. Nullifiers are one-time identifiers derived from private data that prevent double-spending: ``` it('should prevent double-spend with sequence tracking', async () => { const secretKey = new Uint8Array(32); crypto.getRandomValues(secretKey); const privateState: BBoardPrivateState = { secretKey }; const vacantState = { state: State.VACANT, message: { is_some: false, value: '' }, sequence: 0n, owner: new Uint8Array(32) }; // First post should succeed const firstPost = contract.impureCircuits.post( { privateState, ledgerState: vacantState }, 'First message' ); expect(firstPost.newLedgerState.sequence).toBe(1n); // Take down and post again should increment sequence const takeDown = contract.impureCircuits.takeDown({ privateState, ledgerState: firstPost.newLedgerState }); const secondPost = contract.impureCircuits.post( { privateState, ledgerState: takeDown.newLedgerState }, 'Second message' ); // Sequence increments to prevent replay attacks expect(secondPost.newLedgerState.sequence).toBe(2n); }); ``` ## Debug strategies[​](#debug-strategies "Direct link to Debug strategies") When your contract behaves unexpectedly, systematic debugging helps identify the root cause. These strategies help you trace circuit execution, inspect state changes, and diagnose common issues. ### Enable verbose logging[​](#enable-verbose-logging "Direct link to Enable verbose logging") Use logging to trace contract execution and understand circuit behavior: ``` import pino from 'pino'; const logger = pino({ level: 'debug' }); // Log before transaction logger.debug('Submitting increment transaction'); const tx = await deployedContract.callTx.increment(); // Log transaction details logger.debug('Transaction submitted'); const receipt = await tx.wait(); logger.debug({ txId: receipt.public.txId, blockHeight: receipt.public.blockHeight, status: receipt.status }, 'Transaction confirmed'); ``` ### Inspect circuit execution[​](#inspect-circuit-execution "Direct link to Inspect circuit execution") Add detailed logging to understand state transitions during testing: ``` it('should debug circuit state changes', async () => { // Query initial ledger state const initialContractState = await providers.publicDataProvider.contractStateObservable( deployedContract.deployTxData.public.contractAddress, { type: 'latest' } ).toPromise(); console.log('Initial ledger state:', initialContractState.data); // Submit transaction const tx = await deployedContract.callTx.post('Debug message'); console.log('Transaction submitted'); // Wait and inspect receipt const receipt = await tx.wait(); console.log('Transaction receipt:', { status: receipt.status, blockHeight: receipt.public.blockHeight, txId: receipt.public.txId }); // Query final state const finalContractState = await providers.publicDataProvider.contractStateObservable( deployedContract.deployTxData.public.contractAddress, { type: 'latest' } ).toPromise(); console.log('Final ledger state:', finalContractState.data); // Verify state transition expect(finalContractState.data.state).toBe(State.OCCUPIED); }); ``` ## Common debug scenarios[​](#common-debug-scenarios "Direct link to Common debug scenarios") The following scenarios cover typical issues encountered during Compact contract development and how to diagnose them. ### Circuit execution failures[​](#circuit-execution-failures "Direct link to Circuit execution failures") When a circuit fails during execution, check these common causes: * **Witness function return types**: Ensure witness functions return tuples matching the `witness` declaration, for example `[PrivateState, ReturnValue]`. * **Assert conditions**: Verify all `assert` statements pass with your test inputs. Log the values you are comparing to identify which assertion is failing. * **Variable initialization**: Confirm you initialize all variables before use. Compact does not allow reading uninitialized variables. * **Bounded integer types**: Review bounds on types like `Uint<8>` and `Uint<64>`. Ensure values fit within declared ranges. ### Proof generation failures[​](#proof-generation-failures "Direct link to Proof generation failures") When proof generation fails or times out, investigate these potential issues: * **Circuit complexity**: Verify circuit computational bounds are reasonable. Extremely complex circuits may exceed proof server capacity limits. * **Infinite loops**: Check for loops that may not terminate. Use bounded loop counters to guarantee termination. * **Witness data types**: Confirm witness functions return data matching circuit expectations. Verify correct sizes for `Uint8Array` values and valid ranges for `bigint` values. * **Memory constraints**: Review large data structures that may exceed memory limits. Consider chunking or pagination for large collections. ### State synchronization issues[​](#state-synchronization-issues "Direct link to State synchronization issues") When ledger state does not update as expected, verify these aspects: * **Transaction finalization**: Verify transactions complete with `await tx.wait()` before querying state. Premature queries might return stale data. * **Witness consistency**: Confirm witness functions return consistent values across calls. Avoid external dependencies that might change between invocations. * **Ledger field operations**: Review how you modify ledger fields. Ensure operations are valid for the field type (for example, `Counter.increment()` vs direct assignment). ## Next steps[​](#next-steps "Direct link to Next steps") Now that you understand testing strategies for Compact smart contracts: * Review the [smart contract security](/compact/smart-contract-security.md) guide for security best practices * Review the [Compact JavaScript implementation](/guides/compact-javascript-runtime.md) guide for more information on how to use the JavaScript implementation to test your contracts. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Concepts Understand the core ideas behind Midnight, including confidentiality with zero-knowledge proofs, contracts, and verifiable computation. **Core concepts cover these terms** | Concept | Explanation | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Who interacts** | **Accounts** define who participates on Midnight. They manage keys, addresses, and authorization. This shows *who acts in the system*. | | **Where data lives** | **Ledgers** store state. Midnight keeps a public ledger for visible data and a private ledger for shielded data. This shows *where state is stored and who can see it*. | | **How value moves** | **The UTXO model** defines spendable pieces of value or state. Midnight extends this model with private state elements. This shows *how value flows through the system*. | | **How apps connect** | **Web3** explains how wallets, connectors, and dApps communicate with contracts. This shows *how users and applications interact with Midnight*. | | **How privacy is enforced** | **Zero-knowledge proofs** verify correctness without exposing sensitive data. This shows *how private actions stay verifiable*. | | **How computation is proved** | **Kachina** is Midnight’s proving system. It converts private computation into verifiable proofs. This shows *how we trust execution we cannot see*. | | **How it all comes together** | **ZSwap** applies these concepts in practice. It uses private state, proofs, and confidential execution. This shows *how a real private dApp works end-to-end*. | ### [Accounts](/concepts/account.md) Learn how Midnight accounts, addresses, and keys relate to each other. [Read →](/concepts/account.md) ### [Ledgers](/concepts/ledgers.md) See how public and private ledgers track state and interact securely. [Read →](/concepts/ledgers.md) ### [UTXO model](/concepts/utxo.md) Review how UTXOs represent value and how Midnight extends the model. [Read →](/concepts/utxo.md) ### [Web3](/concepts/web3.md) Understand how Midnight fits into wallets, dApps, and existing tooling. [Read →](/concepts/web3.md) ### [Zero-knowledge proofs](/concepts/zero-knowledge-proofs.md) Understand how ZK proofs protect data while proving correctness. [Read →](/concepts/zero-knowledge-proofs.md) ### [Kachina](/concepts/kachina.md) Learn about the proving system that powers Midnight’s confidential computation. [Read →](/concepts/kachina.md) ### [ZSwap](/concepts/zswap.md) See how confidential swaps preserve privacy while enabling efficient exchange. [Read →](/concepts/zswap.md) *** Midnight uses zero-knowledge proofs to keep sensitive data private while still verifying contract logic. Its smart contracts operate across public and private ledgers, reducing transaction correlation and supporting secure, confidential on-chain atomic swaps of tokens and metadata. ### [Learn the building blocks](/concepts/how-midnight-works/building-blocks.md) Review circuits, ledgers, and assignments that form Midnight’s foundation. [Explore →](/concepts/how-midnight-works/building-blocks.md) ### [Explore Compact contracts](/concepts/how-midnight-works/smart-contracts.md) See how Compact defines confidential logic and interacts with verified data. [Open →](/concepts/how-midnight-works/smart-contracts.md) ### [Keep data private](/concepts/how-midnight-works/keeping-data-private.md) Learn the patterns that restrict data visibility to authorized participants. [Learn →](/concepts/how-midnight-works/keeping-data-private.md) ### [Understand Compact semantics](/concepts/how-midnight-works/semantics.md) Trace how the runtime enforces rules over public and private data. [Read →](/concepts/how-midnight-works/semantics.md) ### [Examine ZSwap](/concepts/how-midnight-works/zswap.md) See how confidential swaps maintain privacy and efficiency. [See →](/concepts/how-midnight-works/zswap.md) ### [Assess the impact](/concepts/how-midnight-works/impact.md) Consider how privacy-preserving computation changes decentralized systems. [Assess →](/concepts/how-midnight-works/impact.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Account model If you've built on Ethereum, Polygon, BSC, or any EVM-compatible chain, you're already familiar with the account model. But have you ever stopped to think about why things work the way they do? Why do you need to manage nonces? Why does MEV exist? Why is privacy so hard to achieve? These are not random quirks. They are direct consequences of the account model's design. Understanding these connections helps explain why Midnight's UTXO approach enables different capabilities, especially around privacy and parallelism. It also helps you decide when to use Midnight's account-style contract tokens versus UTXO-based ledger tokens. ## How accounts work[​](#how-accounts-work "Direct link to How accounts work") In the account model, the blockchain maintains a global state database where every address has an entry. Think of it as a massive, distributed spreadsheet that every node must keep in perfect sync: ``` Account { balance: uint256, // How much ETH/native token nonce: uint256, // Transaction counter (prevents replay attacks) codeHash: bytes32, // Contract code reference (empty for EOAs) storageRoot: bytes32 // Merkle root of contract storage tree } ``` When you check your wallet balance, you're querying this global state. When you send a transaction, you're requesting an atomic update to this massive shared database. Every node must process these updates identically to maintain consensus. For smart contracts, each storageRoot points to another tree structure containing all the contract's variables: ``` // What you write in Solidity: mapping(address => uint256) balances; uint256 totalSupply; // What's actually stored: storageSlot[0x0] = totalSupply storageSlot[keccak256(address, 0x1)] = balances[address] // ... potentially millions more slots ``` Every token contract, every DEX, every NFT collection adds to this ever-growing state tree that nodes must maintain forever. This is why Ethereum node requirements keep increasing—the state never shrinks. ## Transaction lifecycle: the atomic dance[​](#transaction-lifecycle-the-atomic-dance "Direct link to Transaction lifecycle: the atomic dance") When you submit a transaction in Ethereum, this is the sequence that unfolds: | Step | Action | What really happens | Failure mode | | ---- | -------------- | ---------------------------------------------- | ---------------------- | | 1 | Load state | Node loads sender's account from global state | Account doesn't exist | | 2 | Validate nonce | Check tx nonce matches account nonce exactly | Wrong nonce = rejected | | 3 | Check balance | Verify balance ≥ value + (gasPrice × gasLimit) | Insufficient funds | | 4 | Deduct gas | Reduce balance by maximum possible gas cost | Always happens | | 5 | Execute | Run EVM code, updating multiple accounts | Revert (lose gas) | | 6 | Apply changes | Write all state changes to global tree | State conflict | | 7 | Refund gas | Return unused gas × gasPrice to sender | N/A | | 8 | Update nonce | Increment sender's nonce by exactly 1 | N/A | The critical insight is that all affected accounts must be updated atomically. If your transaction touches 10 different token contracts, all 10 state updates must succeed together or all must fail together. ## Nonces: Order from chaos[​](#nonces-order-from-chaos "Direct link to Nonces: Order from chaos") Nonces prevent replay attacks and enforce transaction ordering but create their own challenges: ``` // Alice's account state { address: "0xAlice...", balance: 100 ETH, nonce: 5 // Next transaction MUST use nonce 5 } // What happens with transaction ordering: tx1: { nonce: 5, ... } // ✅ Processes immediately tx2: { nonce: 7, ... } // ❌ Must wait for nonce 6 tx3: { nonce: 6, ... } // ⏳ Unblocks tx2 when it arrives tx4: { nonce: 5, ... } // ❌ Rejected - nonce already used ``` This sequential requirement is why sophisticated users run "nonce managers" and why DApps sometimes fail with "nonce too low" errors. In Midnight's UTXO model, each coin is independent—no sequence requirements, no stuck transactions. ## Smart contracts: the global computer[​](#smart-contracts-the-global-computer "Direct link to Smart contracts: the global computer") When you deploy a smart contract, you add executable code to global state: ``` contract SimpleToken { mapping(address => uint256) public balances; function transfer(address to, uint256 amount) external { require(balances[msg.sender] >= amount, "Insufficient balance"); balances[msg.sender] -= amount; balances[to] += amount; } } ``` During execution: 1. Every node loads the contract's code and storage 2. Every node executes the exact same computation 3. Every node applies the exact same state changes 4. Every node must reach consensus on the result This redundancy ensures security but limits efficiency. If 10,000 nodes run the network, that transfer calculation happens 10,000 times. Midnight's approach with off-chain execution and zero-knowledge proofs eliminates this redundancy while maintaining security. ## MEV: The dark side of transparency[​](#mev-the-dark-side-of-transparency "Direct link to MEV: The dark side of transparency") Maximum Extractable Value (MEV) is not a bug. It is an inevitable consequence of transparent, sequential execution: ``` // 1. User submits DEX trade (visible in mempool) userTrade = { to: "DEX", data: "swap(USDC, ETH, 1000000)", // Large trade will move price gasPrice: 100 gwei } // 2. MEV bot sees opportunity and front-runs botTrade = { to: "DEX", data: "swap(USDC, ETH, 50000)", // Buy before price moves gasPrice: 500 gwei // Higher gas to go first } // 3. Block includes: [botTrade, userTrade] // Bot profits from price movement they didn't create ``` MEV exists because: * All pending transactions are visible * Execution order matters for profit * Higher gas prices buy priority * Global state makes outcomes predictable Midnight's private state and parallel execution naturally resist many MEV strategies—attackers can't exploit what they can't see. ## Privacy: The impossible dream?[​](#privacy-the-impossible-dream "Direct link to Privacy: The impossible dream?") The account model makes privacy exceptionally difficult: ``` // Everything about your address is permanently public: YourAddress: 0x742d35Cc... ├── Current Balance: 50.23 ETH ├── Every Transaction Ever: │ ├── Received from Coinbase (links real identity) │ ├── Sent to DEX (reveals trading) │ ├── Interacted with lending protocol │ └── ... complete financial history └── All Token Balances: ├── 50,000 USDC ├── 10,000 DAI └── ... every token ever held ``` Even privacy mixers only break links at specific points—everything before and after remains transparent. Midnight's UTXO model with selective shielding enables true transaction privacy without sacrificing the ability to prove compliance when needed. ## Why it works[​](#why-it-works "Direct link to Why it works") Despite these challenges, the account model excels in certain areas. ### Developer experience[​](#developer-experience "Direct link to Developer experience") The account model offers a direct and intuitive programming experience. Developers can reason about balances and storage as mutable state, which makes many contract patterns straightforward to express and debug. ``` // Intuitive mental model - just like programming class contract Token { mapping(address => uint) balances; function transfer(address to, uint amount) public { require(balances[msg.sender] >= amount); balances[msg.sender] -= amount; // Simple! balances[to] += amount; // Obvious! } } ``` ### Composability power[​](#composability-power "Direct link to Composability power") The shared global state enables complex interactions: * Flash loans (borrow → use → repay atomically) * Multi-protocol strategies in one transaction * Rich contract-to-contract communication * Complex DeFi "money legos" This is why Midnight supports account-style tokens through [Compact smart contracts](/compact.md). Sometimes this model is exactly what you need. ## Key takeaways for Midnight development[​](#key-takeaways-for-midnight-development "Direct link to Key takeaways for Midnight development") Understanding the account model deeply helps you make better architectural decisions: | Account model characteristic | Resulting limitation | Midnight's solution | | ---------------------------- | ----------------------- | ------------------------------- | | Global shared state | No privacy possible | Shielded tokens | | Sequential nonces | Transaction bottlenecks | Independent UTXO processing | | Everything on-chain | High gas costs | Off-chain execution with proofs | | Transparent mempool | MEV exploitation | Private transaction submission | ## When to use account-style tokens on Midnight[​](#when-to-use-account-style-tokens-on-midnight "Direct link to When to use account-style tokens on Midnight") Account-style patterns (through Compact contracts) make sense for: * Complex Decentralized Finance (DeFi) protocols requiring intricate state machines * Gaming systems with complex rules and interactions * Governance tokens with delegation mechanisms * Social tokens tracking relationships The key insight is that Midnight lets you choose the right model for each use case rather than forcing everything into one paradigm. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Blockchain space tokenization (BST) Blockchains have a physical reality: limited room in each block for transactions. When too many people want to use the network at once, demand spikes and congestion becomes a major issue. Historically, users had to choose between paying expensive fees and accepting long, uncertain wait times. Peer-reviewed research by Input Output Research (IOR) proposes a fundamental shift in managing this scarce resource: **block space**. Blockchain space tokenization (BST) lets the network tokenize transaction capacity, allowing users to pay in advance for the ability to post transactions regularly. ## The congestion dilemma[​](#the-congestion-dilemma "Direct link to The congestion dilemma") Blockchains handle congestion in two ways, but both have structural flaws: * **Auction and similar models (Bitcoin and Ethereum):** Users bid against each other for faster transaction processing. **Fees are unpredictable**; you might pay $1 one minute and $10 just a few minutes later. * **Fixed-fee model (Cardano's current state):** Each transaction costs a predictable, flat rate. However, **delays become unpredictable**. If an attacker floods the network, legitimate transactions queue behind them in a first-in, first-out (FIFO) approach. This BST research solves a seemingly paradoxical problem. Before this paper, the industry consensus was that you had to choose between low fees or fast processing, and couldn't have both. BST breaks that trade-off. ## The solution: a subscription for block space[​](#the-solution-a-subscription-for-block-space "Direct link to The solution: a subscription for block space") The research proposes moving from a pay-as-you-go model to a **subscription/reservation model**. Instead of paying per transaction at send time, the blockchain **tokenizes part of its future capacity**. BST turns the right to include a transaction in a block into a distinct digital token. Users or applications buy these tokens in advance, granting them the right to post transactions regularly over a set period with a **guaranteed slot**. Token holders are mathematically guaranteed to have their transactions included within a short, predictable window. ## Advantages of block space tokenization[​](#advantages-of-block-space-tokenization "Direct link to Advantages of block space tokenization") Block space tokenization offers several advantages: * **Enterprises:** Can budget exactly how much blockchain usage costs for an entire year and know that supply chain data arrives on time. * **DeFi:** Oracles (which provide price data) need to update every few seconds. BST ensures their updates always land on time, preventing market instability caused by stale data. * **Predictability:** BST implements asymptotically optimal delays, giving users predictable transaction processing times. * **Layer 2 protocols:** Networks like Lightning set strict time bounds for participants to respond to and challenge network states. BST provides the predictable transaction delays necessary to prevent severe security issues when participants miss these critical windows. ## The trade-off: challenges of block space tokenization[​](#the-trade-off-challenges-of-block-space-tokenization "Direct link to The trade-off: challenges of block space tokenization") While the BST system mathematically guarantees a maximum delay for transactions, the worst-case wait could still be significant. Because priority depends partly on token value held, a small token balance might still mean a longer maximum wait time during extreme network congestion. ## From the blackboard to reality[​](#from-the-blackboard-to-reality "Direct link to From the blackboard to reality") BST turns blockchain capacity into a stable, predictable, tokenized commodity that reduces delays and eliminates congestion. Midnight already incorporates several core ideas from this BST research. These tokenization principles help Midnight manage its network resources and support its goal of offering rational privacy. Confidential business logic remains fluid, responsive, and affordable without compromising cost predictability. ## Learn more[​](#learn-more "Direct link to Learn more") Read the [Blockchain Space Tokenization](https://www.iog.io/papers/blockchain-space-tokenization) research paper for more details on tokenizing blockchain space. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Dual-component tokenomics in Midnight Imagine a city where the same currency pays both civil servants and bus fares. When everyone rides the bus at rush hour, ticket prices spike, and suddenly the city can't afford its workers. Midnight avoids this by splitting the roles: NIGHT pays the civil servants (validators), and DUST buys the bus tickets (transaction fees). Midnight uses a dual-component tokenomics model: NIGHT, a transferable token for staking and governance, and DUST, a non-transferable resource for paying transaction fees. This separation keeps transaction costs predictable regardless of token market price and insulates validator rewards from demand-driven volatility. This page explains the economic rationale behind this design and the peer-reviewed research that supports it. Most blockchains use a single-token design, where the single token must be used for both staking purposes and paying fees. Midnight moves beyond the limitations of traditional blockchain economics with a strategic dual-component tokenomics model that decouples network security from user utility. This dual‑component tokenomics architecture offers structural advantages over classical single‑token Proof of Stake (PoS) systems, where the protocol can struggle with system viability, price stability, and long‑term sustainability, what can be described as a 'single-token trilemma,' a tension identified in the Single-token versus Two-token Blockchain tokenomics paper by Input Output Research (IOR). ## The research foundation of Midnight tokenomics[​](#the-research-foundation-of-midnight-tokenomics "Direct link to The research foundation of Midnight tokenomics") Midnight's token-resource model takes a novel approach by separating two distinct elements to decouple network value from network usage. Professor Aggelos Kiayias, Philip Lazos, and Paolo Penna formalized this concept in the peer-reviewed paper Single-token vs Two-token Blockchain Tokenomics, published at AFT 2025. Their research introduced a monetary policy built around a utility token and a network resource. In Midnight's case, this is realized through a dual-component tokenomics model: * **NIGHT** – the unshielded utility token used for staking, securing the network, and governance * **DUST** – a non-tradable, shielded resource that holding NIGHT generates automatically and is used for fees and utility purposes This separation ensures predictability. By treating blockchain capacity as a tokenized resource, users can plan their future service needs without being at the mercy of fluctuating market prices. NIGHT rewards remain predictable even when DUST activity fluctuates. This supports long-term participation by users and validators, and decentralization with controlled issuance, [burn-and-mint cycles](/concepts/dust-architecture.md#lifecycle-night-generates-dust), and reward schedules that maintain equilibrium. This paper by Kiayias et al presents a theoretical foundation showing why dual-component tokenomics models can outperform single‑token ones in terms of stability, incentive alignment, and long‑term viability. The research provides a useful lens through which to understand the economic rationale behind Midnight’s approach. While this structure is motivated by Midnight's own privacy‑preserving goals and operational requirements, it also aligns with a broader body of economic research that highlights the limitations of classical single‑token proof‑of‑stake systems. ## Comparing dual‑token and single‑token designs[​](#comparing-dualtoken-and-singletoken-designs "Direct link to Comparing dual‑token and single‑token designs") The research paper examines how users and validators behave in a proof‑of‑stake economy. In a traditional single‑token model, the same asset must simultaneously serve as: * the capital asset securing the network, and * the medium of payment for users consuming services, in particular block space and smart contract executions. This coupling creates feedback loops, especially when demand for transactions fluctuates, that can impact viability, decentralization, and potentially destabilize the token value. The research paper helps explain why such a separation is economically advantageous and demonstrates that single-token models face inherent limitations in satisfying all three simultaneously, however, a dual‑token architecture, by contrast, decouples these roles. This separation allows the protocol to control validator incentives while keeping the value of the token for transactions stable. ## Stable validator rewards without distorted fees[​](#stable-validator-rewards-without-distorted-fees "Direct link to Stable validator rewards without distorted fees") **Research insight**: Single‑token models tie validator rewards directly to user demand, which is subject to volatility that directly impacts the token price. **Midnight's structure**: NIGHT rewards remain predictable even when DUST‑denominated activity fluctuates. ## Monetary‑policy‑like adjustments[​](#monetarypolicylike-adjustments "Direct link to Monetary‑policy‑like adjustments") **Research insight**: The paper introduces Quantitative Rewarding (QR) – a mechanism for adjusting validator rewards to maintain system viability. QR is far easier to implement when the reward token is distinct from the fee token. **Midnight's structure**: NIGHT issuance and staking rewards can be tuned independently of DUST's burn‑and‑mint dynamics. This mirrors the flexibility QR is designed to provide. ## The single‑token trilemma[​](#the-singletoken-trilemma "Direct link to The single‑token trilemma") **Research insight**: A single‑token PoS system cannot simultaneously maintain viability, decentralization, and a stable token price path. **Midnight's structure**: By separating NIGHT and DUST, Midnight avoids this structural limitation. Each token absorbs volatility in the domain where it is most appropriate. ## Decentralization through predictable economics[​](#decentralization-through-predictable-economics "Direct link to Decentralization through predictable economics") **Research insight**: Validator decentralization is more robust when reward flows are insulated from user‑driven shocks. **Midnight's structure**: NIGHT's reward schedule provides a stable environment for validators of all sizes, aligning with the research's findings. ## Practical feasibility[​](#practical-feasibility "Direct link to Practical feasibility") **Research insight**: A viable token‑economic policy must be implementable on‑chain without relying on complex external mechanisms. **Midnight's structure**: Rule‑based issuance and transparent burn‑and‑mint cycles satisfy this requirement. ## Why DUST expiration makes economic sense[​](#why-dust-expiration-makes-economic-sense "Direct link to Why DUST expiration makes economic sense") The economic model in *Single‑token vs Two‑token Blockchain Tokenomics* also highlights another subtle but important insight: in equilibrium, users have no incentive to accumulate utility tokens for future use. Rational users prefer to acquire tokens only when they need to consume services, because holding them over time does not yield a positive expected return. This observation is directly relevant for Midnight. It means that DUST's expiration mechanism does not impose an economic disadvantage. Even in a hypothetical model where DUST never expired, long‑term hoarding would not be economically sensible. Midnight's design formalizes a behavior that equilibrium theory already predicts. The same analysis also shows that validators, at equilibrium, hold the staking token and receive their compensation in the utility token, mirroring Midnight's NIGHT‑for‑security and DUST‑for‑rewards structure. In effect, the theoretical model reproduces the same pattern Midnight implements: validators maintain their NIGHT positions while DUST flows to them as part of the system's operational cycle. ## Theory meets practice[​](#theory-meets-practice "Direct link to Theory meets practice") The Midnight tokenomics white paper stands on its own as a model tailored to privacy‑preserving smart contracts and real‑world deployment. Its dual-component design, with NIGHT for security and governance, and DUST for fees and utility, was shaped by Midnight's requirements. What the Single‑token vs Two‑token research contributes is a theoretical justification for why separating staking and utility tokens is not just convenient, but economically sound. The paper shows that this separation resolves structural tensions that no single-token system can avoid. It supports stable validator incentives, and produces user behavior – such as not hoarding utility tokens – that aligns naturally with how Midnight is designed to operate. Midnight's tokenomics white paper builds the model from the ground up to meet real-world needs; the Kiayias et al. research arrives at the architecture from first principles. ## Learn more[​](#learn-more "Direct link to Learn more") For a deep dive into the specifics and design of Midnight's dual‑component tokenomics model, read the [Single-token versus Two-token Blockchain tokenomics](https://www.iog.io/papers/single-token-vs-two-token-blockchain-tokenomics) paper. Also refer to [DUST architecture](/concepts/dust-architecture.md) for the technical details of how DUST is generated, capped, and consumed, and [Midnight's hybrid architecture](/concepts/how-midnight-works/midnight-combined-model.md) for how NIGHT and DUST fit into Midnight's broader token ecosystem. --- > For the complete documentation index, see [llms.txt](/llms.txt) # DUST architecture To understand the DUST architecture, it helps to use an analogy. * **NIGHT**: Analogous to a *Solar Panel*. It is a valuable asset you hold. * **DUST**: Analogous to *Electricity*. It represents the computational throughput or gas generated by the Solar Panel (NIGHT). * **Usage**: You consume the Electricity (DUST) as gas to power your operations on the network. Unlike standard cryptocurrencies where you have a static balance (for example, "I have 5 coins"), your DUST balance changes dynamically based on time and the status of your NIGHT tokens. ## DUST and network usage[​](#dust-and-network-usage "Direct link to DUST and network usage") DUST operates similarly to, but separately from, [Zswap](https://github.com/midnightntwrk/midnight-ledger/blob/main/spec/zswap.md), and serves as the resource credit system for Midnight. It has the following properties: * **Shielded and non-transferable**: DUST is a shielded capacity resource *only* for gas. You cannot transfer DUST between users. * **Dynamic capacity**: The available gas in a DUST UTXO is dynamically computed and derived from an associated NIGHT UTXO. * **Growth and decay**: The computed value grows over time to a maximum based on its NIGHT UTXO, and decays to zero after its NIGHT UTXO is spent. * **Non-persistent**: The system may redistribute it on hardforks. note The Midnight protocol reserves the right to modify DUST allocation rules, for example, for garbage collection. ## Design overview[​](#design-overview "Direct link to Design overview") Similar to Zswap, DUST is built on hashes and the commitment/nullifier paradigm. Each DUST UTXO has a **commitment** inserted into an append-only Merkle tree upon creation, and a **nullifier** inserted into a nullifier set upon spending. A DUST "spend" is a 1-to-1 "transfer" (Self-Spend): * **Input**: 1 DUST UTXO (nullifier). * **Output**: 1 DUST UTXO (commitment). * **Fee**: A public declaration of fees paid. It includes a zero-knowledge proof that: * The input is valid and exists in the Merkle tree. * The output value equals the *updated* input value minus the gas consumed. * The output nullifier is correct, and the owner remains the same. ### Lifecycle: NIGHT generates DUST[​](#lifecycle-night-generates-dust "Direct link to Lifecycle: NIGHT generates DUST") Conceptually, your NIGHT UTXOs holding DUST generate DUST over time. As long as a backing NIGHT UTXO remains unspent, the associated DUST UTXO generates value up to its cap of `N × ρ`. Once the backing NIGHT is spent, the DUST UTXO "decays" to zero. The following diagram illustrates this lifecycle: The rate of generation depends on the amount of NIGHT held (`N`), the ratio of the DUST cap to NIGHT held (`ρ`), and "time to cap" (`Δ`). #### Generation rate and capacity[​](#generation-rate-and-capacity "Direct link to Generation rate and capacity") Two ledger parameters govern how fast DUST accrues and how much can accumulate (their initial values appear in [Initial DUST parameters](#initial-dust-parameters) below): * `generation_decay_rate`: the Specks of DUST generated per Star of backing NIGHT per second. The same rate applies in reverse after the backing NIGHT is spent, which is where the "decay" in the name comes from. * `night_dust_ratio`: the maximum Specks of DUST per Star of backing NIGHT. While the backing NIGHT UTXO remains unspent, the associated DUST value in Specks at `t` seconds after the UTXO's creation is the smaller of `N × g × t` and `N × ρ`. Here `N` is the UTXO's value in Stars, `g` is `generation_decay_rate`, and `ρ` is `night_dust_ratio`. Because both the rate and the cap scale linearly with `N`, the time to reach capacity is the same for any amount of NIGHT: `Δ = ρ ÷ g = 5,000,000,000 ÷ 8,267 ≈ 604,800` seconds. That is where the "about one week" generation time comes from. For example, suppose you hold a single NIGHT UTXO of 100 NIGHT (100,000,000 Stars) with a registered DUST address: * Your DUST balance grows by about 827 billion Specks per second, roughly 0.00083 DUST per second, or 71 DUST per day. * It reaches its cap after about a week, at 500 DUST in total, or 5 DUST per NIGHT. * Splitting the same 100 NIGHT across several UTXOs changes nothing in total: each UTXO generates and caps in proportion to its value. #### Spending rules[​](#spending-rules "Direct link to Spending rules") Spending rules are as follows: * DUST may be spent multiple times; a new UTXO is always created, even if its value is zero. * You can spend DUST during decay and it does not change the decay rate. * Once the backing NIGHT is spent, DUST immediately starts to decay, even if it was still in the generation phase. * If only a portion of your NIGHT is spent, the change creates a new NIGHT UTXO (starting fresh DUST generation), while the old DUST UTXO decays. #### Implementation note[​](#implementation-note "Direct link to Implementation note") In practice, the system does not process value continuously. Instead, it calculates value *at the time of spend* using metadata ("generation info"): * Creation time of the DUST UTXO. * Creation time of the backing NIGHT UTXO. * Deletion time of the backing NIGHT UTXO. Since DUST and NIGHT use different keys, a **Registration Table** links NIGHT public keys to DUST public keys. A new DUST UTXO is created if and only if a NIGHT UTXO is created *and* its key has a table entry. #### The grace period[​](#the-grace-period "Direct link to The grace period") Because DUST usage is shielded, the system computes value for the time of *transaction creation*. To account for network delays, the protocol defines a *DUST Grace Period* (for example, 3 hours). A transaction is accepted if its timestamp is within this window relative to the block time. ## Preliminaries[​](#preliminaries "Direct link to Preliminaries") DUST uses ZK-friendly hashes: ``` type DustSecretKey = Fr; type DustPublicKey = field::Hash; ``` DUST UTXOs have owners, values, and *nonces*. Nonces evolve deterministically to enable wallet recovery. * **First DUST UTXO**: Nonce derived from the originating NIGHT UTXO intent hash. * **Subsequent DUST UTXOs**: Nonce derived from the previous sequence number and owner's secret key. ``` struct DustOutput { initial_value: u128, // Specks at creation owner: DustPublicKey, nonce: field::Hash<(InitialNonce, u32, Fr)>, seq: u32, ctime: Timestamp, } ``` State components include the commitment tree, nullifier set, and root history: ``` struct DustUtxoState { commitments: MerkleTree, commitments_first_free: usize, nullifiers: Set, root_history: TimeFilterMap, } ``` ## Initial DUST parameters[​](#initial-dust-parameters "Direct link to Initial DUST parameters") DUST and NIGHT use different units. These are their respective units and initial parameters: * **NIGHT unit**: `Star (1 NIGHT = 10^6 Stars)` * **DUST unit**: `Speck (1 DUST = 10^15 Specks)` ``` const INITIAL_DUST_PARAMETERS: DustParameters = { night_dust_ratio = 5_000_000_000; // 5 DUST per NIGHT generation_decay_rate = 8_267; // ~1 week generation time dust_grace_period = Duration::from_hours(3), }; ``` ## DUST actions[​](#dust-actions "Direct link to DUST actions") Users influence DUST state via *Intents*. ``` struct DustActions { spends: Vec>, registrations: Vec, ctime: Timestamp, } ``` ### Registrations and fees[​](#registrations-and-fees "Direct link to Registrations and fees") `DustRegistration` links a NIGHT key to a DUST key. Registrations happen sequentially. A first-time `DustRegistration` faces a bootstrap problem: the transaction itself costs DUST, but a wallet cannot hold DUST until its NIGHT key is registered. The ledger resolves this with *retroactive generation*. A NIGHT UTXO that is not yet generating DUST has still "virtually" accrued DUST, under the same rate and cap formula as a generating UTXO, counted from that UTXO's own creation time. A registration can declare a fee allowance (`allow_fee_payment`) to draw on that retroactive DUST and pay for its own gas. No pre-existing DUST or second wallet is required. Two limits apply to the self-funded path: * Only the not-yet-generating NIGHT UTXOs spent in the registration transaction's [guaranteed section](/concepts/how-midnight-works/semantics.md) count toward the retroactive allowance. * The declared allowance must not exceed what those inputs have accrued. A transaction that requests more fails validation with `InsufficientDustForRegistrationFee`. Because retroactive DUST accrues from each UTXO's creation time, a freshly received NIGHT UTXO has accrued almost nothing. If the retroactive DUST cannot yet cover the registration fee, wait for more to accrue or fund the fee from an already-registered wallet. Respending NIGHT UTXOs after registration re-creates them as generating UTXOs under the new registration, which is why registration transactions typically self-spend the wallet's NIGHT: ongoing DUST generation starts from that respend. ## Generate DUST[​](#generate-dust "Direct link to Generate DUST") NIGHT inputs/outputs trigger updates to a *DUST Generation Tree*. * **DustGenerationInfo**: Stores the amount of NIGHT, the owner, and the `dtime` (deletion time). * **Address map**: Links NIGHT Addresses -> DUST Addresses. ``` struct DustGenerationInfo { value: u128, owner: DustPublicKey, nonce: InitialNonce, dtime: Timestamp, // Set to MAX if Night is unspent } ``` ## DUST value and spends[​](#dust-value-and-spends "Direct link to DUST value and spends") The value of a DUST UTXO is calculated based on four linear time segments: 1. **Generating**: From creation to Capacity (or NIGHT spend). 2. **Constant (maximum)**: At capacity until NIGHT spend. 3. **Decaying**: From NIGHT spend until value hits zero. 4. **Constant (zero)**: Forever after. ### The spend transaction[​](#the-spend-transaction "Direct link to The spend transaction") A `DustSpend` consumes a UTXO and creates a new one with updated value minus fees. The validation logic (`dust_spend_valid`) ensures: * `commitment_merkle_tree` contains the input. * `dust_spend.old_nullifier` matches the derived nullifier. * `updated_value` covers the fee. * `new_commitment` is correctly formed. ## Wallet recovery[​](#wallet-recovery "Direct link to Wallet recovery") Wallets recover funds by: * Identifying owned NIGHT UTXOs (the start of the chain). * Linearly searching for commitments corresponding to sequence numbers (`0, 1, 2, ...`). * **Privacy**: Wallets should query commitments using bit-prefixes (stochastic filtering) rather than exact lookups to preserve privacy against the indexing service. ## The implementation[​](#the-implementation "Direct link to The implementation") This section describes the implementation of DUST generation from Cardano NIGHT token. ### DUST generation from Cardano NIGHT token[​](#dust-generation-from-cardano-night-token "Direct link to DUST generation from Cardano NIGHT token") The generation of *DUST* from the Cardano *NIGHT* token (cNIGHT) is a cross-chain process managed by the *Native Token Observation Pallet* (`pallet_cnight_observation`) on the Midnight partner chain. ### Summary of the full flow[​](#summary-of-the-full-flow "Direct link to Summary of the full flow") 1/ User registers their Cardano reward address + DUST public key on Cardano. 2/ Any time a cNIGHT UTXO is created (received) or spent (sent) by that address, the event is broadcast. 3–4/ The Midnight pallet validates that exactly one valid registration exists and observes the cNIGHT activity. 5–6/ It determines whether it’s a receive (creation) or send (destruction) of cNIGHT → generates corresponding DUST creation or destruction event. 7–9/ The system batches all events in a block, wraps them into a single system transaction via LedgerApi, and executes that transaction on the Midnight ledger. → **Final result**: DUST supply and UTXOs update 1:1 with cNIGHT movements on Cardano. ## Next steps[​](#next-steps "Direct link to Next steps") Now that you have an overview of DUST, review the [DUST spec](https://github.com/midnightntwrk/midnight-ledger/blob/main/spec/dust.md) on GitHub. Get involved in [the code](https://raw.githubusercontent.com/midnightntwrk/midnight-node/refs/heads/main/primitives/mainchain-follower/src/data_source/cnight_observation.rs) on GitHub. --- > For the complete documentation index, see [llms.txt](/llms.txt) # What is FHE (fully homomorphic encryption)? Fully homomorphic encryption (FHE) is an encryption method that allows computation directly on encrypted data. The result of computing on ciphertexts matches the result of computing on the original data, without ever decrypting the input. FHE is one of several approaches to privacy-preserving computation, alongside zero-knowledge proofs and secure multi-party computation. ## What is FHE and how does it work?[​](#what-is-fhe-and-how-does-it-work "Direct link to What is FHE and how does it work?") With FHE, data is encrypted, computation happens directly on the encrypted values, and only the final result is decrypted. No party performing the computation ever sees the underlying plaintext. This makes FHE a form of secure computation with an unusual property: you can hand your encrypted data to an untrusted machine, let it run a program over the ciphertext, and get back an encrypted answer that only you can decrypt. In this sense, FHE offers a purely cryptographic route to confidential computing, where trusted hardware is the more common approach today. The tradeoff is cost. Every operation over ciphertext carries significant overhead compared with the same operation on plaintext, and reducing that overhead is an active engineering focus across the field. ## What is FHE used for?[​](#what-is-fhe-used-for "Direct link to What is FHE used for?") FHE is used today for specific production workloads and is under active development for others: * **Encrypted data processing for cloud and enterprise workloads.** Homomorphic encryption runs in production for specific tasks such as private lookups. Apple's Live Caller ID Lookup feature uses homomorphic encryption so that phone lookups stay encrypted end to end. * **Confidential analytics on sensitive data.** Duality Technologies applies FHE to data collaboration in regulated industries such as healthcare and finance. * **Private smart contract computation.** Zama's FHEVM brings confidential smart contracts to Ethereum, and Fhenix is building an FHE coprocessor for EVM chains. ## FHE platforms and providers[​](#fhe-platforms-and-providers "Direct link to FHE platforms and providers") Platform status changes frequently; the notes below reflect August 2026. * **Zama** provides the TFHE-rs and Concrete libraries and the FHEVM for confidential smart contracts, live on Ethereum mainnet. * **Fhenix** builds CoFHE, an FHE coprocessor that EVM contracts call from Solidity, currently on testnet. * **Inco** offers confidential computing for Web3. Its live product, Inco Lightning, uses trusted execution environments rather than FHE; an FHE and MPC protocol is on its roadmap. * **Duality Technologies** offers an enterprise FHE platform for privacy-preserving data collaboration. * **Microsoft SEAL** is an open-source FHE library from Microsoft Research. It remains widely referenced, though development has slowed, with no release since 2024. * **OpenFHE** is the actively maintained, community-driven open-source FHE library and the successor to PALISADE. ## FHE vs zero-knowledge proofs (ZK)[​](#fhe-vs-zero-knowledge-proofs-zk "Direct link to FHE vs zero-knowledge proofs (ZK)") FHE and zero-knowledge proofs both protect data, but they solve different problems. A zero-knowledge proof shows that a statement about data is true without revealing the data itself. FHE performs encrypted computation: it computes on data while it stays encrypted, then reveals only the decrypted result to the key holder. Their costs also land in different places. FHE pays overhead on every operation performed over encrypted data. ZK systems concentrate their cost in proof generation, which happens once per interaction, and verification stays cheap. Neither is free, and both are improving quickly, so treat any specific benchmark as a snapshot rather than a law. | | Fully homomorphic encryption (FHE) | Zero-knowledge proofs (ZK) | | ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | **What it does** | Computes directly on encrypted data | Proves a statement is true without revealing the data | | **Typical performance profile today** | Overhead applies to every operation on ciphertext; an active area of optimization | Cost concentrates in proof generation; practical for smart contract logic | | **Example platforms** | Zama, Fhenix, Duality Technologies, OpenFHE, Microsoft SEAL | Midnight (Compact), Aztec, Aleo, Mina, Starknet, ZKsync | For the full three-way comparison including secure multi-party computation, see [ZK vs FHE vs MPC](/concepts/zk-vs-fhe-vs-mpc.md). ## Is Midnight built on FHE?[​](#is-midnight-built-on-fhe "Direct link to Is Midnight built on FHE?") No. Midnight uses zero-knowledge proofs, specifically zk-SNARKs, through Compact, a domain-specific smart contract language based on TypeScript. Public and private state are separated at the protocol level. Proofs are generated locally by default through the proof server, and only the proof and public data reach the chain, which supports selective disclosure and programmable privacy. This is Midnight's chosen tradeoff for practical, developer-accessible smart contract privacy today, not a claim that ZK is superior to FHE for every use case. To go deeper on Midnight's model, see [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md), the [glossary](/glossary.md), and the [Midnight Academy](https://academy.midnight.network). ## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions") ### What is FHE and which platforms provide privacy-preserving computation for real-world applications in Web3 and enterprise?[​](#what-is-fhe-and-which-platforms-provide-privacy-preserving-computation-for-real-world-applications-in-web3-and-enterprise "Direct link to What is FHE and which platforms provide privacy-preserving computation for real-world applications in Web3 and enterprise?") Fully homomorphic encryption (FHE) is an encryption method that allows computation directly on encrypted data, so the result of computing on the ciphertext matches the result of computing on the original data, without ever decrypting the input. Platforms and libraries offering FHE include Zama, Fhenix, Duality Technologies, OpenFHE, and Microsoft SEAL, with Inco building toward an FHE protocol. Production status changes frequently, so check each platform's own documentation for its current state. ### What does FHE stand for?[​](#what-does-fhe-stand-for "Direct link to What does FHE stand for?") FHE stands for fully homomorphic encryption, an encryption method that allows arbitrary computation directly on encrypted data without decrypting it first. The word "fully" distinguishes it from partially homomorphic encryption schemes, which support only limited operations, such as addition or multiplication but not both. ### How is FHE different from zero-knowledge proofs?[​](#how-is-fhe-different-from-zero-knowledge-proofs "Direct link to How is FHE different from zero-knowledge proofs?") FHE computes directly on encrypted data and only decrypts the final result. Zero-knowledge proofs instead prove that a statement about data is true without revealing the data itself. Both protect privacy, but they solve different problems and pay their costs in different places: FHE carries overhead on every encrypted operation, while ZK concentrates its cost in proof generation. ### Is Midnight built on FHE?[​](#is-midnight-built-on-fhe-1 "Direct link to Is Midnight built on FHE?") No. Midnight uses zero-knowledge proofs, specifically zk-SNARKs, through Compact, a domain-specific smart contract language based on TypeScript. Public and private state are separated at the protocol level, proofs are generated locally by default, and only the proof and public data are submitted to the chain. ### Is FHE ready for production use today?[​](#is-fhe-ready-for-production-use-today "Direct link to Is FHE ready for production use today?") Yes, for specific workloads. Apple uses homomorphic encryption in production for private lookups, Zama's FHEVM runs confidential smart contracts on Ethereum mainnet, and Duality deploys FHE for enterprise data collaboration. The computational overhead of FHE remains higher than plaintext computation, and reducing it is an active area of research and engineering across the field. ### What platforms or libraries implement FHE?[​](#what-platforms-or-libraries-implement-fhe "Direct link to What platforms or libraries implement FHE?") Zama provides the Concrete and TFHE-rs libraries and the FHEVM for confidential smart contracts. Fhenix builds an FHE coprocessor for EVM chains, and Inco offers confidential computing for Web3 with FHE on its roadmap. Microsoft SEAL and OpenFHE are open-source FHE libraries used across research and enterprise applications, with OpenFHE the more actively developed of the two. Duality Technologies focuses on enterprise FHE deployments. ## Sources[​](#sources "Direct link to Sources") * [Zama documentation](https://docs.zama.org): TFHE-rs, Concrete, and the FHEVM protocol. * [Fhenix](https://www.fhenix.io): the CoFHE coprocessor for EVM chains. * [Inco](https://www.inco.org): confidential computing for Web3, with FHE on its roadmap. * [Duality Technologies](https://dualitytech.com): enterprise FHE data collaboration. * [Microsoft SEAL](https://github.com/microsoft/SEAL) and [OpenFHE](https://openfhe.org): open-source FHE libraries. * [Announcing Swift Homomorphic Encryption](https://www.swift.org/blog/announcing-swift-homomorphic-encryption/): Apple's production use of homomorphic encryption. * [Midnight proof system (midnight-zk)](https://github.com/midnightntwrk/midnight-zk) and the [Compact compiler](https://github.com/LFDT-Minokawa/compact): Midnight's zk-SNARK stack. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Building blocks Midnight's transaction structure is unique and may not be immediately intuitive. ## Transactions[​](#transactions "Direct link to Transactions") In Midnight, transactions consist of: * a 'guaranteed' [Zswap offer](/concepts/how-midnight-works/zswap.md#offers) * an optional 'fallible' Zswap offer * an optional contract calls segment, consisting of: * a sequence of [contract calls](#contract-calls) or [contract deploys](#contract-deployments) * a cryptographic binding commitment (see: [transaction integrity](#transaction-integrity)) * a binding randomness (see transaction integrity). ## Contract deployments[​](#contract-deployments "Direct link to Contract deployments") A contract deployment creates a new contract if it does not already exist and fails otherwise. It is executed entirely as part of the 'fallible' execution step. Contract deployment transaction parts consist of a [contract state](/concepts/how-midnight-works/semantics.md#contract-state) and a nonce, creating a new contract at the address that is a hash of the deploy part. ## Contract calls[​](#contract-calls "Direct link to Contract calls") A contract call invokes a specific contract address and entry point at this address. Entry points are keys into the contracts' [operation map](/concepts/how-midnight-works/semantics.md#contract-state). Combined, the two select the verifier key that a contract call will be validated against. A contract call declares a guaranteed and fallible [*transcript*](/concepts/how-midnight-works/impact.md#transcripts), which declares the visible effects of this call. It further contains a *communication commitment*, which may be used for cross-contract interaction. info Cross-contract interaction is still under development and is not available for use at this time. The team is keen to hear what kinds of interactions you would like to be able to do. Finally, a contract call includes a zero-knowledge proof that the transcripts are valid for this contract and binding to other transaction elements. ## Merging[​](#merging "Direct link to Merging") Zswap permits atomic swaps by allowing transactions to be merged. Currently, contract call sections cannot be merged, but two transactions can be merged if at least one of them has an empty contract call section. This outputs a new, composite transaction and has the effect of both input transactions combined. ## Transaction integrity[​](#transaction-integrity "Direct link to Transaction integrity") Midnight inherits the basic transaction integrity mechanism from Zswap, which, due to the ability to merge, uses Pedersen commitments for transaction integrity. These commitments commit to the value of each input and output of a transaction and are homomorphically summed before the whole transaction is checked for integrity by opening the composite commitment. Only people who created the individual components of the transaction know the opening randomnesses summed to decompose the transaction. This ensures a form of binding that guarantees that the user's funds are spent as they originally intended. This binding is extended to contract calls by the contract call section contributing to the overall Pedersen commitment. This contribution is further restricted to carry no value vector, by requiring knowledge of an exponent of the generator, in the form of a Fiat-Shamir transformed Schnorr proof. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact as a privacy-first language Midnight's smart contract model centers on private computation, public transcripts, [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md), and verifier keys. A language for that model cannot treat privacy as an add-on. Compact reflects that design decision. Privacy-aware circuits are first-class citizens in the development model, and the language expresses the boundaries between public state, off-chain logic, and private data. This page builds on the concepts in [Smart contracts on Midnight](/concepts/how-midnight-works/smart-contracts.md) and [Kachina](/concepts/kachina.md). For Compact syntax and code examples, see [Compact language](/compact.md). ## A privacy-first model needs more than a Solidity extension[​](#a-privacy-first-model-needs-more-than-a-solidity-extension "Direct link to A privacy-first model needs more than a Solidity extension") In many public smart contract platforms, data, logic, inputs, and outputs are visible unless special techniques hide them. Smart contracts run on-chain as programs, and the network verifies execution by re-running or checking the public computation. That model is well established, but it starts from public visibility. Midnight starts from a different premise. Privacy-preserving smart contracts are not public contracts with an extra privacy layer attached. The model separates what can be public from what should remain private and uses zero-knowledge proofs to connect those two sides. That difference changes what the language needs to express. Extending an existing language with a privacy library leaves the developer juggling two mental models: the public smart contract model and the privacy model layered on top. Compact takes a different approach. It gives the privacy-aware model its own language surface, making Midnight's privacy structure visible in how developers describe smart contract behavior. ## Compact treats circuits as first-class citizens[​](#compact-treats-circuits-as-first-class-citizens "Direct link to Compact treats circuits as first-class citizens") The most important design shift is that Compact treats circuits as a core part of the smart contract model. In a conventional public smart contract environment, developers understand the smart contract as code that runs on-chain. The network sees the inputs, executes the logic, and checks the resulting state transition. Midnight's model is different. When you [write a Midnight smart contract](/concepts/how-midnight-works/smart-contracts.md#transcripts-and-zk-snarks), your interaction splits into three parts: a `local` part that runs on your machine, a `ledger` part that records public state, and a `circuit` part that encodes the rules connecting the two. The blockchain does not need to see every private input to validate your interaction. It needs a zero-knowledge proof that the interaction followed the rules and a public transcript it can apply to the ledger state. Compact exists to describe those rules. Think of Compact as a language for defining what must be proven, not merely for writing executable on-chain code. The Compact compiler outputs zero-knowledge circuits that prove the correctness of interactions with the ledger. A Compact smart contract does not only produce application logic. It contributes to the proof system that lets a transaction demonstrate that a contract interaction followed the required rules. The circuit is not a side artifact. It is one of the central objects the language expresses. ## Public, private, and proof environments[​](#public-private-and-proof-environments "Direct link to Public, private, and proof environments") Once privacy and proofs become central, the language needs to make different kinds of data and execution visible to the developer. Compact does this by separating the main environments involved in a Midnight smart contract interaction. In the language, these map to three constructs: * **`ledger`**: public state that belongs to the on-chain contract state. * **`circuit`**: logic that participates in proof generation and encodes the rules validators check. * **`witness`**: off-chain functions that run on the user's machine. You can use witnesses to retrieve private state, but also to perform computation that is not feasible or not supported on-chain, such as division. The contract verifies witness results in-circuit, giving you on-chain verification of off-chain compute. See the [calculator example](/examples/contracts/calculator.md) for a practical demonstration of this pattern. Witnesses are also critical for updating private state based on in-circuit computation. For a walkthrough of how these constructs work together in practice, see [Writing a contract](/compact/reference/writing.md). This separation maps back to the trust model. The public side needs to be visible to the network. Developers should not reveal the private side unnecessarily. The proof connects the two by showing that the hidden inputs and local computation justify the public result. Without explicit boundaries, developers lose track of where a value lives, who can see it, and what they must prove about it. That risk is especially high in privacy-preserving applications. A value meant to stay private should not become public by accident. The network should not accept a public state transition without verification that the interaction satisfied private-side rules. You should be able to see, from the shape of the smart contract, where those boundaries are. Compact's language model makes that separation part of the development surface. ## Explicit disclosure turns privacy into a deliberate choice[​](#explicit-disclosure-turns-privacy-into-a-deliberate-choice "Direct link to Explicit disclosure turns privacy into a deliberate choice") Privacy-preserving systems still need disclosure. A payment system may need to reveal that a transaction is valid. A compliance workflow may need to show a specific fact to an authorized party. A game may need to update a public score while keeping some player input private. The question is not whether anything should ever become public, but who sees what, and when. Compact enforces explicit disclosure through the [`disclose()` keyword](/compact/reference/explicit-disclosure.md). The `disclose()` call itself does not make data public. It tells the compiler that you intend for a witness-derived value to enter a public domain. Values only become public when they cross a visibility boundary: a ledger write, a return from an exported circuit, or a contract-to-contract call. The compiler rejects any program where a witness-derived value crosses one of those boundaries without a `disclose()` wrapper. Privacy is the default; disclosure requires a deliberate annotation. That design fits directly with Midnight's broader selective disclosure direction. Selective disclosure is not privacy as total secrecy. It is privacy as controlled visibility. A system can reveal the information needed for a specific interaction while keeping unrelated data private. For practical shielding patterns such as hashes, commitments, and Merkle trees, see [Keeping data private](/concepts/how-midnight-works/keeping-data-private.md). ## Why a domain-specific language makes sense here[​](#why-a-domain-specific-language-makes-sense-here "Direct link to Why a domain-specific language makes sense here") Compact is a domain-specific language. That choice matters because Midnight needs developers to express privacy-aware smart contract rules that compile into the proof-oriented workflow the protocol requires. A general-purpose language can be flexible, but flexibility is not always the same as clarity. When privacy boundaries, proof logic, and ledger state are core parts of the model, a language needs to make those concepts visible. Developers should not have to infer them from a library call buried inside otherwise public execution logic. A domain-specific language can surface the important concepts at the right level of abstraction. A developer still has to learn how Midnight structures smart contract interactions, but Compact guides that learning by making the relevant concepts part of the language itself. Compact has a TypeScript-like surface, which reduces the learning curve for developers who are not cryptography specialists, while exposing privacy-specific structure that a general-purpose language would obscure. ## Compact is a design boundary, not a syntax choice[​](#compact-is-a-design-boundary-not-a-syntax-choice "Direct link to Compact is a design boundary, not a syntax choice") Compact draws a boundary. Where an EVM-style smart contract starts from "what does this execute on-chain?", a Midnight smart contract starts from "what must be public, what can remain private, and what proof shows that the transition is valid?" Compact is the language layer built around that second framing. ## Start learning Compact[​](#start-learning-compact "Direct link to Start learning Compact") If you are ready to move from concepts to code, the recommended path is: 1. **[Write your first contract](/compact/reference/writing.md)**: build a complete Compact smart contract and see how `ledger`, `circuit`, and `witness` work together. 2. **[Understand explicit disclosure](/compact/reference/explicit-disclosure.md)**: learn how the `disclose()` keyword enforces deliberate data visibility at the compiler level. 3. **[Keep data private](/concepts/how-midnight-works/keeping-data-private.md)**: explore practical shielding patterns including hashes, commitments, Merkle trees, and the commitment/nullifier pattern. 4. **[Build a bulletin board DApp](/tutorials/bboard/smart-contract.md)**: apply what you have learned in a tutorial that combines a Compact contract with a working DApp. If you prefer to set up your environment first, start with [Install the Toolchain](/getting-started/installation.md) and [Create your first contract](/getting-started/hello-world.md). ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Compact language](/compact.md): overview of Compact and its role in generating zero-knowledge circuits. * [Smart contracts on Midnight](/concepts/how-midnight-works/smart-contracts.md): the transcript, proof, and verifier key model that Compact compiles into. * [Zero-knowledge proofs](/concepts/zero-knowledge-proofs.md): how ZK-SNARKs work and how Midnight uses them. * [Kachina](/concepts/kachina.md): the formal model behind public and private state separation. * [Example contracts](/examples/contracts.md): browse Compact contracts for elections, auctions, token transfers, and more. --- # End-to-end architecture > For the complete documentation index, see [llms.txt](/llms.txt) Your device computes a Midnight transaction privately and proves it correct; only then does the network verify it publicly. Private data participates in the computation but never reaches the chain. What crosses the boundary is the public record of execution, plus zero-knowledge proofs that it is correct. This page connects the whole journey in one diagram. Each stage links to a page that covers it in depth. ## The complete flow[​](#the-complete-flow "Direct link to The complete flow") \* The updated private state persists on the device only after the transaction succeeds. ## What each layer can and cannot see[​](#what-each-layer-can-and-cannot-see "Direct link to What each layer can and cannot see") | Layer | Can see | Cannot see | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Chain observer (anyone) | Contract address, which circuit the transaction invoked, public transcripts, ledger operation arguments, disclosed values, commitments, nullifiers, block timing | Witness return values (unless disclosed into a public position), private state, internal computation, the value inserted into a Compact `MerkleTree` (guessable if low entropy), which commitment a given nullifier spends | | Node (validator) | Same as a chain observer, plus mempool timing | Same as a chain observer | | Indexer | Everything on chain (it indexes public data) | Private state, witness values; it cannot open commitments | | Indexer, with your viewing key | Your own shielded transaction history (decrypt-only access; the indexer operator learns it too) | Other users' shielded data; a viewing key cannot spend or sign | | Proof server | Everything in the proof request, including witness values. It is a trust boundary: run your own; with wallet-delegated proving, the proving step moves to whatever proof server the wallet uses | Nothing; it sees the full request | ## Go deeper into each stage[​](#go-deeper-into-each-stage "Direct link to Go deeper into each stage") * Transaction anatomy, offers, and binding: [Building blocks](/concepts/how-midnight-works/building-blocks.md) * How a contract splits into local, circuit, and ledger parts, and what a transcript is: [Smart contracts](/concepts/how-midnight-works/smart-contracts.md) * Well-formedness, the guaranteed and fallible phases, and ledger state updates: [Transaction semantics](/concepts/how-midnight-works/semantics.md) * Commitments, nullifiers, and the techniques that keep data private: [Keeping data private](/concepts/how-midnight-works/keeping-data-private.md) * How transactions move through the node: [Transactions on the network](/concepts/network-architecture/transactions.md) * Exactly what is visible on chain, and the proof server and indexer trust boundaries: [Security and best practices](/guides/security-best-practices.md) * The same flow from the SDK's point of view, provider by provider: [Midnight.js](/sdks/official/midnight-js.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # The Impact VM info Impact is still under active revision. Expect its attributes, including storage-related costs, to change. Currently, users cannot write Impact manually; this feature may be added in the future. On-chain parts of programs are written in *Impact*, our on-chain VM language. You should not need to worry about the details of impact when writing contracts; however, you may see it appear when inspecting transactions and contract outputs. Impact is a stack-based, non-Turing-complete state manipulation language. A contract is executed on a stack containing three things: * a 'context' object describing context related to the containing transaction * an 'effects' object gathering actions performed by the contract during the execution * the contract's current state. Program execution proceeds linearly, with no operations being able to decrease the program counter and every operation being bounded in the time it takes. Program execution has an attached cost, which may be bounded by a 'gas' limit. Programs can either abort, invalidating this (part of) a transaction, or succeed, in which case they must leave a stack in the same shape as they started. The resulting effects must match the transcript's declared effects, and the contract state must be marked as storable, in which case it is adopted as the updated state. ## Transcripts[​](#transcripts "Direct link to Transcripts") Execution transcripts consist of: * a declared gas bound, used to derive the fees for this call * a declared effects object, used to bind the contract's semantics to that of [other parts](/concepts/how-midnight-works/semantics.md) * the program to execute. ## Values[​](#values "Direct link to Values") The Impact stack machine operates on the following state values: * `null` * ``, a field-aligned binary cell * `Map { k1: v1, k2: v2, ... }`, a map from field-aligned binary values to state values * `Array(n) [ v0, v1, ... ]`, an array of `0 < n < 16` state values * `MerkleTree(d) { k0: v1, k2: v2, ... }`, a sparse, fixed-depth `1 <= d <= 32` Merkle tree, with the slots `k0`, `k2`, ..., containing the leaf hashes `v1`, `v2`, ... (typically represented as hex strings). ## Field-aligned binary[​](#field-aligned-binary "Direct link to Field-aligned binary") The basic data types used in Impact are 'field-aligned binary' (FAB) values. These values can store complex data structures in a binary representation while keeping the information necessary to encode them as field elements in any prime field. Aligned values consist of a sequence of aligned *atoms*, each of which consists of a byte string and an alignment atom, where alignment atoms are one of: * `f`, indicating a field alignment: the atom will be interpreted as a little-endian representation of a field element. * `c`, indicating a compression alignment: the atom will be interpreted as a field element derived by hashing its value. * `bn`, indicating an `n`-byte alignment: the atom will be interpreted as a sequence of field elements depending on the prime field and curve to compactly encode `n` bytes. ### Programs[​](#programs "Direct link to Programs") A program is a sequence of operations, consisting of an opcode, potentially followed by a number of arguments depending on the specific opcode. Programs can be run in two modes: *evaluating* and *verifying*. In verifying mode, `popeq[c]` arguments are enforced for equality, while in evaluating mode, the results are gathered instead. Each `Op` has a fixed effect on the stack, which will be written as `-{a, b} +{c, d}`: consuming items `a` and `b` being at the top of the stack (with `a` above `b`), and replacing them with `c` and `d` (with `d` above `c`). The number of values here is just an example. State values are *immutable* from the perspective of programs: a value on the stack cannot be changed, but it can be replaced with a modified version of the same value. We write `[a]` to refer to the value stored in the cell `a`. Due to the ubiquity of it, we write 'sets `[a] := ...`' for 'create `a` as a new cell containing `...`'. We prefix an output value with a `'` to indicate this is a *weak* value, kept solely in-memory, and not written to disk, and an input value with `'` to indicate it *may* be a weak value. We use `"` and `†` to indicate that an input *may* be a weak value, and *iff* it is, the correspondingly marked output will be a weak value. Where arguments are used, we use `State` for a state value, `u21` for a 21-bit unsigned integer, and `path(n)` for a sequence of *either* field-aligned binary values, *or* the symbol `stack`, indicating keys to use in indexing, either directly, or to use stack values instead. | Name | Opcode | Stack | Arguments | Cost (unscaled) | Description | | --------- | ------ | ----------------------------- | ------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `noop` | `00` | `-{} +{}` | `n: u21` | `n` | nothing | | `lt` | `01` | `-{'a, 'b} +{c}` | - | `1` | sets `[c] := [a] < [b]` | | `eq` | `02` | `-{'a, 'b} +{c}` | - | `1` | sets `[c] := [a] == [b]` | | `type` | `03` | `-{'a} +{b}` | - | `1` | sets `[b] := typeof(a)` | | `size` | `04` | `-{'a} +{b}` | - | `1` | sets `[b] := size(a)` | | `new` | `05` | `-{'a} +{b}` | - | `1` | sets `[b] := new [a]` | | `and` | `06` | `-{'a, 'b} +{c}` | - | `1` | sets `[c] := [a] & [b]` | | `or` | `07` | `-{'a, 'b} +{c}` | - | `1` | sets \`\[c] := \[a] | | `neg` | `08` | `-{'a} +{b}` | - | `1` | sets `[b] := ![a]` | | `log` | `09` | `-{'a} +{}` | - | `1` | outputs `a` as an event | | `root` | `0a` | `-{'a} +{b}` | - | `1` | sets `[b] := root(a)` | | `pop` | `0b` | `-{'a} +{}` | - | `1` | removes `a` | | `popeq` | `0c` | `-{'a} +{}` | `a: State` only when validating | \` | a | | `popeqc` | `0d` | `-{'a} +{}` | `a: State` only when validating | \` | a | | `addi` | `0e` | `-{'a} +{b}` | `c: State` | `1` | sets `[b] := [a] + c`, where addition is defined below | | `subi` | `0f` | `-{'a} +{b}` | `c: State` | `1` | sets `[b] := [a] - c`, where subtraction is defined below | | `push` | `10` | `-{} +{'a}` | `a: State` | \` | a | | `pushs` | `11` | `-{} +{a}` | `a: State` | \` | a | | `branch` | `12` | `-{'a} +{}` | `n: u21` | `1` | if `a` is non-empty, skip `n` operations. | | `jmp` | `13` | `-{} +{}` | `n: u21` | `1` | skip `n` operations. | | `add` | `14` | `-{'a, 'b} +{c}` | - | `1` | sets `[c] := [a] + [b]` | | `sub` | `15` | `-{'a, 'b} +{c}` | - | `1` | sets `[c] := [b] - [a]` | | `concat` | `16` | `-{'a, 'b} +{c}` | `n: u21` | `1` | sets `[c] = [b] ++ [a]`, if \` | | `concatc` | `17` | `-{'a, 'b} +{c}` | `n: u21` | `1` | as `concat`, but `a` and `b` must already be in-memory | | `member` | `18` | `-{'a, 'b} +{c}` | - | `size(b)` | sets `[c] := has_key(b, a)` | | `rem` | `19` | `-{a, "b} +{"c}` | - | `size(b)` | sets `c := rem(b, a, false)` | | `remc` | `1a` | `-{a, "b} +{"c}` | - | `size(b)` | sets `c := rem(b, a, true)` | | `dup` | `3n` | `-{x*, "a} +{"a, x*, "a}` | - | `1` | duplicates `a`, where `x*` are `n` stack items | | `swap` | `4n` | `-{"a, x*, †b} +{†b, x*, "a}` | - | `1` | swaps two stack items, with `n` items `x*` between them | | `idx` | `5n` | `-{k*, "a} +{"b}` | `c: path(n)` | \` | c | | `idxc` | `6n` | `-{k*, "a} +{"b}` | `c: path(n)` | \` | c | | `idxp` | `7n` | `-{k*, "a} +{"b, pth*}` | `c: path(n)` | \` | c | | `idxpc` | `8n` | `-{k*, "a} +{"b, pth*}` | `c: path(n)` | \` | c | | `ins` | `9n` | `-{"a, pth*} +{†b}` | - | `sum size(x_i)` | where `pth*` is `{key_{n+1}, x_{n+1}, ..., key_1, x_1}` set `x'_{n+2} = a`, `x'_j = ins(x_j, key_j, cached, x'_{j+1})`, `b = x'_1`. `†` is the weakest modifier of `a` and `x_j`s, and `cached` set to `false` | | `insc` | `an` | `-{"a, pth*} +{†b}` | - | `sum size(x_i)` | as `ins`, but with `cached` set to `true` | | `ckpt` | `ff` | `-{} +{}` | | `1` | denotes boundary between internally atomic program segments. Should not be crossed by jumps. | In the description above, the following short-hand notations are used. Where not specified, result values are placed in a `Cell` and encoded as FAB values. * `a + b`, `a - b`, or `a < b` (collectively `a op b`), for applying `op` on the contents of cells `a` and `b`, interpreted as 64-bit unsigned integers, with alignment `b8`. * `a ++ b` is the field aligned binary concatenation of `a` and `b`. * `a == b` for checking two cells for equality, at least one of which must contain at most 64 bytes of data * `a & b`, `a | b`, `!a` are processed as boolean and, or, and not over the contents of cells `a` and maybe `b`. These must encode 1 or 0. * `typeof(a)` returns a tag representing the type of a state value: * ``: 0 * `null`: 1 * `Map { ... }`: 2 * `Array(n) { ... }`: 3 + n \* 32 * `MerkleTree(n) { ... }`: 4 + n \* 32 * `size(a)` returns the number of non-null entries is a `Map`, `n` for an `Array(n)` or `MerkleTree(n)`. * `has_key(a, b)` returns `true` if `b` is a key to a non-null value in the `Map` `a`. * `new ty` creates a new instance of a state value according to the tag `ty` (as returned by `typeof`): * cell: Containing the empty value. * `null` for itself * `Map`: The empty map * `Array(n)`: An array on `n` `null`s * `MerkleTree(n)`: A blank Merkle tree * `a.get(b, cached)` retrieves the sub-item indexed with `b`. If the sub-item is *not* loaded in memory, *and* `cached` is `true`, this command fails. For different `a`: * `a: Map`, the value stored at the key `b` * `a: Array(n)`, the value at the index `b` < n * `rem(a, b, cached)` removes the sub-item indexed (as in `get`) with `b` from `a`. If the sub-item is *not* loaded in memory, *and* `cached` is `true`, this command fails. * `ins(a, b, cached, c)` inserts `c` as a sub-item into `a` at index `c`. If the path for this index is *not* loaded in memory, *and* `cached` is `true`, this command fails. * `root(a)` outputs the Merkle-tree root of the `MerkleTree(n)` `a`. ## Context and effects[​](#context-and-effects "Direct link to Context and effects") The `context` is an `Array(_)`, with the following entries, in order: caution Currently, only the first two of these are correctly initialized! 1. A `Cell` containing the 256-bit aligned current contract's address. 2. A `Map` from `CoinCommitment` keys to 64-bit aligned Merkle tree indicies, for all newly allocated coins. 3. A `Cell` containing the block's 64-bit aligned seconds since the UNIX epoch approximation. 4. A `Cell` containing the block's 32-bit aligned seconds indicating the maximum amount that the former value may diverge. 5. A `Cell` containing the block's 256-bit hash. This list may be extended in the future in a minor version increment. The `effects` is an `Array(_)`, with the following entries, in order: 1. A `Map` from `Nullifier`s to `null`s, representing a set of claimed nullifiers. 2. A `Map` from `CoinCommitment`s to `null`s, representing a set of received coins claimed. 3. A `Map` from `CoinCommitment`s to `null`s, representing a set of spent coins claimed. 4. A `Map` from `(Address, Bytes(32), Field)` to `null`, representing the contract calls claimed. 5. A `Map` from `Bytes(32)` to cells of `u64`, representing coins minted for any specialization hash. This list may be extended in the future in a minor version increment. `effects` is initialized to `[{}, {}, {}, {}, {}]`. All of `context` and `effects` may be considered cached. To prevent cheaply copying data into the contract state with as little as two opcodes, both are flagged as *weak*, and any operations performed with them. If the final `state'` is tainted, the transaction fails, preventing this from being directly copied into the contract's state. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Private data This document describes some strategies for keeping data private in Midnight contracts. This is not an exhaustive list, but it should help you get started. The most crucial thing to bear in mind is that, except for `[Historic]MerkleTree` data types, anything that is passed as an argument to a `ledger` operation in Compact, as well as all reads and writes of the ledger itself, are publicly visible and should be treated as such. What is public is the argument or ledger value itself, not the code that manipulates it. For instance: ``` export ledger items: Set; export ledger others: MerkleTree<10, Field>; // Reveals `item1` items.insert(item1); // Reveals the *value* of `f(x)`, but not `x` directly items.member(f(x)); // The exception: Does *not* reveal `item2`, though someone that // guesses the value of `item2` can check it! others.insert(item2); ``` However, sometimes you need to reference shielded data in the public state. In those cases, one of the patterns below may help. ## Hashes and commitments[​](#hashes-and-commitments "Direct link to Hashes and commitments") The most basic approach to storing data in public, while keeping it shielded, is to store only a hash or commitment of data, rather than the full data itself. Compact's standard library provides two primary primitives for this: * [`persistentHash`](/compact/standard-library/exports.md#persistentHash), a building block to hash binary data * [`persistentCommit`](/compact/standard-library/exports.md#persistentCommit), a primitive for creating commitments from any Compact type. Both of these effectively create a hash of their inputs, with `persistentHash` being limited to the `Bytes<32>` data type and `persistentCommit` hashing arbitrary data together with a `Bytes<32>` random value. Hashes guarantee that the input cannot be computed from the output, nor any information about the input guessed, unless the whole input is guessed. This is one reason the additional randomness input of `persistentCommit` is important: it prevents someone from guessing the value itself and checking that the hash matches. This is especially useful when there are a small number of possible values, such as an individual vote in an election. The other advantage of randomness is that it prevents correlating equal values: even if I can't guess someone's password, for instance, I might recognize if the same hashed version appears twice, which might unintentionally leak information about who made a state change. With sufficient randomness used, the commitment of a value can be stored on the ledger without revealing it. ### Randomness and rounds in commitments[​](#randomness-and-rounds-in-commitments "Direct link to Randomness and rounds in commitments") Fresh randomness for each commitment is desirable, but in some cases, it is possible to re-use existing randomness by guaranteeing that the *data* will never be the same for the same randomness. We use this in some of our example applications, where we reuse a secret key as a randomness source, together with a round counter to ensure unlinkability between rounds. caution Be careful working with randomness! It's easy to get wrong, and erring on the safe side is generally advisable. ### Authenticating with hashes[​](#authenticating-with-hashes "Direct link to Authenticating with hashes") One of the most useful features of zero-knowledge proofs is that it's possible to emulate signatures just by using hashes in a circuit. That is, just by hashing a secret key and comparing that with a known 'public key', a contract can guarantee that only someone that knows the secret key can continue the transaction. For instance, here's a contract that allows only the creator to use it: ``` import CompactStandardLibrary; witness secretKey(): Bytes<32>; export ledger organizer: Bytes<32>; export ledger restrictedCounter: Counter; constructor() { organizer = publicKey(secretKey()); } export circuit increment(): [] { assert(organizer == publicKey(secretKey()), "not authorized"); restrictedCounter.increment(1); } circuit publicKey(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "some-domain-seperator"), sk]); } ``` ## Making use of Merkle trees[​](#making-use-of-merkle-trees "Direct link to Making use of Merkle trees") Merkle trees, exposed in Compact as the `MerkleTree` and `HistoricMerkleTree` types, are a very useful tool for shielding the values contained in a set. Their key feature is making it possible to assert publicly that some value is contained within the `MerkleTree`, without revealing *which* value this is. This goes above and beyond having, for instance, a `Set>` storing commitments and testing if a commitment is inside it, because a `MerkleTree` does not reveal which entry's membership is proven. This property can be used, for instance, to authorize a set of secret keys to do specific operations, without each operation revealing which key was used to authorize it. In practice, this works by a circuit proving that it has knowledge of a path to an inserted value in the tree and checking that the hash of this path matches the expected path of the tree. The Compact standard library and compact JavaScript target ADTs provide tools for these operations. Specifically, examine the [`MerkleTreePath`](/compact/standard-library/exports.md#merkletreepath) type, the [`merkleTreePathRoot()`](/compact/standard-library/exports.md#merkle_tree_path_root) circuit, and the `pathForLeaf()` and `findPathForLeaf()` functions exposed on the `MerkleTree`/`HistoricMerkleTree` JavaScript state objects, as described in the [ledger data types](/compact/reference/ledger-adt.md) specification. Together, they can be used as follows: ``` import CompactStandardLibrary; export ledger items: MerkleTree<10, Field>; witness findItem(item: Field): MerkleTreePath<10, Field>; export circuit insert(item: Field): [] { items.insert(item); } export circuit check(item: Field): [] { const path = findItem(item); assert(items.checkRoot(merkleTreePathRoot<10, Field>(path.value)), "path must be valid"); } ``` With the `findItem` implementation: ``` function findItem(context: WitnessContext, item: bigint): MerkleTreePath { return context.ledger.items.findPathForLeaf(item)!; } ``` Note that `pathForLeaf` is preferable when possible, as it does not require an *O(n)* scan of the tree, although it does require knowledge of where the item was originally placed. The distinction between `MerkleTree` and `HistoricMerkleTree` is that `checkRoot` for the latter accepts proofs made against prior versions of the Merkle tree. This is helpful if a tree has frequent insertions, as these otherwise invalidate old proofs, although `HistoricMerkleTree` is not suitable if items are frequently removed or replaced, as this could lead to proofs being considered valid which should not be. ### The commitment/nullifier pattern[​](#the-commitmentnullifier-pattern "Direct link to The commitment/nullifier pattern") One powerful shielding pattern is to keep data in two different committed forms (referred to as "commitments" and "nullifiers"), with the former kept in a Merkle tree, and the latter in a `Set`. This lets us make single-use authentication tokens by first creating an entry in the Merkle tree and then when using it, proving its existence and adding the nullifier to a `Set`, asserting that it is not already there. This ensures that re-using the token isn't possible, while still not revealing which token was used. This is the underlying pattern of Zerocash and [Zswap](/concepts/how-midnight-works/zswap.md), which uses it to build shielded UTXOs. It's crucial that the commitments and nullifiers use a domain separator to ensure they are not equal for the same secret data and, optionally, that creating the nullifier requires secret knowledge (as in the [authenticating with hashes section](#authenticating-with-hashes)), which ensures that the initial authorizer can't identify the token's use either. Here's an example where public keys are authorized to increment a counter, once only: ``` import CompactStandardLibrary; witness findAuthPath(pk: Bytes<32>): MerkleTreePath<10, Bytes<32>>; witness secretKey(): Bytes<32>; export ledger authorizedCommitments: HistoricMerkleTree<10, Bytes<32>>; export ledger authorizedNullifiers: Set>; export ledger restrictedCounter: Counter; export circuit addAuthority(pk: Bytes<32>): [] { authorizedCommitments.insert(pk); } export circuit increment(): [] { const sk = secretKey(); const authPath = findAuthPath(publicKey(sk)); assert(authorizedCommitments.checkRoot(merkleTreePathRoot<10, Bytes<32>>(authPath)), "not authorized"); const nul = nullifier(sk); assert !authorizedNullifiers.member(nul) "already incremented"; authorizedNullifiers.insert(disclose(nul)); restrictedCounter.increment(1); } circuit publicKey(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "commitment-domain"), sk]); } circuit nullifier(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "nullifier-domain"), sk]); } ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight's hybrid architecture Midnight combines approaches to create a hybrid architecture that doesn't force you to choose between models but integrates both to maximize benefits. [Midnight's hybrid architecture](https://www.youtube.com/embed/5BGkt7d6fNw?si=NSxPch4B0EqXR_Jn) ## The combination[​](#the-combination "Direct link to The combination") Midnight is a data-protecting blockchain that made a deliberate architectural choice: instead of forcing developers into one paradigm, it provides both UTXO and account-based capabilities. This isn't just about having options—it's about using the right tool for the right job. At its foundation, Midnight operates on a UTXO model. This choice enables the natural parallelism and privacy features we explored in the previous lesson. NIGHT tokens, Midnight's native utility token, exist as UTXOs on the ledger. But here's where Midnight innovates beyond other UTXO chains: NIGHT tokens serve a special purpose. They generate DUST, a renewable resource that powers all transactions on the network. This NIGHT-generates-DUST mechanism is fundamental to Midnight's economic model and ensures predictable transaction costs. On top of this UTXO foundation, Midnight introduces a smart contract layer that can operate using account-based patterns. When you deploy a Compact smart contract (Midnight's smart contract language), it can maintain complex state just like contracts on Ethereum. This means developers can write intuitive smart contracts with familiar patterns while the underlying platform still benefits from UTXO advantages. ## Understanding Midnight's token ecosystem[​](#understanding-midnights-token-ecosystem "Direct link to Understanding Midnight's token ecosystem") Before we dive deeper into token types in future chapters, let's establish a clear framework for understanding how value moves through Midnight's ecosystem. The key insight is understanding the distinction between tokens (which represent value) and resources (which enable network operations). ## The NIGHT token and DUST resource[​](#the-night-token-and-dust-resource "Direct link to The NIGHT token and DUST resource") NIGHT is Midnight's native utility token that exists as UTXOs on the ledger. Think of NIGHT as a renewable energy source—like solar panels that generate electricity. Just as solar panels produce energy when exposed to sunlight, NIGHT tokens continuously generate DUST when designated to a DUST address. DUST is not a token—it's a shielded network resource used exclusively to pay for transaction fees. The amount of DUST you can store is proportional to your NIGHT balance, and DUST decays when disconnected from its generating NIGHT tokens. This unique mechanism provides operational predictability: as long as you hold NIGHT, you can execute transactions without worrying about volatile gas prices. ## Token categories[​](#token-categories "Direct link to Token categories") Beyond the NIGHT/DUST dynamic, Midnight supports two fundamental categories of tokens: * **Ledger Tokens** live directly on Midnight's blockchain, managed by the core protocol itself. These tokens exist as UTXOs and benefit from the highest level of security and efficiency. They can be either shielded (private) or unshielded (transparent), giving users control over their privacy preferences. Because they're handled by Midnight's optimized UTXO engine, they process with maximum efficiency and don't require trusting any smart contract code. * **Contract Tokens** are created and managed by Compact smart contracts. These tokens use account-based patterns within the contracts, maintaining balances and state similar to ERC-20 tokens on Ethereum. With contract tokens, you can program custom logic, implement complex distribution mechanisms, or create tokens that interact with other contracts. These also support both shielded and unshielded variants, though the implementation differs from ledger tokens. ## Token types[​](#token-types "Direct link to Token types") When we consider the intersection of where tokens live (ledger vs. contract) and their privacy properties (shielded vs. unshielded), we get a matrix of possibilities: | Token Type | Location | Privacy | Key Characteristics | Example Use Cases | | -------------------------- | ----------------- | ----------- | -------------------------------------------------------- | -------------------------------------------------- | | Shielded Ledger Tokens | Blockchain ledger | Private | Native privacy, maximum efficiency, UTXO-based | Private payments, confidential value transfer | | Unshielded Ledger Tokens | Blockchain ledger | Transparent | Full transparency, high performance, UTXO-based | NIGHT tokens, public treasuries, exchange listings | | Shielded Contract Tokens | Smart contracts | Private | Programmable privacy, custom logic, account-based | Private securities, confidential rewards | | Unshielded Contract Tokens | Smart contracts | Transparent | Full programmability, ERC-20 style, complex interactions | Governance tokens, public DeFi protocols | Each token type serves specific needs. Unshielded ledger tokens like NIGHT provide transparent, high-performance value transfer—perfect for exchanges, public treasuries, or any scenario requiring auditability. Shielded ledger tokens enable private peer-to-peer transactions with the efficiency of native blockchain operations. Contract tokens bring programmability to both transparent and private use cases. Unshielded contract tokens work like traditional ERC-20s but benefit from Midnight's infrastructure. Shielded contract tokens open entirely new possibilities—imagine private company equity where transfers are confidential but voting rights remain verifiable. ## Implications[​](#implications "Direct link to Implications") Understanding Midnight's hybrid architecture fundamentally changes how you approach application design. Instead of being constrained by a single model's limitations, you can architect solutions that leverage each model's strengths. Consider a decentralized exchange. Traditional DEXs on account-based chains suffer from MEV and lack privacy options. On Midnight, you could architect a hybrid solution: the order book and market-making logic live in transparent smart contracts (leveraging the account model's strengths for complex state), while actual token swaps execute as atomic UTXO transactions (leveraging parallelism and optional privacy). This isn't just theoretical—it's the kind of innovation Midnight's architecture enables. ## Decisions[​](#decisions "Direct link to Decisions") When building on Midnight, your first decision is often whether to use ledger tokens or contract tokens. Here's a framework for making that choice: Choose ledger tokens when you need maximum performance, native privacy features, or simple value transfer without complex logic. The UTXO model's parallelism makes ledger tokens ideal for payment systems, remittance platforms, or any high-volume transaction scenario. Choose contract tokens when you need programmable logic, complex state management, or integration with other smart contracts. The account model within contracts makes these perfect for DeFi protocols, gaming assets, or tokens with sophisticated distribution mechanisms. You're not locked into one choice. A single application can use both ledger tokens for efficient value transfer and contract tokens for complex logic. This flexibility is what makes Midnight's architecture revolutionary. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Transaction semantics ## Ledger states[​](#ledger-states "Direct link to Ledger states") Midnight's ledger consists of two items: * Zswap's state * a Merkle tree of coin commitments * an index to the first free slot of the coin commitment tree * a set of nullifiers * a set of valid past Merkle tree roots * a map from contract addresses to contract states. ### Contract state[​](#contract-state "Direct link to Contract state") A contract state consists of: * an [Impact state value](/concepts/how-midnight-works/impact.md#values) * a map of entry point names to operations, where entry points correspond to exported circuits in a contract. A contract operation consists of a Snark verifier key that is used to validate contract calls made against this contract and entry point. ## Transaction fallibility[​](#transaction-fallibility "Direct link to Transaction fallibility") Transactions execute in three stages: * well-formedness check * guaranteed phase * fallible phase. The well-formedness check is run without any state and checks the general integrity and consistency of the transaction. In contrast, both the guaranteed and fallible phases are run against the ledger state and either produce a new state or fail. If a transaction fails during the guaranteed phase, it is *not included in the ledger*. If it fails during the fallible phase, any effects of the guaranteed phase *still apply*, and the ledger will record the transaction as a *partial success*. The fees for all phases of execution are collected in the *guaranteed* phase and are forfeited if a transaction fails in the fallible phase. ## Well-formedness[​](#well-formedness "Direct link to Well-formedness") The well-formedness check verifies that a transaction is in a canonical format, and that: * all zero-knowledge proofs in [Zswap](/concepts/how-midnight-works/zswap.md) offers can be verified * the Schnorr proof in the contract section can verified * the guaranteed offer is balanced with respect to the following adjustments: * subtraction of the fees of the entire transaction * addition of any mints performed in guaranteed transcripts * the fallible offer is balanced with respect to the following adjustment: * Addition of any mints performed in fallible transcripts * each contract-owned input or output is claimed exactly once by the same contract in the effects section of the transcript matching the fallibility of the offer it appears in * any outputs claimed as being created by a contract in the effects section of a transcript are claimed at most once, and they appear in the offer matching the fallibility of the transcript * any contract calls that are claimed in a transcript are present and claimed at most once * if a contract call has both a guaranteed and fallible section, the fallible section starts with a `ckpt` operation. ## Phase execution[​](#phase-execution "Direct link to Phase execution") Other than the notes in the [transaction fallibility section](#transaction-fallibility), the guaranteed and fallible phases operate similarly, except that the following additional work is performed in the guaranteed phase: * contract operations for all calls are looked up, and the zero-knowledge proofs are verified against them * the fallible Zswap section is also applied during the guaranteed section, to ensure that it cannot invalidate the fallible section by itself. \[^1] Then: 1. The phase's Zswap offer is applied, by inserting new commitments into the Merkle tree and nullifiers into the nullifier set (aborting if they are already present), checking that the Merkle roots used are valid past roots (aborting otherwise), and updating the past roots set 2. The above additional checks for the guaranteed phase are performed, if applicable 3. For each contract call in sequence, the transcript relevant to this execution phase is applied 1. The contract's current state is loaded 2. The context is set up from the transaction 3. The [Impact](/concepts/how-midnight-works/impact.md) program is executed against the context, an empty effects set, the transcript program, and the declared gas limit, in verification mode 4. The resulting effects are tested to be equal to the declared effects 5. The resulting state is stored as the contract's state, iff it is "strong". \[^1] This would permit invalidating any fallible section by merging with an invalid spend otherwise. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Smart contracts on Midnight While you may have some familiarity with smart contracts, designing smart contracts for data protection provides unique challenges and perspectives. This article will therefore briefly walk through key points in which Midnight differs from more public smart contract solutions and how this should inform your construction of contracts in Midnight. ## Replicated state machines[​](#replicated-state-machines "Direct link to Replicated state machines") All blockchain systems are replicated state machines at their core: They keep a *ledger state*, which is modified by *transactions*. Various blockchains differ in which transactions are considered valid and what effect they have on a ledger state. Smart-contract-enabled blockchains allow transactions to program parts of the blockchain's validity criteria that subsequent transactions have to satisfy. The focus here is on the *account model*, where contracts are *deployed* by a transaction, which assigns a unique address to the contract in the blockchain. This contract can define the validation criteria and state transitions for the transactions that interact with it. The following example illustrates these ideas. Imagine a contract to support a guessing game, in which the player guesses factors of a number, stored in the contract's state. Making a correct guess allows the player to set the next number for the opposing player(s). Thus, when making a guess, the player offers two factors for the current number and two factors to define the new number. The logic of a guess is expressed in pseudocode as follows: note This is pseudocode, not a functional Compact program. ``` def guess_number(guess_a, guess_b, new_a, new_b): assert(guess_a != 1 and guess_b != 1 and new_a != 1 and new_b != 1, "1 is too boring a factor") assert(guess_a * guess_b == number, "Guessed factors must be correct") number = new_a * new_b ``` The contract *could* just let the player provide the new number directly, instead of its factors, but then they could (whether by accident or intentionally) also spoil the fun by passing in a prime number. Forcing the player to provide 'interesting' factors eliminates this possibility. When the contract is deployed, this program is put directly on-chain, typically in a compressed, bytecode form, along with an initial state of the contract. Conceptually, this may make the ledger's state look something like this: ``` contracts: "": state: number: 35 entryPoints: guess_number: | def guess_number(...): // ... ``` A transaction can then call this contract by supplying inputs to the function, for instance: ``` transaction: type: "call" address: "" entryPoint: "guess_number" inputs: [5, 7, 2, 6] ``` When processed, nodes process this by: * looking up the `state` at `` as well as the program at `` and `guess_number` * running the program against the state, and `inputs` * if the program succeeds, storing the new `state`. ## Midnight contracts, conceptually[​](#midnight-contracts-conceptually "Direct link to Midnight contracts, conceptually") You may have noticed that the above program is not a good implementation for this game, because every time a new number is set, its factors are publicly visible as part of the transaction that sets it. Anyone who really wants to win can read off the factors and use them as their own 'guess'. Where's the sport in that? To move beyond this problem, imagine that you don't have to worry about the blockchain and how it processes transactions. Instead, consider a contract as an interactive program that can interact with the contract's on-chain state, as well as call arbitrary code on the user's local machine. In this setting, it's possible to rewrite the above pseudocode program to look something like this: ``` def guess_number(): (a, b) = local.guess_factors(number) assert(a != 1 and b != 1, "1 is too boring a factor") assert(a * b == number, "Guessed factors must be correct") (a, b) = local.new_challenge() assert(a != 1 and b != 1, "1 is too boring a factor") number = a * b ``` While this program is longer than the one in the previous section, it is also doing slightly more. It tells us where the numbers come from: local calls to `guess_factors` or `new_challenge` respectively. Often this is what happens anyway, with transaction inputs needing to be carefully computed ahead of time to ensure that the corresponding transaction succeeds. Here, the API is clear, and the `guess_factors` routine is even given the number for which it should guess (which previously you'd have to figure out for yourself). On the chain, this interaction would have the following interactions: * retrieving `number` ledger field * setting `number` ledger field. Neither of these reveals the details of the factors - neither the ones guessed, nor the ones the new challenge consists of. A practical challenge with this approach is how to ensure that the contract is correctly used. For the `local` calls, this is an accepted risk; we don't want to prescribe how `guess_factors` works, for instance, just that it outputs correct guesses (hence the input validation). For the contract program itself, we want other users to be convinced that we ran the right program and that the changes made to the contract's state are sensible. ## Transcripts and ZK Snarks[​](#transcripts-and-zk-snarks "Direct link to Transcripts and ZK Snarks") The key technology that makes everything work is the [ZK Snark](/glossary.md#zk-snarks). At their core, ZK Snarks (and more broadly zero-knowledge proofs) are a way to prove that you know how to assign values to a number of variables, so that they satisfy some set of clear, mathematical conditions. Some of these variables are *public*, while most are not. The above program can be cleanly split into three interacting parts, each run in a separate environment: The `local` part, the `ledger` part, and the glue that links the two together and encodes the core program logic. This 'glue' can be converted into a series of variable assignments and equations that can be transformed into a ZK Snark, while the ledger interactions can be converted into a program that runs on-chain. Here, in the example of factoring the current state of `35` into `5 * 7` and replacing it with `2 * 6`: Off-chain code ``` (a, b) = local. guess_factors(n1) (a, b) = local. new_challenge() ``` ⇓ Private transcript ``` a1 = 5 b1 = 7 a2 = 2 b2 = 6 ``` In-circuit code ``` def guess_number(): assert(a != 1 and b != 1, "...") assert(a * b == n2, "...") assert(a != 1 and b != 1, "...") n3 = a * b ``` ⇓ Circuit constraints ``` guess_number: inputs: public: n1, n2, n3, transcript code private: a1, b1, a2, b2 constraints: a1 != 1 b1 != 1 a1 * b1 = n2 a2 != 1 b2 != 1 n3 = a2 * b2 // Additional constraints // enforcing the shape of // the public transcript ``` On-chain code ``` n1 = number n2 = number number = n3 ``` ⇓ Public transcript ``` n1 = 35 n2 = 35 n3 = 12 assert(n1 == number) assert(n2 == number) number = n3 ```
More complex programs, with function calls, conditionals, iterations, and complex primitives such as hash function calls can also be translated in this way. See the [writing a contract](/compact/reference/writing.md) section of this documentation for a description of the language we use to write these programs. In the preceding example, it is possible to prove that, for public `n1`, `n2` and `n3`, we know values of `a1`, `b1`, `a2`, and `b2` for which these equations hold. This proof does not say that anyone actually ran the above program, but it *does* say that the program's rules were followed, which is what a skeptical user truly cares about. The sequence of assignments, `n1`, `n2`, and `n3`, and the program that produces or uses them is referred to as the *public transcript*, and conversely `a1`, `b1`, `a2`, and `b2` are the *private transcript*. Public transcripts are encoded as bytecode\[^1], and the shape of this bytecode is directly enforced by the circuit. Transactions in Midnight then are essentially made up of the public transcript and a zero-knowledge proof that this transcript is correct. Each transaction is made with respect to a contract and a specific *circuit*\[^2] on that contract. On-chain, instead of storing the code for `guess_number()`, a cryptographic key used to verify zero-knowledge proofs *for* `guess_number()` is stored. This cryptographically encodes and enforces all of the equations listed in the circuit above. Broadly, the state looks something like this: ``` contracts: "": state: number: 35 entryPoints: guess_number: "" ``` And a transaction made against this state might look something like: note This is a sketch of a transaction. ``` transaction: type: "call" address: "" entryPoint: "guess_number" transcript: | n1 = 35 n2 = 35 n3 = 12 assert(n1 == number) assert(n2 == number) number = n3 proof: "" ``` This transaction, when it is verified, will check that the proof is valid with respect to the verifier key and then *run* the transcript. Here it checks that things are still as expected; if the current `number` *isn't* `35` the transaction is no longer valid – whoever made it did not guess the factors of 35, after all. The result of the transaction (if it succeeds) is updating the state to contain `12` – and importantly, *this* transaction tells no one which factors were used there, or in the guess! A reasonable question is why the `number` check occurs twice, and in practice, this is a valid observation: There is no need to read the same value multiple times. However, this way of handling external interactions means that the operations performed here are arbitrary; the zero-knowledge proof had no knowledge of what a `read` is or that the values of `n1` and `n2` are necessarily the same, and this allows the use of more interesting operations, such as `increment` or `insert`. These are particularly useful to avoid making transactions invalid due to results not matching, as in the case of `35` above. Contrast two simultaneous invocations of `increment` with two simultaneous sequences of `read`ing a value, adding `1`, and `write`ing it again; the `increment` will (almost) always succeed, while the read-add-write sequence is prone to failure. ## Putting value at stake[​](#putting-value-at-stake "Direct link to Putting value at stake") It's not immediately obvious how the notion of *value* fits into this model. In public blockchains, it's easy for a smart contract to have a value as well as a state, which can be used to pay into and out of the contract. As this transfer of value is important to many applications, it is necessary to achieve such transfers in a setting that preserves data privacy. The Midnight token currently uses an implementation of [Zswap](/concepts/how-midnight-works/zswap.md), which operates similarly to UTXOs, but shields the token values, types, and fund holders. An exception to total shielding applies to the funds held by a contract; the value and type of these are still shielded by default, but holding and releasing them *is* linked to the contract. These UTXOs are represented in contracts as individual coins, which are just data until they are explicitly *received*. Once received, they can be handled like any other data – whether they are stored publicly, encrypted, or stored privately is up to the contract itself. When a contract wishes, they can then be *sent* to another contract or to a user address. Coin *receives* and *sends* have special semantics: They are recorded as operations in the public transcript but have no effect on the contract's state. Instead, they require a corresponding input or output to be included in the same transaction, ensuring that a contract doesn't receive funds that don't exist or send funds it doesn't have. Again in pseudocode, wagers can be attached to the example: ``` def guess_number(new_wager): (a, b) = local.guess_factors(number) builtin.send(wager, local.self()) assert(a != 1 and b != 1, "1 is too boring a factor") assert(a * b == number, "Guessed factors must be correct") (a, b) = local.new_challenge() assert(a != 1 and b != 1, "1 is too boring a factor") number = a * b builtin.receive(new_wager) wager = new_wager ``` ## Factoring and keys[​](#factoring-and-keys "Direct link to Factoring and keys") The example of factoring may seem like a toy, and it is somewhat arbitrary, but it is worth noting that factoring large integers is an important problem in cryptography. Knowing the factors of large numbers is the basis of the RSA cryptographic algorithms, and the simple guessing game corresponds to proving that you know the secret keys for an RSA public key. This shows the power of zero-knowledge proofs and that they can serve the same purposes as signature schemes. Not only can you prove you know a secret key, but you can then prove that *the same person* did something else, effectively signing what they did. In practice, if you want to authenticate, this construction is not the most efficient; proving the knowledge of a preimage of hash functions (that is, knowing `sk` such that `pk = H(sk)`) is a simpler alternative in most cases. *** \[^1] For advanced reading of *how* the operations are encoded, see the details of [Midnight's on-chain VM, Impact](/concepts/how-midnight-works/impact.md). \[^2] Circuits are named such as the compilation of zero-knowledge proofs has many similarities with assembling a special-purpose logic circuit --- > For the complete documentation index, see [llms.txt](/llms.txt) # Zswap info The details of Midnight's native currency implementation are not yet stable and will undergo further revisions. The performance of basic operations has not been optimized at this time. Zswap\[^1] is a shielded token mechanism, based on Zerocash\[^2], extended with *native token support* and *atomic swaps*. Zswap's basic component is an [offer](#offers), which conceptually is a set of [inputs](#inputs) and [outputs](#outputs). In this matter, it matches the UTXO model, although the set of unspent transactions itself is not computable due to the inability to link matching inputs and outputs, a property inherited from Zerocash. This section describes a slight variation of Zswap used in Midnight that permits contracts to hold funds. ## Offers[​](#offers "Direct link to Offers") A Zswap offer consists of four elements: * a set of [input](#inputs) coins (also called 'spends') * a set of [output](#outputs) coins * a set of transient coins * a balance vector. Transient coins are coins that are both created and spent in the same transaction. This may seem superfluous, but it extends the ability for contracts to manage coins. Conceptually, this is an [output](#outputs) immediately followed by an [input](#inputs), with the sole distinction that the input spends from a locally created coin commitment set, as opposed to the global one, to prevent index collisions. The balance vector is a vector of the total value of this offer. Its dimensions are all possible [token types](#token-types), with each dimension carrying its own value. An input of a given type counts positively towards this vector and negatively towards an output. A balance vector is considered *balanced* if, for all dimensions, it is non-negative. Typically, it is *adjusted* before checking for balance, to account for token mints and fee deductions. ### Outputs[​](#outputs "Direct link to Outputs") A Zswap output creates a new coin and places a corresponding *commitment* in a global Merkle tree. It consists of: * the commitment itself * a multi-base Pedersen commitment to the type/value vector * an optional contract address, iff (if and only if) this output is targeted at a contract * an optional ciphertext, if the output is toward a user that must receive it * a zero-knowledge proof that the former are correct with respect to each other. Outputs are valid if their zero-knowledge proof is verified. ### Inputs[​](#inputs "Direct link to Inputs") A Zswap input spends an existing coin, by referencing (without revealing) its original commitment in the global Merkle tree and producing a corresponding (but unlinkable) *nullifier*. It consists of: * the nullifier itself * a multi-base Pedersen commitment to the type/value vector * an optional contract address, iff the output is targeted at a contract * a Merkle tree of a tree containing the commitment corresponding to the nullifier * a zero-knowledge proof that the former are correct with respect to each other. Inputs are valid iff the zero-knowledge proof verifies *and* the Merkle tree root is in the set of past roots. ### Token types[​](#token-types "Direct link to Token types") A token type in Midnight is a 256-bit collision-resistant hash output or the pre-defined zero value, which represents the native token. Users can issue their own tokens from contracts, with these token types being derived as a hash of the contract's address and a domain-separator given by the user. \[^1] Engelmann, F., Kerber, T., Kohlweiss, M., & Volkhov, M. 2022. Zswap: zk-SNARK based non-interactive multi-asset swaps. *Proceedings on Privacy Enhancing Technologies (PoPETs)* 4 (2022), 507-527. `https://eprint.iacr.org/2022/1002.pdf` \[^2] Ben-Sasson, E., Chiesa, A. Garman, C., Green, M., Miers, I., Tromer, E., & Virza, M. 2014. Zerocash: Decentralized Anonymous Payments from Bitcoin. *2014 IEEE Symposium on Security and Privacy, SP 2014, Berkeley, CA, USA, May 18-21, 2014*, 459-474. `https://eprint.iacr.org/2014/349.pdf` --- > For the complete documentation index, see [llms.txt](/llms.txt) # How privacy blockchains work Public blockchains make all transaction data visible by default. Privacy blockchains change this by using cryptographic or architectural techniques, so that transaction details, identities, or data stay confidential while remaining verifiable. Midnight is a privacy-focused blockchain built for compliant applications: it separates public and private state at the protocol level through zero-knowledge proofs and selective disclosure. ## Public blockchains vs privacy blockchains[​](#public-blockchains-vs-privacy-blockchains "Direct link to Public blockchains vs privacy blockchains") Blockchain visibility sits on a spectrum with three broad points, not a ranking: * **Public blockchains**, such as Bitcoin and Ethereum, are transparent by design. Transaction history and balances are visible to anyone, which supports open verification but exposes activity patterns. * **Privacy blockchains** add confidentiality on top of, or instead of, that default transparency. They support confidential transactions whose details stay hidden from public view while the network still verifies that every rule was followed. * **Permissioned or enterprise blockchains** restrict visibility to approved participants entirely. Only vetted members run nodes or read data, which suits consortium use cases. A single application can span these points. For example, an enterprise blockchain can add cryptographic privacy between its own members, and a privacy blockchain can expose selected data publicly. ## Techniques privacy blockchains use[​](#techniques-privacy-blockchains-use "Direct link to Techniques privacy blockchains use") Privacy blockchains draw on four main techniques. Each deserves its own deep dive, so this section stays at summary level: * **Zero-knowledge proofs** prove a statement is true without revealing the underlying data. See [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md) for how they work. * **Confidential computing and trusted execution environments (TEEs)** run computation inside an isolated, attested hardware enclave, so even the machine's operator cannot read the data in use. * **Secure multi-party computation (MPC)** splits computation across multiple parties, so no single party sees the combined private inputs. * **Fully homomorphic encryption (FHE)** computes directly on encrypted data and decrypts only the final result. See [fully homomorphic encryption](/concepts/fully-homomorphic-encryption.md) for a deeper look. For the full technical comparison of the cryptographic approaches, see [ZK vs FHE vs MPC](/concepts/zk-vs-fhe-vs-mpc.md). ## Which platforms enable compliant privacy for enterprise use cases[​](#which-platforms-enable-compliant-privacy-for-enterprise-use-cases "Direct link to Which platforms enable compliant privacy for enterprise use cases") Compliant privacy means keeping sensitive data confidential by default while still allowing selective, verifiable disclosure to auditors, regulators, or counterparties when required. Regulated industries generally need this combination rather than absolute anonymity. Platforms group naturally by technical approach. The examples below are named factually, not ranked, and reflect August 2026: * **Zero-knowledge proofs**: Midnight, Aztec, and Aleo build private smart contracts on zero-knowledge proofs. * **Confidential computing and trusted execution environments**: Oasis Sapphire and Secret Network run confidential contracts inside hardware enclaves. * **Fully homomorphic encryption**: Zama brings FHE smart contracts to Ethereum. Inco is often grouped here and is building toward an FHE protocol, though its live product, Inco Lightning, runs on trusted execution environments. * **Enterprise-permissioned ledgers**: Hyperledger Fabric, an LF Decentralized Trust project, and Canton Network serve consortium and institutional deployments. Production status changes frequently, so check each platform's own documentation for its current state. ## How Midnight enables compliant privacy for enterprises[​](#how-midnight-enables-compliant-privacy-for-enterprises "Direct link to How Midnight enables compliant privacy for enterprises") Midnight uses a hybrid ledger that separates public transaction data from shielded private state. Zero-knowledge proofs, specifically zk-SNARKs generated from Compact contracts, let the network verify a transaction without exposing its contents. Selective disclosure through viewing keys, special keys that provide read-only access to shielded transactions, lets an authorized party such as an auditor or regulator see specific data on request, without making that data public by default. This combination is what Midnight calls programmable privacy: applications choose what stays confidential, what becomes public, and what can be disclosed to whom. It is Midnight's own architecture, not a claim that Midnight is the only or best option for every enterprise use case. This page builds on the general Web3 model described in [Web3](/concepts/web3.md). For the developer entry point, see the [Midnight Developer Hub](https://midnight.network/developer-hub). ## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions") ### How do privacy blockchains work and which platforms enable compliant privacy for enterprise use cases?[​](#how-do-privacy-blockchains-work-and-which-platforms-enable-compliant-privacy-for-enterprise-use-cases "Direct link to How do privacy blockchains work and which platforms enable compliant privacy for enterprise use cases?") Privacy blockchains use cryptographic or architectural techniques, such as zero-knowledge proofs, confidential computing, or fully homomorphic encryption, to keep transaction data or identities confidential while still allowing that data to be verified. For enterprise use cases, compliant privacy platforms include zero-knowledge-based chains such as Midnight, Aztec, and Aleo, confidential-computing platforms such as Oasis Sapphire and Secret Network, and FHE-based platforms such as Zama. Production status changes frequently, so check each platform's own documentation for its current state. ### What is the difference between a public blockchain and a privacy blockchain?[​](#what-is-the-difference-between-a-public-blockchain-and-a-privacy-blockchain "Direct link to What is the difference between a public blockchain and a privacy blockchain?") A public blockchain such as Bitcoin or Ethereum makes all transaction data visible to anyone by default. A privacy blockchain adds confidentiality on top of, or instead of, that default transparency, keeping transaction details or identities hidden from public view while still allowing the underlying computation to be verified. ### What techniques do privacy blockchains use to protect data?[​](#what-techniques-do-privacy-blockchains-use-to-protect-data "Direct link to What techniques do privacy blockchains use to protect data?") The main techniques are zero-knowledge proofs, which prove a statement is true without revealing the underlying data. Confidential computing and trusted execution environments run computation in an isolated, attested environment. Secure multi-party computation splits computation across multiple parties, and fully homomorphic encryption computes directly on encrypted data. ### Which platforms enable compliant privacy for enterprises?[​](#which-platforms-enable-compliant-privacy-for-enterprises "Direct link to Which platforms enable compliant privacy for enterprises?") Enterprises evaluating compliant privacy typically look at zero-knowledge-based platforms such as Midnight, Aztec, and Aleo, confidential-computing platforms such as Oasis Sapphire and Secret Network, FHE-based platforms such as Zama, and enterprise-permissioned ledgers such as Hyperledger Fabric and Canton Network. Each platform's enterprise and compliance positioning evolves, so verify current capabilities against its own documentation. ### How does Midnight enable compliant privacy for enterprises?[​](#how-does-midnight-enable-compliant-privacy-for-enterprises "Direct link to How does Midnight enable compliant privacy for enterprises?") Midnight uses a hybrid ledger that separates public transaction data from shielded private state, verified through zero-knowledge proofs so a transaction can be confirmed valid without exposing its contents. Selective disclosure through viewing keys lets an authorized party, such as an auditor or regulator, see specific data on request, without making that data public by default. ### Can privacy blockchains be used in regulated industries?[​](#can-privacy-blockchains-be-used-in-regulated-industries "Direct link to Can privacy blockchains be used in regulated industries?") Yes, when they support selective disclosure rather than absolute anonymity. Regulated industries generally need the ability to reveal specific data to auditors or regulators on request, so platforms that combine confidentiality by default with verifiable, targeted disclosure fit compliance requirements better than systems built for full anonymity. ## Sources[​](#sources "Direct link to Sources") * [Midnight ledger documentation](/concepts/ledgers.md): Midnight's shielded and unshielded token model, rational privacy, and viewing keys. * [Midnight proof system (midnight-zk)](https://github.com/midnightntwrk/midnight-zk) and the [Compact compiler](https://github.com/LFDT-Minokawa/compact): Midnight's zk-SNARK stack. * [Aztec documentation](https://docs.aztec.network) and [Aleo documentation](https://developer.aleo.org): zero-knowledge platform references. * [Oasis Sapphire](https://oasis.net) and [Secret Network](https://scrt.network): TEE-based confidential computing platforms. * [Zama documentation](https://docs.zama.org) and [Inco](https://www.inco.org): FHE and confidential computing platform references. * [Hyperledger Fabric](https://www.lfdecentralizedtrust.org/projects/fabric) and [Canton Network](https://www.canton.network): enterprise-permissioned ledger references. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Kachina Kachina is a data-protecting smart contract model that enables confidential, general-purpose smart contract functionality without sacrificing decentralization. It provides a practical protocol for building data-protecting smart contracts using non-interactive zero-knowledge proofs. By design, contracts separate personal data that stays on a user's machine from data processed publicly on-chain. At the core of Kachina is a bridge between the blockchain and users' local machines. It represents the system through two distinct [states](/glossary.md#state): * **Public state**: Resides on the blockchain and is accessible to all participants * **Private state**: Exists locally on each user's machine Kachina connects private and public state updates using zero-knowledge proofs. A contract can update public and private state in tandem. By definition, a ZKP lets one party (the prover) convince another party (the verifier) that a statement is true without disclosing additional information. In Kachina, the statement is that a private state change justifies a corresponding public state change. To make a valid assertion, participating parties prove in zero-knowledge that their public state updates are valid. They provide evidence of a corresponding private state and the inputs that justify the update. Kachina supports this process with ZK Snarks and offers a low-level, versatile framework grounded in the Universally Composable (UC) security model. ![kachina](https://ucarecdn.com/e298a234-a027-4cb6-9564-86f0d5488e43/) As shown in the figure, clients can maintain private state for contracts in which they participate. For each user, public state operates as a deterministic state machine coupled with private state. Private data is never shared on-chain. Authorization for contract actions is based on ZKPs that verify transaction compliance with contract rules. Validation starts by checking the proof against the circuit, then runs the public portion of the contract to produce a new public state. Kachina also enables concurrency to improve smart contract efficiency. Concurrency means multiple actors can perform tasks simultaneously without blocking each other, which increases throughput. Kachina uses transcripts to record state operations and related queries. By optimizing conflicting transactions and allowing reorderings, Kachina minimizes information leakage while maximizing concurrency. ## The model[​](#the-model "Direct link to The model") Kachina presents smart contracts as reactive state machines. Users interact with these contracts by submitting transactions to Midnight. When a user initiates a transaction, they intend to issue a high-level command to the smart contract, such as casting a vote or withdrawing funds. After the transaction is confirmed by the ledger, the user receives information about the outcome of their command and any computed results based on the contract's current state. ## The core protocol idea[​](#the-core-protocol-idea "Direct link to The core protocol idea") To handle smart contract data securely, Kachina allows contracts to interact with specialized entities that facilitate data access and updates. These entities let contracts issue queries and obtain relevant information. Instead of directly mutating contract data, this interaction preserves state integrity and consistency. Users maintain a transcript of these interactions, including queries and expected responses. By proving knowledge of inputs that produce those responses, users validate the transcript and verify reliable data handling. Kachina provides a strong foundation for building privacy-preserving smart contract systems. It lets users interact with contracts securely while protecting personal data and preserving intended contract functionality. This model applies to many use cases, including TradFi and DeFi applications, supply chain systems, healthcare applications, and more. For more details, see [Kachina - Foundations of Private Smart Contracts](https://eprint.iacr.org/2020/543.pdf). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Ledgers If you're coming from Ethereum or other EVM chains, you'll encounter one of the most important differences in blockchain architecture. The choice between account and UTXO models is not just an implementation detail; it shapes how tokens are tracked and what kinds of applications you can build. Midnight is a privacy-preserving blockchain built on the UTXO model because it enables strong privacy features, parallelism, and efficiency. Midnight also supports account-style tokens through smart contracts. This dual approach gives developers flexibility and starts with understanding these two models. ## The fundamental difference[​](#the-fundamental-difference "Direct link to The fundamental difference") Blockchains track ownership. There are two primary approaches, and they represent different models of digital ownership: | Model | Core concept | State management | Examples | | ------------- | ----------------------------------------- | ------------------------------------------ | -------------------------- | | Account model | Persistent accounts with balances | Global state updated in place | Ethereum, Polygon, BSC | | UTXO model | Individual coins (outputs) that are spent | State transitions via consumption/creation | Bitcoin, Cardano, Midnight | The *account model* is common in Ethereum-style systems. Think of it as a giant spreadsheet where each row is an address and the balance column is updated on each transaction. Each address has a persistent account with a balance. When you send tokens, the system subtracts from one balance and adds to another. The *UTXO model* (Unspent Transaction Output) is used by Bitcoin and forms Midnight's foundation. Instead of tracking balances in a single table, the system tracks individual "coins" (UTXOs). Each UTXO has a specific value and owner. When you spend tokens, you consume existing UTXOs and create new ones, similar to paying with cash and receiving change. There is no single stored balance; your balance is the sum of the UTXOs you control. ## Why this matters for token development[​](#why-this-matters-for-token-development "Direct link to Why this matters for token development") Different applications have different needs. Midnight supports both token approaches and gives you architectural flexibility: **Ledger tokens (UTXO-based)** - These are native to Midnight's blockchain ledger itself. NIGHT tokens—Midnight's native utility token—are the prime example. NIGHT tokens exist as individual UTXOs directly on the ledger and serve a special purpose: they generate DUST, the renewable resource that powers all transactions on Midnight. Each NIGHT token UTXO has a specific value and owner, and spending them follows the UTXO pattern of consuming inputs and creating outputs. This UTXO structure is crucial because it enables Midnight's privacy features—individual UTXOs can be shielded or unshielded as needed. **Contract tokens (Account-based)** - These live inside smart contracts written in Compact (Midnight's smart contract language) and work just like ERC-20 tokens you know from Ethereum. The contract maintains a mapping of addresses to balances, and transfers simply update these balance numbers. These tokens follow OpenZeppelin-style standards adapted for Compact, so if you're comfortable with Solidity token development, contract tokens will feel immediately familiar. Contract tokens can also support both shielded and unshielded operations, giving you privacy options even within the account model. This approach lets you choose the right model for each use case instead of forcing one model everywhere. ## Concrete comparison[​](#concrete-comparison "Direct link to Concrete comparison") The following example shows how a simple token transfer differs between the two models. ### Account model (Ethereum-style)[​](#account-model-ethereum-style "Direct link to Account model (Ethereum-style)") When you send 40 ETH from Alice to Bob: ``` // Conceptually, the ledger does this: // Before: Alice = 100 ETH, Bob = 50 ETH accounts[Alice].balance -= 40; accounts[Bob].balance += 40; // After: Alice = 60 ETH, Bob = 90 ETH // The state is modified in-place // Both accounts must exist in the global state ``` The ledger maintains a global database of all account balances, updating them in place. Every account that has ever received tokens must be tracked forever. ### UTXO model (Midnight-style)[​](#utxo-model-midnight-style "Direct link to UTXO model (Midnight-style)") When Alice sends 40 NIGHT tokens to Bob: ``` // Alice has a 100 NIGHT UTXO // Transaction consumes it entirely and creates new ones: transaction = { inputs: [ { value: 100, owner: Alice, id: "utxo_123" } // Consumed entirely ], outputs: [ { value: 40, owner: Bob }, // Payment to Bob (new UTXO) { value: 60, owner: Alice } // Change back to Alice (new UTXO) ] } // Old UTXO is marked as spent, new UTXOs are created // No balances are updated - only coin ownership changes ``` No balances are updated in place. Instead, Alice's 100 NIGHT UTXO is marked as spent and two new UTXOs are created. This is like paying with a $100 bill for a $40 item and receiving $60 in change. ## The architectural impact[​](#the-architectural-impact "Direct link to The architectural impact") This difference in value tracking has major implications for scalability, privacy, and application design. ### Parallelism and performance[​](#parallelism-and-performance "Direct link to Parallelism and performance") The UTXO model naturally enables parallel transaction processing. Since each UTXO is independent, transactions using different UTXOs can be processed simultaneously. For example, if Alice has 10 different UTXOs, she can send them to 10 different recipients in parallel transactions. In contrast, account-based systems must process transactions that touch the same account sequentially. Each transaction modifies the same balance, which creates a bottleneck. ### Privacy through architecture[​](#privacy-through-architecture "Direct link to Privacy through architecture") Midnight's privacy model is compliance-friendly. Unlike systems that enforce full anonymity, Midnight offers "rational privacy": users can choose shielded tokens when needed and still support compliance requirements through viewing keys (special keys that provide read-only access to shielded transactions). The UTXO model makes this possible because each coin is independent. You can use shielded UTXOs without affecting others. You can reveal specific transactions for compliance while keeping others private. This granular control is difficult in account models where activity is tied to one persistent address. This privacy capability extends to ledger tokens (UTXO-based) and, in evolving form, contract tokens (account-based), though implementation details differ. Ledger tokens can be shielded at the UTXO level, while contract tokens use Midnight's private smart contract state model. ### State management and efficiency[​](#state-management-and-efficiency "Direct link to State management and efficiency") Account systems must maintain an ever-growing global state. Every account that has ever existed must be tracked, even when it holds a zero balance. This leads to state growth that increases node operating cost over time. ## The mental model shift[​](#the-mental-model-shift "Direct link to The mental model shift") For developers coming from Ethereum, the biggest adjustment is thinking about value differently: | Your current thinking | UTXO thinking | Why it matters | | ------------------------------------------------ | ------------------------------------------- | ------------------------------------ | | "Check my account balance" | "Count my unspent coins" | No single privacy linkage point | | "Update sender and receiver balances" | "Consume inputs, create outputs" | Enables atomic coin-level operations | | "Transaction failed due to insufficient balance" | "Not enough UTXOs to cover the amount" | Better error and fee planning | | "Gas is deducted from my account" | "I need DUST (generated by NIGHT) for fees" | More explicit resource management | | "One address = one identity" | "Many UTXOs = flexible identity surface" | Stronger privacy options | This shift also matters for Midnight's smart contracts, which execute off-chain with proof generation. Instead of every node re-executing contract code, Midnight uses zero-knowledge circuits to prove correct execution. ## Choosing the right token type[​](#choosing-the-right-token-type "Direct link to Choosing the right token type") Understanding these models is practical preparation for building on Midnight. Choosing between ledger tokens and contract tokens is one of your first major design decisions: | Use case | Best choice | Why this model works | Example applications | | -------------------------- | ------------------------- | ------------------------------------- | ---------------------------------------- | | High-volume payments | Ledger tokens (UTXO) | Parallel transaction processing | Payment processors, remittance systems | | Private transactions | Ledger tokens (UTXO) | Individual UTXOs can be shielded | Confidential transfers, private auctions | | Cross-chain bridges | Ledger tokens (UTXO) | Atomic operations and clear ownership | Bridge protocols, wrapped assets | | Complex DeFi logic | Contract tokens (account) | Rich state management capabilities | AMMs, lending protocols, yield farming | | Gaming mechanics | Contract tokens (account) | Complex rules and interactions | In-game currencies, item crafting | | Governance systems | Contract tokens (account) | Voting weights and delegation | DAOs, protocol governance | | Compliance-friendly assets | Both (hybrid approach) | Transparent base plus private options | Securities, regulated stablecoins | You are not forced to choose one model forever. You can use UTXO-based ledger tokens when you need performance and privacy, and account-based contract tokens when you need familiar programming patterns. You can also use both in the same application. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Consensus Blockchain consensus is the mechanism by which distributed nodes agree on the state of a ledger without a central authority. It is what keeps a blockchain secure and tamper-resistant without a single trusted party. Different blockchains choose different consensus mechanisms depending on their needs; the main families are proof of work, proof of stake, and Byzantine fault tolerance variants such as proof of authority. ## How privacy-focused blockchains handle consensus[​](#how-privacy-focused-blockchains-handle-consensus "Direct link to How privacy-focused blockchains handle consensus") Consensus and privacy are separate concerns. Consensus is about how nodes agree on the public ledger state, while privacy is about what data on that ledger is visible to whom. A privacy-focused blockchain still needs consensus on transaction validity and ordering; it does not need consensus nodes to see the private contents of a transaction. Midnight separates these concerns by keeping consensus on the public ledger layer, while private state and computation stay off-chain, verified through [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md). Validators can agree on the chain's state without seeing private data, and selective disclosure lets users reveal specific data when a business or compliance need requires it. For how Midnight separates public and private state, see [keeping data private](/concepts/how-midnight-works/keeping-data-private.md), and for the broader landscape of privacy techniques, see [ZK vs FHE vs MPC](/concepts/zk-vs-fhe-vs-mpc.md). ## Comparison at a glance[​](#comparison-at-a-glance "Direct link to Comparison at a glance") | Consensus family | How it works | Example platforms | | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | Proof of work (PoW) | Validators (miners) compete to solve a computational puzzle; the winner proposes the next block | Bitcoin | | Proof of stake (PoS) | The protocol selects validators to propose blocks in proportion to the stake they hold or have delegated | Ethereum | | Delegated proof of stake (DPoS) | Token holders vote for a smaller set of delegates who produce blocks on their behalf | EOS (now Vaulta) | | Practical Byzantine fault tolerance (pBFT) | A validator set votes explicitly on each block, tolerating a portion of faulty or malicious nodes | Chains built on CometBFT (formerly Tendermint) across the Cosmos ecosystem | | Proof of authority (PoA) with separate finality | A known, rotating set of validators produces blocks in round-robin order; a separate finality mechanism later confirms blocks as irreversible | Midnight (AURA for block production, GRANDPA for finality) | Example platforms verified August 2026. ## Midnight's consensus model[​](#midnights-consensus-model "Direct link to Midnight's consensus model") The Midnight Network leverages a modified consensus model built on top of standard *Substrate primitives*, specifically *AURA* for block production and *GRANDPA* for finality. These components have been extended to support the unique requirements of Midnight as a Cardano Partnerchain. ## Validator selection[​](#validator-selection "Direct link to Validator selection") Unlike standard Substrate chains, Midnight uses a *custom validator set selection function*. This mechanism accounts for *stake delegation from Cardano Stake Pool Operators (SPOs)*, allowing existing Cardano validators to participate in Midnight consensus. The model also supports optional inclusion of *permissioned validators*, offering flexibility for hybrid public/private network deployments. ## AURA: Block production[​](#aura-block-production "Direct link to AURA: Block production") AURA is Midnight's block production mechanism and belongs to the proof-of-authority family introduced above. *AURA (Authority Round)* is a *proof-of-authority (PoA)* algorithm used to determine which validator is responsible for producing each block. Validators take turns in a *round-robin fashion*, based on predefined slots and session keys. This model is simple, fast, and deterministic, making it suitable for high-throughput blockchains with known validator sets. AURA is not specific to Midnight and was originally implemented in [OpenEthereum](https://openethereum.github.io/Aura). You can read more in the [Polkadot protocol glossary](https://github.com/polkadot-developers/polkadot-docs/blob/79fe4ec5498411bc8ac8bfef58c79cd2c6713090/polkadot-protocol/glossary.md?plain=1#L29). ## GRANDPA: Finality[​](#grandpa-finality "Direct link to GRANDPA: Finality") GRANDPA is Midnight's finality layer, the part of consensus that makes a block irreversible, as introduced above. *GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement)* is a finality gadget that provides *asynchronous, provable finality*. It operates independently of block production, allowing validators to vote on chains and finalize blocks that have received sufficient support. GRANDPA is a general-purpose consensus component originally developed for Polkadot and is *not specific to Midnight*. You can find its [formal specification here](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf) and learn more in the [Polkadot protocol glossary](https://github.com/polkadot-developers/polkadot-docs/blob/79fe4ec5498411bc8ac8bfef58c79cd2c6713090/polkadot-protocol/glossary.md?plain=1#L186). ## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions") ### What is blockchain consensus and how do modern privacy-focused blockchains implement it for secure and compliant applications?[​](#what-is-blockchain-consensus-and-how-do-modern-privacy-focused-blockchains-implement-it-for-secure-and-compliant-applications "Direct link to What is blockchain consensus and how do modern privacy-focused blockchains implement it for secure and compliant applications?") Blockchain consensus is the mechanism by which distributed nodes agree on the state of a shared ledger without relying on a central authority. Modern privacy-focused blockchains keep this agreement process on the public ledger layer, separate from the private data itself, so validators can confirm that transactions are valid without seeing their private contents. Midnight does this with AURA for block production and GRANDPA for finality, while zero-knowledge proofs verify private state and computation instead of exposing them to validators. ### What is a blockchain consensus mechanism?[​](#what-is-a-blockchain-consensus-mechanism "Direct link to What is a blockchain consensus mechanism?") A consensus mechanism is the set of rules a blockchain uses to get its distributed nodes to agree on which transactions are valid and in what order they occurred. Common families include proof of work, proof of stake, and Byzantine fault tolerance variants such as proof of authority, each with different tradeoffs in speed, energy use, and the validator set required. ### What is the difference between proof of work and proof of stake?[​](#what-is-the-difference-between-proof-of-work-and-proof-of-stake "Direct link to What is the difference between proof of work and proof of stake?") Proof of work requires validators to compete by solving a computational puzzle, which is energy-intensive but has secured Bitcoin since its launch. Proof of stake instead selects validators in proportion to the stake they hold or have delegated, which uses far less energy and secures Ethereum and most newer blockchains. ### Do privacy blockchains still need consensus if transactions are private?[​](#do-privacy-blockchains-still-need-consensus-if-transactions-are-private "Direct link to Do privacy blockchains still need consensus if transactions are private?") Yes. Consensus and privacy solve different problems. Consensus is about nodes agreeing on the ledger's state and transaction validity, while privacy is about what data on that ledger is visible to whom. A privacy-focused blockchain still needs validators to agree on the public parts of the ledger, such as that a transaction is valid and correctly ordered, even when the transaction's private contents stay hidden through cryptographic techniques such as zero-knowledge proofs. ### What consensus mechanism does Midnight use?[​](#what-consensus-mechanism-does-midnight-use "Direct link to What consensus mechanism does Midnight use?") Midnight uses a modified consensus model built on Substrate primitives: AURA for block production and GRANDPA for finality. Validator selection incorporates stake delegation from Cardano Stake Pool Operators, reflecting Midnight's role as a Cardano Partner Chain, and also supports optional permissioned validators for flexible public or private network deployment. To run a node or validator, see the [nodes documentation](/nodes.md). ### Is proof of authority secure enough for compliant, real-world applications?[​](#is-proof-of-authority-secure-enough-for-compliant-real-world-applications "Direct link to Is proof of authority secure enough for compliant, real-world applications?") Proof of authority relies on a known, accountable set of validators rather than an open, anonymous set, which suits applications that need predictable performance and clear accountability, such as compliant enterprise use cases. Midnight combines rotating AURA block production with GRANDPA finality voting, and its validator selection draws on stake delegation from Cardano Stake Pool Operators, with support for permissioned validators where a deployment requires them. ## Sources[​](#sources "Direct link to Sources") * [AURA specification (OpenEthereum)](https://openethereum.github.io/Aura): the proof-of-authority block production algorithm. * [GRANDPA formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf): the finality gadget Midnight uses. * [Polkadot protocol glossary](https://github.com/polkadot-developers/polkadot-docs/blob/79fe4ec5498411bc8ac8bfef58c79cd2c6713090/polkadot-protocol/glossary.md): AURA and GRANDPA reference definitions. * [Bitcoin whitepaper](https://bitcoin.org/bitcoin.pdf): the original proof-of-work design. * [Ethereum proof-of-stake documentation](https://ethereum.org/developers/docs/consensus-mechanisms/pos/): the canonical proof-of-stake deployment. * [CometBFT](https://github.com/cometbft/cometbft): the Byzantine fault tolerant engine, formerly Tendermint Core, used across the Cosmos ecosystem. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Cryptography Outside of the Midnight Ledger, which contains its own specialized cryptographic circuits, the Midnight node relies on several foundational cryptographic algorithms for securing core functions such as consensus, state transition integrity, and network communication. The primary hash function used is *Blake2 256*, which provides strong cryptographic guarantees and is employed for general-purpose hashing — including block hashes and within various state transition functions. It strikes a balance between performance and security, making it suitable for runtime-critical operations. For signature verification, Midnight uses three distinct schemes depending on the role: * **sr25519** is based on the Schnorrkel and Ristretto x25519 construction and is used to sign block authorship messages in AURA. It supports efficient key derivation, signature aggregation, and strong security guarantees. * **ECDSA** is used to sign Partnerchain-related consensus messages. This ensures interoperability with external systems where ECDSA is the standard. * **Ed25519** is used in two parts of the Midnight node: * to sign finality messages in GRANDPA, enabling fast and secure verification of validator communication during finalization. * to sign messages exchanged through the underlying libp2p protocols in the Polkadot SDK. The Midnight node also uses **twoxhash** as a non-cryptographic hash function for generating storage keys. Although it is not suitable for cryptographic use, twoxhash is optimized for speed and low collision rates, which makes it a good fit for internal key-value storage structures. See [Storage](/concepts/network-architecture/storage.md) for more details. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Onchain logic and state The Midnight node follows the standard Polkadot SDK model for defining and executing on-chain logic. All core logic (except native pre-compiles) is compiled into *WebAssembly (WASM)*, which forms the node’s *runtime* — the state transition function executed consistently across all participating nodes. This runtime comprises modular components known as *FRAME pallets*. Each pallet encapsulates a specific domain of logic and can include: * Storage definitions (maps, multi-key maps, lists, values) * Events * Dispatchable functions (transactions) * Offchain workers * Hooks * Host-exposed functions * RPC methods This modular design allows for a flexible and extensible on-chain execution environment, similar in spirit to a smart contract framework but compiled ahead of time and governed at the chain level. Midnight’s runtime integrates both upstream pallets from *Polkadot SDK* and components developed by *Cardano Partner-Chains*. Examples include: * `pallet-aura`: Handles block production using the AURA protocol. * `pallet-grandpa`: Manages finality through the GRANDPA protocol. * `pallet-partnerchains-session` and `pallet_session_validator_management`: Coordinate session rotation and validator management in the partnerchain context. The core pallet powering Midnight’s privacy-preserving transaction logic is `pallet-midnight`. This internally maintained pallet encapsulates the state machine for the [Midnight Ledger](/api-reference/ledger.md). `pallet-midnight` processes specialized transactions from the Midnight Ledger, including *ZSwap asset transfers* and *contract operations*. Instead of traditional signature-based dispatch, it validates the cryptographic *proofs* embedded in each transaction. Native libraries are used to verify these proofs and execute the corresponding state transitions. After execution, the new state is committed on-chain. As with other Polkadot SDK chains, Midnight stores canonical ledger state in a *Patricia-Merkle trie* backed by a key-value database. A *commitment to the full Midnight Ledger state* is also persisted, providing a tamper-proof and verifiable snapshot after each block. --- > For the complete documentation index, see [llms.txt](/llms.txt) # P2P networking In decentralized networks, the peer-to-peer (P2P) layer is responsible for connecting nodes and enabling data exchange. The Midnight node uses the default Polkadot SDK Rust LibP2P implementation. Key components include: ### Discovery mechanisms[​](#discovery-mechanisms "Direct link to Discovery mechanisms") To participate in a decentralized network, a node must discover and connect to peers. Midnight supports several peer discovery strategies: #### Bootstrap nodes[​](#bootstrap-nodes "Direct link to Bootstrap nodes") Nodes can be configured with a list of predefined peers, known as bootstrap nodes. These hard-coded identities and addresses are provided in the network configuration. On startup, the node attempts to connect to these trusted peers to join the network and learn about additional peers. #### mDNS (multicast DNS)[​](#mdns-multicast-dns "Direct link to mDNS (multicast DNS)") For local network discovery, mDNS enables nodes to find peers on the same LAN using UDP broadcast. This is useful for development environments, testnets, or networks where peers are in close proximity. You can enable or disable mDNS through network settings. #### Kademlia DHT (random walk)[​](#kademlia-dht-random-walk "Direct link to Kademlia DHT (random walk)") Once connected to at least one peer, the node engages in a Kademlia-based random walk on each configured chain’s *Distributed Hash Table (DHT)*. This involves sending FIND\_NODE queries to discover additional peers. Over time, the node builds a more complete view of the network, improving connectivity and resilience. ### Connection establishment[​](#connection-establishment "Direct link to Connection establishment") After discovery, peers establish direct connections and negotiate shared protocol capabilities. This stage sets the transport, security, and multiplexing foundation that higher-level sync and gossip protocols rely on. #### Transport layer[​](#transport-layer "Direct link to Transport layer") When node A (Alice) wants to connect to node B (Bob) and knows Bob's address, it initiates a connection using one of the following transport protocols: * **TCP/IP**: Traditional IPv4 or IPv6 socket connections. * **WebSockets**: Built on top of TCP, allowing browser-friendly or proxy-compatible connections via WebSocket framing. * **DNS**: Domain names can be used as node addresses, resolved to IPs during the connection process. #### Encryption and multiplexing[​](#encryption-and-multiplexing "Direct link to Encryption and multiplexing") Once peers establish the underlying transport, they upgrade the connection through a series of negotiated protocols: * Peers use the [Noise Protocol Framework](https://noiseprotocol.org/) for encryption, which ensures end-to-end confidentiality and integrity. * Peers typically use Yamux for stream multiplexing, allowing multiple logical streams (substreams) to operate concurrently over a single physical connection. Peers negotiate these upgrades using Multistream-Select, which lets them choose compatible encryption and multiplexing options. #### Substream protocols[​](#substream-protocols "Direct link to Substream protocols") Once the connection is multiplexed, peers open multiple substreams, each dedicated to a specific application-level protocol. These include: * **Ping**: For liveness checks and latency measurements. * **Request-Response**: For structured data exchange (e.g., block or transaction queries). * **Notifications**: For broadcasting events like new transactions, block announcements, finality updates, and light-client state syncs. #### Peer identification[​](#peer-identification "Direct link to Peer identification") Each node identifies itself using a unique *ed25519 public key*, separate from the keypair used for consensus message signing. During the handshake, peers exchange this identity key and use it to authenticate each other throughout the session. --- > For the complete documentation index, see [llms.txt](/llms.txt) # RPC interface The Remote Procedure Call (RPC) layer lets external clients, such as dApps, wallets, explorers, and services, interact with a running Midnight node over HTTP/HTTPS or WebSocket connections. In Midnight, RPCs follow the JSON-RPC standard and expose methods for: * Submitting transactions, which trigger state transitions * Querying on-chain contract state * Fetching auxiliary data, such as off-chain values or metadata These methods form the interface for building tools and applications on top of Midnight. ### Core RPC methods[​](#core-rpc-methods "Direct link to Core RPC methods") Midnight nodes expose a set of custom RPC methods focused on ledger state, contract state, and system information. Key methods include: ``` #[method(name = "midnight_jsonContractState")] fn get_json_state( &self, contract_address: String, at: Option, ) -> Result; ``` Returns the JSON-encoded state of a given smart contract. ``` #[method(name = "midnight_contractState")] fn get_state( &self, contract_address: String, at: Option, ) -> Result; ``` Returns the raw (binary-encoded) contract state at a specific block (or the latest block if omitted). ``` #[method(name = "midnight_unclaimedAmount")] fn get_unclaimed_amount( &self, beneficiary: String, at: Option, ) -> Result; ``` Fetches the amount of unclaimed tokens or rewards for a beneficiary address. ``` #[method(name = "midnight_zswapChainState")] fn get_zswap_chain_state( &self, contract_address: String, at: Option, ) -> Result; ``` Returns the current ZSwap chain state for a contract. ``` #[method(name = "midnight_apiVersions")] fn get_supported_api_versions(&self) -> RpcResult>; ``` Lists all supported RPC API versions, which is useful for tooling compatibility checks. ``` #[method(name = "midnight_ledgerVersion")] fn get_ledger_version(&self, at: Option) -> Result; ``` Returns the ledger version at the specified block. ### Polkadot SDK RPC support[​](#polkadot-sdk-rpc-support "Direct link to Polkadot SDK RPC support") Midnight also supports default Polkadot SDK RPC methods, including: * `system_health` * `chain_getBlock` * `state_getStorage` * `rpc_methods`, which returns a list of all supported RPC endpoints. You can call `rpc_methods` at any time to retrieve the full list of methods exposed by your node. note Some RPC methods exposed by Midnight might not appear in the [Polkadot JS web app](https://polkadot.js.org/). For a general reference, see the [Polkadot SDK RPC method documentation](https://polkadot.js.org/docs/substrate/rpc/). Midnight implementations overlap with this list, but support can differ by node version and configuration. ### Partnerchain RPCs[​](#partnerchain-rpcs "Direct link to Partnerchain RPCs") Midnight exposes partnerchain-specific RPC methods, especially for block producers and sidechain integration. These methods query consensus signals, relay finality information, and coordinate between chains. ### Security note for block producers[​](#security-note-for-block-producers "Direct link to Security note for block producers") warning Not all RPC methods are safe to expose on public or production nodes. If you run a block-producing node, be cautious about which RPC endpoints you enable. Some methods can leak sensitive data or increase performance risk. To minimize risk: * Use the `--rpc-methods Safe` flag to limit exposed methods to a safer subset. * Avoid using `--rpc-external` unless absolutely necessary, as it exposes RPC interfaces to external networks. Always review your node’s RPC configuration to ensure it aligns with your threat model and operational role (for example, validator vs. observer). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Storage Midnight is built on the Polkadot SDK (formerly Substrate) and uses ParityDB as its default database backend. * **ParityDB**: A fast key-value store designed for blockchain use cases that stores all on-chain state. * **Merkle-Patricia trie**: The underlying data structure for state commitments. It preserves state integrity and supports efficient inclusion proofs for on-chain data (for example, contract state or account balances). * **twoxhash**: A non-cryptographic hash function that generates storage keys within the trie. It is optimized for speed and low collision rates, which makes it well suited for internal key-value lookups. While not suitable for cryptographic guarantees, it significantly improves trie performance. All state transitions are committed into this trie and persisted via ParityDB. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Transactions The Midnight node supports the standard Polkadot SDK transaction format, but these default-style transactions are uncommon in practice. Midnight relies on a proof-based verification model tightly coupled with the Midnight Ledger design. A block is an ordered list of extrinsics. As on any [Substrate](/concepts/network-architecture/onchain-logic.md) chain, those extrinsics fall into two kinds: transactions that users or tooling submit into the transaction pool, and inherents that the block author injects directly (no signature, not gossiped) and every other node re-checks. Midnight layers a second distinction on top of this, between ledger transactions and non-ledger transactions, which this page describes. ## The transaction format and its classification[​](#the-transaction-format-and-its-classification "Direct link to The transaction format and its classification") When you decode a transaction from the chain, you classify it against a published vocabulary that the node exposes through runtime metadata. The `TransactionTypeV2` enumeration names the categories a decoder can expect: * `MidnightTx`: a ledger-carrying transaction. It holds the opaque ledger payload together with the result of decoding it. * `TimestampTx`: the block timestamp, surfaced as a first-class transaction value. * `UnknownTx`: any transaction the classifier does not recognize, such as a future or unknown variant. info This classification is a vocabulary for off-node consumers. Indexers, the toolkit, and other downstream tooling read it through runtime metadata to label a decoded transaction. The node does **not** match on these categories to decide how to process a transaction; dispatch happens through the runtime's pallet calls and inherents, not through this enumeration. An earlier `TransactionType` enumeration carried an optional decoded transaction; `TransactionTypeV2` supersedes it by carrying the full decode result, so a consumer can see why a payload failed to decode. ## The ledger and non-ledger boundary[​](#the-ledger-and-non-ledger-boundary "Direct link to The ledger and non-ledger boundary") The node and the ledger own different parts of a transaction, and the boundary between them is precise: * The **node** frames, validates, weighs, and routes a transaction. It owns the extrinsic shape, the validation and weighting rules, the events it emits, and the classification vocabulary above. * The **ledger** decodes and interprets the opaque payload. A ledger transaction crosses into the ledger as a byte vector; the Midnight Ledger owns and interprets everything inside that payload, including the shielded and unshielded state changes, the proofs, and the contract operations. A **ledger transaction** is the proof-based state change carried by this opaque payload. The node applies it through `pallet-midnight` and emits ledger events (such as contract calls, contract deployments, and applied-transaction markers), but it never inspects the payload's contents. A **non-ledger transaction** is every other node-defined extrinsic or inherent: system transactions, the bridge transfer flow, the cNIGHT observation inherent, the timestamp, and the classification envelope itself. The rest of this page documents these categories. info The ledger team documents the contents of a ledger transaction payload. See the [ledgers concept page](/concepts/ledgers.md) and the [ledger API reference](/api-reference/ledger.md) for the shielded and unshielded transaction model. This page stops at the node boundary and does not describe the payload internals. ## Non-ledger transaction categories[​](#non-ledger-transaction-categories "Direct link to Non-ledger transaction categories") Each non-ledger category has a distinct origin and privilege. The table below summarizes them; the sections that follow give the detail. Treat origin and privilege as load-bearing; the categories are structurally different, and a bridge transfer in particular is not a peer of a user-submitted transaction. | Category | Origin | Privilege | Owning component | Observable effect | | ------------------ | ------------------------------------------------ | ------------------------- | ---------------------------- | ----------------------------------------------- | | Ledger transaction | User or tooling (pool) | Unsigned, proof-validated | `pallet-midnight` (envelope) | Ledger events (contract call, deploy, applied) | | System transaction | Governance | Root, governance-gated | `pallet-midnight-system` | `SystemTransactionApplied` event | | Timestamp | Block author (inherent) | inherent | `pallet-timestamp` | Classified as `TimestampTx` | | Unknown | Classifier fallback | None (off-node label) | classification vocabulary | Decoded as `UnknownTx` | | cNIGHT observation | Block author (inherent) | inherent | `pallet-cnight-observation` | Recorded Cardano token movements | | Bridge transfer | Block author (inherent), then system transaction | inherent, then root path | `pallet-c2m-bridge` | Bridge transfer event plus a system transaction | ### System transaction[​](#system-transaction "Direct link to System transaction") A system transaction applies a state change to the ledger through a privileged, audited channel rather than through the user transaction pool. Governance submits it with root origin, and the node gates it against an allow-check before applying it, so only system transactions that governance permits can reach the ledger. When the node applies one, it emits a `SystemTransactionApplied` event that carries the transaction hash and its serialized form, which lets an indexer correlate the effect on the ledger with the originating call. A system transaction differs from a ledger transaction in three ways: its origin (governance rather than any user), its privilege (root, plus the governance allow-check), and its event. Both ultimately reach the ledger's apply path, but only the system transaction does so through this privileged channel. ### Timestamp[​](#timestamp "Direct link to Timestamp") The block author supplies the block timestamp as an inherent, and the standard timestamp pallet applies it. The classification vocabulary surfaces it as `TimestampTx`, so a downstream decoder can read the block's timestamp as a first-class transaction value. The timestamp is not a separately submitted transaction; it is the classification of the inherent's value. ### Unknown[​](#unknown "Direct link to Unknown") `UnknownTx` is a classifier fallback rather than an on-chain object. A decoder yields it when an encoded transaction matches neither the ledger-carrying nor the timestamp category, for example, a variant that a future runtime introduces. It signals forward compatibility: a consumer can recognize that a transaction exists without being able to interpret it. ### cNIGHT observation[​](#cnight-observation "Direct link to cNIGHT observation") The node observes cNIGHT token movements on Cardano and records them on Midnight through an inherent. The block author injects the observed movements, and every other node re-derives and compares them when it validates the block, so the observation is a consensus-checked fact rather than a user-submitted claim. This inherent underpins the registration and DUST-generation tracking that the cNIGHT observation pallet owns. ### Bridge transfer[​](#bridge-transfer "Direct link to Bridge transfer") A bridge transfer moves tokens from Cardano to Midnight. It is **not** a user-submittable transaction and is not a peer of a ledger transaction. The block author injects the observed Cardano transfer as an inherent; the bridge handler then validates it against the approved-transfers list (single-use, to prevent replay), constructs the corresponding ledger system transaction, and applies it through the system transaction path. The net effect on the ledger therefore arrives as a system transaction, while the bridge emits its own event (such as a user transfer, reserve transfer, or invalid transfer) so that an indexer can correlate the Cardano-side movement with the Midnight-side result. Model a bridge transfer as an inherent that produces a system transaction, never as a standalone transaction type. ## Consensus inherents[​](#consensus-inherents "Direct link to Consensus inherents") Beyond the categories above, the block author also injects consensus inherents that the Cardano Partner-Chains SDK supplies, including the AURA slot, the main-chain hash, and authority selection. These are consensus infrastructure rather than Midnight transaction categories; see [on-chain logic and state](/concepts/network-architecture/onchain-logic.md) and [consensus](/concepts/network-architecture/consensus.md) for how they fit block production and finality. ## The ledger transaction lifecycle[​](#the-ledger-transaction-lifecycle "Direct link to The ledger transaction lifecycle") Most Midnight transactions are unsigned and follow a format defined by the Midnight Ledger. Instead of traditional signature-based authorization, these transactions embed a cryptographic proof that attests to the validity of a specific action, such as a contract invocation, contract deployment, or ZSwap transaction. This proof lets the network validate state transitions without exposing sensitive data or signatures directly. When you submit a transaction, it passes through several processing stages. First, the transaction pool validates its well-formedness, ensuring it meets the structural and logical requirements that the runtime and ledger specification define. Once a block includes the transaction, the runtime fully verifies the embedded proof. If the proof is valid, the runtime executes the corresponding state transition. It then commits the resulting state update to on-chain storage, completing the transaction lifecycle. --- > For the complete documentation index, see [llms.txt](/llms.txt) # The origins of sidechains and partner chains The original side chain research set the foundations for scalability, which further evolved into a partner chain framework, where a mature network like Cardano interacts with Midnight, its first partner chain. ## The evolution of scalability[​](#the-evolution-of-scalability "Direct link to The evolution of scalability") Midnight builds upon a long line of research and development at Input | Output (IOG). This journey began with the 2019 academic paper [Proof-of-Stake Sidechains](https://eprint.iacr.org/2018/1239), and continuing with the evolution of the partner chain framework that allows for secure, private computation linked to a public settlement layer. Midnight, as the first partner chain to Cardano, inherits security from the existing, highly decentralized, mature network. This means that developers can experiment with bold new features – like **programmable privacy** in the case of Midnight – without having to build a resilient infrastructure from scratch. ## What is a sidechain?[​](#what-is-a-sidechain "Direct link to What is a sidechain?") A sidechain is a separate blockchain that runs in parallel with, and depends on, the main chain. It acts like a specialized subsystem where developers can implement custom rules, different languages, or other performance or security features without affecting the stability or speed of the primary chain. Essentially, the goal of sidechains is to enable blockchain scalability or new functionality, while interoperability with the main chain makes it usable. Within a sidechain system, there are typically two chains, the main chain and the side chain, that are connected via bridges. These bridges enable the transfer of assets between the chains and allow smart contracts on different chains to interact. One of the defining features of sidechains is that they are heterogenous. This means that the ledgers in the network do not need to be clones of one another; they can vary wildly in their design and operation, as follows: * **Different parties**: Maintained by distinct sets of validators or miners. * **Diverse consensus mechanisms**: One chain might use Proof-of-Work (PoW) while another uses Proof-of-Stake (PoS), or other consensus mechanisms. * **Varied assumptions**: Security may rely on a majority of hashing power, a majority of stake, or even a single trusted operator (eg in a private bank ledger). ## How to verify cross-chain transactions[​](#how-to-verify-cross-chain-transactions "Direct link to How to verify cross-chain transactions") Imagine a system of two ledgers, A and B, connected by a bridge. To maintain consistency, the maintainers of ledger B must verify that incoming transfers from ledger A are legitimate. Since maintainers of ledger B cannot automatically access records on ledger A, several verification patterns are used to achieve this: * **Direct observation**: Nodes on ledger B run a full node (full or light-client) of ledger A. They can access everything, but are hardware-intensive. * **Certificate-based**: * **Optimistic**: Assumes transactions are valid unless a fraud proof is submitted. * **Signature by full population**: All maintainers of ledger A collaboratively produce a stake-based threshold multisignature (like Mithril) on the state of the chain. * **Signature by a small committee**: Cleverly selected to faithfully represent the whole population. The certificate-based approaches may be further augmented by the use of SNARKs for better efficiency. ## Security and the firewall property[​](#security-and-the-firewall-property "Direct link to Security and the firewall property") What security guarantee do we expect from a system of ledgers interconnected in this way? For each of the ledgers in the ecosystem, its necessary security assumption (e.g. honest majority of stake) can be either satisfied or violated. Security assumptions are considered monotone, which means that once a ledger’s underlying assumption is broken, the ledger is classified as failed. In this model, security is not recoverable; once the violation occurs, the ledger can no longer be trusted to provide its original guarantees. To protect the ecosystem, the *PoS Sidechains* paper formalizes two critical requirements for the entire system: ### Individual security[​](#individual-security "Direct link to Individual security") As long as each ledger’s specific security assumption is satisfied, it must provide the standard features, in a nutshell: * **Safety**: Settled transactions remain settled forever; * **Liveness**: Valid transactions will eventually be settled. ### The firewall property[​](#the-firewall-property "Direct link to The firewall property") The firewall property aims to ensure that the failure of one ledger must not endanger the security of other connected ledgers. This is a vital concept in Midnight’s design. If Sidechain A is compromised, a user on the Cardano mainnet or sidechain B should not see their assets or consensus integrity at risk. The risk of a failed ledger must be contained. Technically, this condition is captured by requiring that in case any ledger ever fails and the list of transactions it carried is lost irreversibly, there must exist an “explanation” list of transactions that it could have contained that is consistent with the contents of all the remaining—still secure and operational—ledgers, in the sense that together they result in a valid state of the overall system. ## Why this research matters for Midnight[​](#why-this-research-matters-for-midnight "Direct link to Why this research matters for Midnight") Midnight is built on these exact principles and as the first partner chain of Cardano, the framework defined in this research paper ensures that while Midnight offers specialized ‘shielded’ transactions and data protection, the Cardano mainchain remains firewalled from it, ensuring the robustness of the whole ecosystem. ## Learn more[​](#learn-more "Direct link to Learn more") More details on the various ways sidechains interact, how they might support each other via merged staking, and the detailed logic behind the firewall property discussed above can be found in the research paper [Proof-of-Stake Sidechains](https://eprint.iacr.org/2018/1239). --- > For the complete documentation index, see [llms.txt](/llms.txt) # UTXO model The UTXO model is a different way to reason about digital value. If the account model feels familiar because it mirrors traditional banking, UTXO can feel unfamiliar at first. Once you understand it, the design trade-offs become clear and explain why Midnight uses it as a foundation for privacy and parallelism. UTXO stands for "Unspent Transaction Output." Think of each UTXO as a discrete digital coin, similar to physical cash in a wallet. Each has a specific value, belongs to a specific owner, and must be spent in its entirety. This constraint enables several of the model's most useful properties. ## The digital cash metaphor[​](#the-digital-cash-metaphor "Direct link to The digital cash metaphor") The cash metaphor is not only a teaching tool; it closely maps to how UTXOs work: Imagine you're at a coffee shop and your latte costs $3.50. You reach into your wallet and find you have: * One $20 bill * One $5 bill * Two $1 bills You can't tear the $5 bill to extract exactly $3.50. Instead, you must hand over the entire $5 bill and receive $1.50 in change. The original $5 bill leaves your possession forever—it's been "consumed" in the transaction—and you receive new bills as change. The UTXO model implements this exact pattern digitally: ``` // Your wallet contains discrete UTXOs (like bills): AliceWallet = [ UTXO_1: { value: 100 NIGHT, id: "abc123..." }, UTXO_2: { value: 50 NIGHT, id: "def456..." }, UTXO_3: { value: 25 NIGHT, id: "ghi789..." } ] // To send 60 NIGHT, you must consume entire UTXOs: Transaction { inputs: [UTXO_1], // Consume the 100 NIGHT UTXO entirely outputs: [ { value: 60, recipient: Bob }, // Payment { value: 40, recipient: Alice } // Change back to yourself ] } ``` ## Core UTXO concepts[​](#core-utxo-concepts "Direct link to Core UTXO concepts") The following principles explain how the UTXO model works in Midnight. ### UTXOs are indivisible[​](#utxos-are-indivisible "Direct link to UTXOs are indivisible") This is not only a design choice; it is a core property of the model. Each UTXO is treated as a complete unit: ``` // This is IMPOSSIBLE in UTXO systems: ❌ UTXO_100.spend(30) // Can't spend part of a UTXO // You MUST do this instead: ✅ Transaction { inputs: [UTXO_100], // Consume entirely outputs: [ { value: 30, owner: recipient }, { value: 70, owner: self } // Change ] } ``` This indivisibility enables atomic transactions, parallel processing, and, in Midnight, support for shielded tokens. ### The nullifier set in Midnight[​](#the-nullifier-set-in-midnight "Direct link to The nullifier set in Midnight") Midnight differs from Bitcoin in how it tracks spent outputs. Instead of only marking UTXOs as spent, Midnight uses a nullifier set: ``` // When a UTXO is spent in Midnight: 1. UTXO_abc123 is consumed in a transaction 2. A nullifier is computed: nullifier = Hash(UTXO_abc123, ownerSecret) 3. This nullifier is added to the global nullifier set 4. Future transactions check: isNullified(UTXO) before accepting // The nullifier set grows over time: NullifierSet = { "0xn1a2b3c4...", // From spent UTXO_1 "0xn5d6e7f8...", // From spent UTXO_2 "0xn9g0h1i2...", // From spent UTXO_3 // ... millions more } ``` This approach is important because: * **No pruning requirement**: Unlike Bitcoin, Midnight does not rely on pruning spent outputs from historical data. * **Privacy compatible**: A nullifier can be validated without publicly linking to the spent UTXO. * **Double-spend protection**: Once a nullifier appears in the set, that spend cannot be accepted again. * **Efficient verification**: Nodes can check membership efficiently during validation. ### Transaction atomicity through output creation[​](#transaction-atomicity-through-output-creation "Direct link to Transaction atomicity through output creation") Every UTXO transaction is atomic: all inputs are consumed and all outputs are created together, or nothing happens. ``` // A multi-party payment showcasing atomicity: Transaction { inputs: [ UTXO_A: 100 NIGHT, // From Alice UTXO_B: 50 NIGHT // Also from Alice ], outputs: [ { value: 40, owner: Bob }, { value: 30, owner: Carol }, { value: 20, owner: Dave }, { value: 60, owner: Alice } // Change ] } // Either ALL of this happens, or NONE of it does ``` ### The UTXO lifecycle in Midnight[​](#the-utxo-lifecycle-in-midnight "Direct link to The UTXO lifecycle in Midnight") Understanding the lifecycle helps explain why this model is effective: ``` // 1. BIRTH: UTXO created in a transaction NewUTXO = { value: 100 NIGHT, owner: AlicePublicKey, id: Hash(transaction, outputIndex), commitment: PedersenCommit(value, randomness) // For privacy } // 2. LIFE: UTXO exists in the unspent set UnspentSet.add(NewUTXO) // Can be queried, proven, but not modified // 3. DEATH: UTXO consumed in a transaction Transaction.consume(NewUTXO) nullifier = ComputeNullifier(NewUTXO, AlicePrivateKey) NullifierSet.add(nullifier) // 4. AFTERLIFE: Nullifier prevents resurrection if (NullifierSet.contains(nullifier)) { reject("UTXO already spent!") } ``` ## Why this system[​](#why-this-system "Direct link to Why this system") Account balances can look simpler at first glance. In practice, the UTXO model provides advantages that become clear when building for privacy, concurrency, and provability. ### Parallelism as a model property[​](#parallelism-as-a-model-property "Direct link to Parallelism as a model property") The UTXO model naturally enables parallelism: ``` // Account Model: Forced Sequential Processing // These transactions MUST process in order: Tx1: Alice.balance -= 50 // Must complete first Tx2: Alice.balance -= 30 // Must wait for Tx1 // Why? Both modify the same global state // UTXO Model: Natural Parallel Processing // These transactions can process SIMULTANEOUSLY: Tx1: Consume UTXO_A (50 NIGHT) → Send to Bob Tx2: Consume UTXO_B (30 NIGHT) → Send to Carol // Why? They touch completely independent objects ``` This is more than a minor optimization. In high-throughput scenarios, this architectural difference can materially increase throughput. ### Privacy built into the foundation[​](#privacy-built-into-the-foundation "Direct link to Privacy built into the foundation") The UTXO model naturally supports privacy features that are harder to implement in account-based systems: ``` // Account Model: Everything linked to one address AliceAccount: { balance: 1000, history: [every transaction ever] } // Privacy requires complex workarounds // UTXO Model: Natural isolation UTXO_1: { value: 100, owner: AddressA } // For receiving salary UTXO_2: { value: 50, owner: AddressB } // For online shopping UTXO_3: { value: 25, owner: AddressC } // For donations // Shielded and unshielded token UTXOs can be used as required ``` In Midnight, token UTXOs can be shielded or unshielded, which lets users choose privacy at the transaction level rather than at the account level. ### State management and efficiency[​](#state-management-and-efficiency "Direct link to State management and efficiency") The UTXO approach to state differs from account models: ``` // What nodes need to track: ActiveState = { // Account Model: Every account that exists accounts: Map, // Grows forever // UTXO Model: Only unspent outputs utxos: Set, // Naturally bounded nullifiers: Set // Prevents double-spends } // The key insight: In UTXO, spent history can be archived // In accounts, all history affects current state ``` ## Deep comparison[​](#deep-comparison "Direct link to Deep comparison") This comparison summarizes practical implications: | Aspect | Account model | UTXO model | Why it matters for Midnight | | ----------------------- | -------------------------- | --------------------------- | ----------------------------------- | | Value storage | Single mutable balance | Immutable discrete coins | Enables shielded tokens | | Transaction model | State updates | State transitions | Natural audit trail and provability | | Concurrency | Lock → Process → Unlock | No locks needed | Massive throughput potential | | Privacy approach | Mix entire balance | Shielded token UTXOs | Granular privacy control | | Double-spend prevention | Balance arithmetic check | Nullifier set membership | Works even with hidden values | | State growth | Unbounded (all accounts) | Bounded (active UTXOs only) | Long-term sustainability | | Determinism | Depends on execution order | Order-independent | Predictable outcomes | ## Key insights: the UTXO paradigm shift[​](#key-insights-the-utxo-paradigm-shift "Direct link to Key insights: the UTXO paradigm shift") The UTXO model is more than a different way to track balances. It changes how value flow is modeled: * From mutable to immutable: Instead of changing balances in place, the system creates and consumes discrete values. This supports strong auditability and proof systems. * From sequential to parallel: By avoiding shared balance updates, the model enables natural concurrency across independent UTXOs. * From monolithic to granular: Each UTXO is independent, enabling fine-grained control over privacy, spending, and ownership. * From accounts to capabilities: UTXOs can represent value, rights, or other discrete digital assets. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Web3 Web3 is often described as an evolution of the internet centered on decentralization, transparency, and user control. Unlike Web2, which relies heavily on centralized platforms and intermediaries, Web3 uses blockchain infrastructure to support decentralized interactions. It enables users to interact directly with decentralized applications (DApps) and services without relying on a central operator. At its core, Web3 aims to return control of data, identity, and digital assets to individuals. ## Smart contracts and Midnight's approach[​](#smart-contracts-and-midnights-approach "Direct link to Smart contracts and Midnight's approach") A *smart contract* is a program stored on a blockchain that executes predefined logic when specific conditions are met. Smart contracts reduce reliance on intermediaries and support transparent, auditable workflows. Midnight uses smart contracts together with zero-knowledge (ZK) technology to enable stronger data protection in Web3 applications. ## Data protection and identity management[​](#data-protection-and-identity-management "Direct link to Data protection and identity management") As internet usage has become pervasive, data protection has become a core concern. Individuals and organizations face heightened risk as more data moves online. Web3 can help users and organizations regain control of their data, but robust solutions that bridge Web2 and Web3 are still evolving. Midnight aims to help developers build privacy-preserving smart contracts with ZK technology. Its approach is grounded in Universally Composable (UC) privacy and UC security principles. Midnight offers Web3 capabilities that support secure interactions with DApps and decentralized platforms: * **Decentralization**: Data is distributed across multiple nodes rather than centralized servers, reducing single points of failure and improving resilience. * **Immutability**: Data committed on Midnight is tamper-resistant and cannot be changed unilaterally, which supports integrity and auditability. * **Encryption and privacy**: Midnight uses ZKP techniques to protect sensitive data. Users control their private keys, which control access to assets and private actions. * **Selective disclosure**: Users can disclose only the minimum necessary information to DApps and services, which helps reduce unnecessary data exposure. * **Metadata protection**: Midnight also protects metadata. On many blockchains, transaction metadata is broadly observable. Features such as shielded tokens reduce metadata leakage, helping DApps protect sensitive metadata alongside confidential payload data. To see how privacy blockchains work as a category, including the techniques and platforms across the wider ecosystem, see [how privacy blockchains work](/concepts/how-privacy-blockchains-work.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Zero-knowledge proofs A zero-knowledge proof (ZKP) lets someone prove knowledge of a secret without revealing the secret itself. For example, a ZKP can prove that an attribute lies within a range without revealing its exact value. A client of a dApp or service can use ZKPs to selectively disclose information from a self-sovereign identity while keeping other attributes private. For example, consider a person voting in a local election. They must reside within the electorate, be on the voter roll, and not have voted already. In a conventional process, they may need to show documents that disclose their home address, date of birth, and full name. In addition, each voter is marked on the roll as they vote, which can introduce coercion risk under poor governance. In a zero-knowledge setting, using a digital ID and an appropriate application, the citizen can prove that their address is within the required area, they are registered to vote, and they have not voted already, without disclosing personally identifiable information. In general, ZKPs can prove statements such as: * A company is not on a sanctions list * A customer is over 28 years of age * A customer has purchased over €1m of product in the past year. In cases like these, the assertion can be proven without revealing other information. ## ZK Snarks[​](#zk-snarks "Direct link to ZK Snarks") Midnight uses zero-knowledge succinct non-interactive arguments of knowledge (zk-SNARKs), a class of ZKPs designed for compact proofs and efficient verification. Two key properties are: * **Succinctness**: Proof size remains small relative to the size of the statement, which enables efficient verification and reduced data transfer. * **Non-interactivity**: The prover can generate a proof without back-and-forth interaction with the verifier, unlike interactive proof systems that require multiple communication rounds. ### How do ZK Snarks work?[​](#how-do-zk-snarks-work "Direct link to How do ZK Snarks work?") Because ZK Snarks are non-interactive arguments of knowledge, they let a prover demonstrate a statement's validity without ongoing interaction with a verifier. Proof generation and verification use advanced cryptographic constructions, including elliptic-curve-based techniques. The high-level process looks as follows: ![zk-snarks](https://ucarecdn.com/bacf5357-29d7-490e-8b13-ed13c671efaf/) The process typically includes: * **Setup phase**: The system establishes public parameters used by the proving and verification algorithms. These parameters are critical to scheme security and correctness. * **Key components**: ZK Snarks use specialized cryptographic components (for example, elliptic-curve-based constructions and hashing primitives) to enable compact proofs. * **Circuit construction**: The statement is encoded as an arithmetic circuit that defines operations and constraints. * **Witness and proof generation**: The prover uses the private witness, the circuit, and public parameters to generate a proof that the statement is valid without revealing witness data. * **Verification**: The verifier uses the proof, public parameters, and statement to efficiently check validity. ## Related comparisons[​](#related-comparisons "Direct link to Related comparisons") * [ZK vs FHE vs MPC](/concepts/zk-vs-fhe-vs-mpc.md): how zero-knowledge proofs compare to fully homomorphic encryption and secure multi-party computation. * [zk-SNARK vs zk-STARK](/concepts/zk-snark-vs-zk-stark.md): a deep dive into the two main zero-knowledge proof systems. * [Fully homomorphic encryption](/concepts/fully-homomorphic-encryption.md): how FHE works and how it compares to the zero-knowledge approach. --- > For the complete documentation index, see [llms.txt](/llms.txt) # zk-SNARK vs zk-STARK: which approach do privacy-focused blockchains use? zk-SNARKs and zk-STARKs are both types of zero-knowledge proofs, but they differ in trusted setup requirements, proof size, and quantum resistance. The better choice depends on the application: neither is superior for every workload. Midnight uses zk-SNARKs through Compact, a domain-specific smart contract language based on TypeScript. ## Comparison at a glance[​](#comparison-at-a-glance "Direct link to Comparison at a glance") | | zk-SNARK | zk-STARK | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **Trusted setup** | Some constructions require a one-time trusted setup that produces a Common Reference String. Universal setups, used by PLONK-style systems with KZG commitments, are shared across all circuits. Transparent constructions, such as Halo 2, avoid a ceremony entirely | Not required; relies on publicly verifiable randomness | | **Proof size** | Small, often under a kilobyte | Larger than most zk-SNARKs, typically tens to hundreds of kilobytes | | **Verification time** | Fast, close to constant regardless of computation size | Grows polylogarithmically with computation size; on very large computations, STARK systems can outperform SNARKs despite larger proofs | | **Post-quantum resistance** | Most constructions rely on elliptic-curve assumptions and are not considered quantum-resistant | Considered quantum-resistant, since STARKs rely on hash functions | | **Example platforms** | Midnight (Compact), Zcash (Halo 2), Aztec (Noir) | Starknet (Cairo), built on StarkWare's proving stack | Platform examples verified August 2026. Some systems combine both approaches; see below. ## What is a zk-SNARK?[​](#what-is-a-zk-snark "Direct link to What is a zk-SNARK?") A zk-SNARK is a succinct, non-interactive zero-knowledge proof. Succinct means the proof stays small relative to the statement it proves, and non-interactive means the prover generates it without back-and-forth rounds with the verifier. Constructions differ in how they handle setup. Earlier systems, such as Groth16, require a trusted setup ceremony for every circuit to produce a Common Reference String. PLONK-style systems with KZG commitments run one universal ceremony whose output serves every circuit. Transparent constructions, such as Halo 2, replace the trusted setup with an inner-product-argument commitment scheme that needs only public parameters, and use recursive proof accumulation to keep verification efficient. Platforms built on zk-SNARKs include Midnight, Zcash, whose current shielded protocol uses Halo 2, and Aztec, which builds zk-SNARK-based rollups with its Noir language. ZKsync wraps STARK-generated proofs in a final SNARK for cheap verification on Ethereum, and Loopring, Ethereum's first zk-rollup, used zk-SNARKs until it shut down in 2026. ## What is a zk-STARK?[​](#what-is-a-zk-stark "Direct link to What is a zk-STARK?") A zk-STARK is a zero-knowledge proof that requires no trusted setup, a property known as transparency. It relies on publicly verifiable randomness and hash functions rather than elliptic-curve assumptions, which is also why STARKs are considered quantum-resistant. The tradeoff is size: STARK proofs are larger than most SNARK proofs. Proving scales quasilinearly with computation size and verification grows only polylogarithmically, so STARKs shine on very large computations. Starknet, with its Cairo language, is the flagship production deployment of StarkWare's proving stack. ## zk-SNARK vs zk-STARK: the key differences[​](#zk-snark-vs-zk-stark-the-key-differences "Direct link to zk-SNARK vs zk-STARK: the key differences") **Trusted setup.** Many zk-SNARK constructions depend on a Common Reference String from a one-time ceremony; if a ceremony were compromised, false proofs would in theory become possible. Universal setups reduce the exposure to a single, shared, updatable ceremony, and transparent SNARKs such as Halo 2 remove the ceremony entirely. zk-STARKs never need one. **Proof size.** SNARK proofs are small, often a few hundred bytes, which keeps on-chain verification cheap. STARK proofs are orders of magnitude larger. **Verification time and scaling.** SNARK verification stays close to constant no matter how large the computation. STARK verification grows polylogarithmically, and on very large computations the whole STARK pipeline can come out ahead. **Post-quantum resistance.** Most SNARKs rely on elliptic-curve assumptions that quantum computers could eventually weaken. STARKs rely on hash functions and are considered quantum-resistant. **Typical platforms.** zk-SNARKs power Midnight, Zcash, and Aztec. zk-STARKs power Starknet. Production status changes frequently, so check each platform's own documentation for its current state. ## Which is better for real-world applications?[​](#which-is-better-for-real-world-applications "Direct link to Which is better for real-world applications?") Neither, universally. zk-SNARKs suit applications that need small proofs and fast verification, such as most privacy-preserving smart contracts and shielded transactions today. zk-STARKs suit applications that want to avoid a trusted setup entirely or need post-quantum resistance, at the cost of larger proofs. Some systems use both. ZKsync proves with a STARK-based prover and wraps the result in a final SNARK so Ethereum can verify it cheaply. The combination captures STARK-style proving scalability and SNARK-style verification cost. ## Why Midnight uses zk-SNARKs[​](#why-midnight-uses-zk-snarks "Direct link to Why Midnight uses zk-SNARKs") Compact compiles to zk-SNARK circuits, chosen for practical, developer-accessible smart contract privacy with small proofs and fast verification. Midnight's proving system is a PLONK-family zk-SNARK using KZG polynomial commitments over the BLS12-381 curve. It relies on a universal, one-time setup: a public structured reference string shared by all circuits, so no per-circuit ceremony is needed. Proofs are generated locally by default through the proof server, and the network verifies them on-chain. This is Midnight's chosen tradeoff, not a claim that zk-SNARKs are universally better than zk-STARKs. For how proving works in practice, see [local proving](/guides/local-proving.md), and for the broader landscape, see [ZK vs FHE vs MPC](/concepts/zk-vs-fhe-vs-mpc.md). ## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions") ### zk-SNARK vs zk-STARK: which approach is used by privacy-focused blockchains and which is better for real-world applications?[​](#zk-snark-vs-zk-stark-which-approach-is-used-by-privacy-focused-blockchains-and-which-is-better-for-real-world-applications "Direct link to zk-SNARK vs zk-STARK: which approach is used by privacy-focused blockchains and which is better for real-world applications?") Both are zero-knowledge proof systems, but they differ in tradeoffs. zk-SNARKs, used by platforms including Midnight, Zcash, and Aztec, offer small proofs and fast verification, which suits most privacy-preserving smart contracts today. zk-STARKs, used by Starknet, avoid the need for a trusted setup and are considered quantum-resistant, at the cost of larger proof sizes. The better approach depends on whether trusted setup avoidance and post-quantum resistance, or smaller proofs and faster verification, matter more for the application. ### What is the difference between zk-SNARK and zk-STARK?[​](#what-is-the-difference-between-zk-snark-and-zk-stark "Direct link to What is the difference between zk-SNARK and zk-STARK?") zk-SNARKs are succinct, non-interactive zero-knowledge proofs; many rely on a one-time trusted setup and produce small proofs that verify in near-constant time. zk-STARKs skip the trusted setup entirely, using publicly verifiable randomness instead, and are built on hash functions that make them considered quantum-resistant, but their proofs are larger. ### Do zk-SNARKs need a trusted setup?[​](#do-zk-snarks-need-a-trusted-setup "Direct link to Do zk-SNARKs need a trusted setup?") Some do and some do not. Earlier constructions, such as Groth16, require a trusted setup ceremony for every circuit, and a compromised ceremony could in theory allow false proofs. PLONK-style constructions with KZG commitments need only one universal ceremony shared across all circuits, and transparent constructions, such as Halo 2, need none. Midnight's proving system is a PLONK-family zk-SNARK with KZG commitments and uses a one-time universal setup whose public parameters every circuit shares. ### Are zk-STARKs quantum-resistant?[​](#are-zk-starks-quantum-resistant "Direct link to Are zk-STARKs quantum-resistant?") They are considered quantum-resistant. Unlike most zk-SNARKs, which rely on elliptic-curve assumptions that quantum computers could eventually weaken, zk-STARKs rely on hash functions, which are believed to withstand quantum attacks. ### Which blockchains use zk-SNARKs vs zk-STARKs?[​](#which-blockchains-use-zk-snarks-vs-zk-starks "Direct link to Which blockchains use zk-SNARKs vs zk-STARKs?") zk-SNARKs are used by Midnight, Zcash, and Aztec, among others; Loopring, Ethereum's first zk-rollup, also used them until it shut down in 2026. zk-STARKs are pioneered by StarkWare and power Starknet, with its Cairo language. Some systems use both approaches together: ZKsync proves with STARKs and wraps the result in a SNARK for cheap on-chain verification. Adoption details change, so check each platform's own documentation for its current state. ### Does Midnight use zk-SNARKs or zk-STARKs?[​](#does-midnight-use-zk-snarks-or-zk-starks "Direct link to Does Midnight use zk-SNARKs or zk-STARKs?") Midnight uses zk-SNARKs, compiled from Compact, a domain-specific smart contract language based on TypeScript. This is Midnight's chosen tradeoff for practical, developer-accessible smart contract privacy with small proofs and fast verification, not a claim that zk-SNARKs are universally superior to zk-STARKs. To go deeper on Midnight's model, see [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md), the [glossary](/glossary.md), and the [Midnight Academy](https://academy.midnight.network). ## Sources[​](#sources "Direct link to Sources") * [Midnight proof system (midnight-zk)](https://github.com/midnightntwrk/midnight-zk): Midnight's PLONK-family zk-SNARK implementation with KZG commitments. * [Compact compiler](https://github.com/LFDT-Minokawa/compact): the Compact language and its zero-knowledge circuit output. * [Explaining Halo 2](https://electriccoin.co/blog/explaining-halo-2/): the transparent zk-SNARK construction from Electric Coin Co. * [NU5 activates on mainnet](https://electriccoin.co/blog/nu5-activates-on-mainnet-eliminating-trusted-setup-and-launching-a-new-era-for-zcash/): Zcash's move to Halo 2. * [Scalable, transparent, and post-quantum secure computational integrity](https://eprint.iacr.org/2018/046.pdf): the original zk-STARK paper. * [StarkWare STARK overview](https://starkware.co/stark/) and [Starknet documentation](https://docs.starknet.io): the flagship zk-STARK deployment. * [ZKsync documentation](https://docs.zksync.io): a system combining STARK proving with SNARK verification. * [Aztec documentation](https://docs.aztec.network): reference documentation for the zk-SNARK-based Aztec rollup. --- > For the complete documentation index, see [llms.txt](/llms.txt) # ZK vs FHE vs MPC: which should you use for a privacy-focused DApp? Zero-knowledge proofs (ZK), fully homomorphic encryption (FHE), and secure multi-party computation (MPC) are three different approaches to privacy-preserving computation, each with different tradeoffs. The right choice depends on what needs to stay private and what performance profile your application can tolerate. Midnight uses zero-knowledge proofs, specifically zk-SNARKs, through Compact, a domain-specific smart contract language based on TypeScript. This page compares the three cryptographic approaches in depth. For the category-level view first, see [how privacy blockchains work](/concepts/how-privacy-blockchains-work.md). ## Comparison at a glance[​](#comparison-at-a-glance "Direct link to Comparison at a glance") | | Zero-knowledge proofs (ZK) | Fully homomorphic encryption (FHE) | Secure multi-party computation (MPC) | | ------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | **What it protects** | Proves a statement is true without revealing the underlying data | Allows computation directly on encrypted data | Allows multiple parties to jointly compute over combined private inputs | | **Where computation happens** | The prover generates a proof, locally by default; the network verifies it on-chain | Directly on ciphertext, by a single computing party | Distributed across multiple non-colluding parties | | **Typical performance profile today** | Cost concentrates in proof generation; practical for smart contract logic | Overhead applies to every operation on encrypted data; an active area of optimization | Requires coordination and communication between parties; overhead scales with party count | | **Example platforms** | Midnight (Compact), Aztec (Noir), Aleo (Leo), Mina, Starknet (Cairo), ZKsync | Zama (TFHE-rs, Concrete, FHEVM), Fhenix, Duality Technologies, OpenFHE, Microsoft SEAL | Partisia Blockchain, Lit Protocol, Threshold Network | | **Typical use case today** | Private smart contracts, selective disclosure, identity proofs | Encrypted data processing, confidential analytics, confidential smart contracts | Threshold key management, distributed signing, joint computation without a trusted party | Platform examples verified August 2026. Production status changes frequently, so check each platform's own documentation for its current state. ## What is a zero-knowledge proof (ZK)?[​](#what-is-a-zero-knowledge-proof-zk "Direct link to What is a zero-knowledge proof (ZK)?") A zero-knowledge proof lets one party prove that a statement is true without revealing the data behind it. For example, a proof can show that a transaction follows the rules of a smart contract without exposing the transaction's contents. Midnight, Aztec, and Aleo use zk-SNARKs, a proof type with small proofs and fast verification, to power private smart contracts. Other zero-knowledge platforms include Mina, which builds its whole chain on recursive zk-SNARKs, and Starknet, which uses zk-STARKs with its Cairo language. ZKsync combines both: a STARK-based prover produces the proofs, and a final SNARK makes them cheap to verify on Ethereum. For a deeper introduction, see [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md), and for the two proof systems compared in depth, see [zk-SNARK vs zk-STARK](/concepts/zk-snark-vs-zk-stark.md). ## What is fully homomorphic encryption (FHE)?[​](#what-is-fully-homomorphic-encryption-fhe "Direct link to What is fully homomorphic encryption (FHE)?") Fully homomorphic encryption is a form of encrypted computation. It allows computation directly on encrypted data: the result of computing on ciphertexts matches the result of the same computation on the plaintext, without ever decrypting the input. No party performing the computation sees the underlying data. FHE platforms and libraries include Zama, which provides the TFHE-rs and Concrete libraries and the FHEVM for confidential smart contracts on Ethereum, and Fhenix, which offers an FHE coprocessor for EVM chains, currently on testnet. Duality Technologies applies FHE to enterprise data collaboration. OpenFHE is the actively maintained general-purpose open-source library, and Microsoft SEAL is a historically important library whose development has slowed. Inco is building toward an FHE protocol; its live product, Inco Lightning, runs on trusted execution environments. For a deeper look, see [fully homomorphic encryption](/concepts/fully-homomorphic-encryption.md). ## What is secure multi-party computation (MPC)?[​](#what-is-secure-multi-party-computation-mpc "Direct link to What is secure multi-party computation (MPC)?") Secure multi-party computation allows multiple parties to jointly compute a function over their combined private inputs. No single party sees another party's raw input. The technique relies on splitting data or keys across participants, so privacy holds as long as the parties do not collude. MPC platforms include Partisia Blockchain, which runs MPC smart contracts on its own mainnet, Lit Protocol, which provides threshold key management using MPC with hardware-protected nodes, and Threshold Network, the threshold cryptography network behind tBTC. Trusted execution environments (TEEs) are sometimes grouped with MPC by mistake. The industry often labels this approach confidential computing. Platforms such as Oasis Sapphire, Secret Network, and Inco Lightning run computation inside attested hardware enclaves. That is a hardware trust model, not a cryptographic protocol, so this page treats TEEs as their own category. ## How ZK, FHE, and MPC compare[​](#how-zk-fhe-and-mpc-compare "Direct link to How ZK, FHE, and MPC compare") **What stays private.** ZK keeps the underlying data private and reveals only the proven statement. FHE keeps the data encrypted throughout the computation. MPC keeps each party's input private from the other parties. **Where computation happens.** ZK computation runs where the data lives, and only the proof travels. FHE computation runs on a single machine that holds ciphertext. MPC computation is spread across several machines that must stay online and communicate. **Performance.** Both FHE and ZK carry substantial overhead relative to plaintext execution, but they pay it in different places. FHE incurs its cost on every operation performed over encrypted data, while ZK systems concentrate their cost in proof generation, which happens once per interaction. MPC pays its cost in network communication, which grows with the number of parties. All three are active areas of optimization across the industry. **Developer tooling.** ZK smart contract tooling is comparatively mature: purpose-built languages such as Compact on Midnight, Noir on Aztec, and Leo on Aleo mean you do not write circuits by hand. FHE tooling is younger and centers on libraries and Solidity extensions, such as Zama's FHEVM. MPC tooling is typically platform-specific, as on Partisia. **Typical use cases.** ZK suits private smart contracts, identity proofs, and selective disclosure. FHE suits encrypted data processing and confidential analytics. MPC suits threshold key management, distributed signing, and joint computation between organizations that do not trust each other. ## Can ZK, FHE, and MPC be combined?[​](#can-zk-fhe-and-mpc-be-combined "Direct link to Can ZK, FHE, and MPC be combined?") Yes. They solve overlapping but distinct problems, and hybrid designs are an active area of industry research and development. For example, an application can use MPC for key management alongside zero-knowledge proofs for transaction privacy, and some FHE designs use zero-knowledge proofs to show that encrypted inputs are well formed. ## Why Midnight uses zero-knowledge proofs[​](#why-midnight-uses-zero-knowledge-proofs "Direct link to Why Midnight uses zero-knowledge proofs") Midnight chose zero-knowledge proofs for practical, developer-accessible smart contract privacy. Compact compiles to zk-SNARK circuits, and the protocol separates public and private state at the protocol level. Private data stays with the user: proofs are generated locally by default through the proof server, and only the proof and public data reach the chain. This programmable privacy model also supports what Midnight calls rational privacy. Applications keep data confidential by default and disclose selectively when a business or compliance need requires it. This is Midnight's chosen tradeoff for building private DApps today, not a claim that ZK is universally superior to FHE or MPC for every use case. To go deeper on Midnight's model, see [zero-knowledge proofs](/concepts/zero-knowledge-proofs.md), the [glossary](/glossary.md), and the [Midnight Academy](https://academy.midnight.network). For the developer entry point, see the [Midnight Developer Hub](https://midnight.network/developer-hub). ## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions") ### ZK vs FHE vs MPC: which should I use for building a privacy-focused DApp?[​](#zk-vs-fhe-vs-mpc-which-should-i-use-for-building-a-privacy-focused-dapp "Direct link to ZK vs FHE vs MPC: which should I use for building a privacy-focused DApp?") It depends on what needs to stay private and what performance your application can tolerate. Zero-knowledge proofs suit applications that need to prove a statement is true without revealing the underlying data, such as private smart contracts and identity checks. Fully homomorphic encryption suits scenarios that require computing directly on encrypted data, at a per-operation cost. Secure multi-party computation suits scenarios where multiple parties jointly compute a result without any one party seeing the others' raw inputs, such as threshold key management. ### What platforms support ZK, FHE, and MPC for building privacy-preserving DApps?[​](#what-platforms-support-zk-fhe-and-mpc-for-building-privacy-preserving-dapps "Direct link to What platforms support ZK, FHE, and MPC for building privacy-preserving DApps?") ZK-based platforms include Midnight, Aztec, Aleo, Mina, Starknet, and ZKsync. FHE-based platforms and libraries include Zama, Fhenix, Duality Technologies, OpenFHE, and Microsoft SEAL, with Inco building toward an FHE protocol. MPC-based platforms include Partisia Blockchain, Lit Protocol, and Threshold Network. Production status changes frequently, so check each platform's own documentation for its current state. ### What is the difference between ZK, FHE, and MPC?[​](#what-is-the-difference-between-zk-fhe-and-mpc "Direct link to What is the difference between ZK, FHE, and MPC?") Zero-knowledge proofs let one party prove a statement is true without revealing the data behind it. Fully homomorphic encryption lets a single party compute directly on encrypted data without decrypting it first. Secure multi-party computation lets several parties jointly compute a result over their combined private inputs, without any single party seeing the others' raw data. The three solve different problems and are not strict substitutes for each other. ### Does Midnight use FHE or ZK?[​](#does-midnight-use-fhe-or-zk "Direct link to Does Midnight use FHE or ZK?") Midnight uses zero-knowledge proofs, specifically zk-SNARKs, through Compact, a domain-specific smart contract language based on TypeScript. Midnight does not use fully homomorphic encryption. Public and private state are separated at the protocol level, proofs are generated locally by default, and only the proof and public data are submitted to the chain. ### Can ZK, FHE, and MPC be combined in the same application?[​](#can-zk-fhe-and-mpc-be-combined-in-the-same-application "Direct link to Can ZK, FHE, and MPC be combined in the same application?") Yes. They solve overlapping but distinct privacy problems, and combining them, for example using MPC for key management alongside zero-knowledge proofs for transaction privacy, is an active area of industry research. ### Which approach has the best developer experience for building a private DApp today?[​](#which-approach-has-the-best-developer-experience-for-building-a-private-dapp-today "Direct link to Which approach has the best developer experience for building a private DApp today?") This depends on the platform, not only the cryptographic approach. On the ZK side, Midnight's Compact is a statically typed language based on TypeScript, designed so developers do not need deep cryptography expertise. Other ZK, FHE, and MPC platforms have their own developer tooling, which you should evaluate on its own merits rather than assume. ## Sources[​](#sources "Direct link to Sources") * [Midnight proof system (midnight-zk)](https://github.com/midnightntwrk/midnight-zk): Midnight's zk-SNARK implementation. * [Compact compiler](https://github.com/LFDT-Minokawa/compact): the Compact language and its zero-knowledge circuit output. * [Aztec documentation](https://docs.aztec.network), [Aleo documentation](https://developer.aleo.org), [Mina documentation](https://docs.minaprotocol.com), [Starknet documentation](https://docs.starknet.io), and [ZKsync documentation](https://docs.zksync.io): zero-knowledge platform references. * [Zama documentation](https://docs.zama.org), [Fhenix](https://www.fhenix.io), [Inco](https://www.inco.org), [Duality Technologies](https://dualitytech.com), [OpenFHE](https://openfhe.org), and [Microsoft SEAL](https://github.com/microsoft/SEAL): FHE platform and library references. * [Partisia Blockchain documentation](https://partisiablockchain.gitlab.io/documentation/), [Lit Protocol documentation](https://developer.litprotocol.com), and [Threshold Network](https://threshold.network): MPC platform references. * [Oasis Sapphire](https://oasis.net) and [Secret Network](https://scrt.network): TEE-based platform references. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Zswap Supporting multiple asset types and atomic swaps is important for use cases such as decentralized finance (DeFi). Midnight uses Zswap to provide these capabilities with data protection. ## Atomic swaps[​](#atomic-swaps "Direct link to Atomic swaps") An atomic swap is an all-or-nothing transaction. Suppose Alice wants fishing gear and Bob has it in his shop. They agree on this transaction: *Rod $600.00, reel $300.00, tackle $100.00.* Alice has only $700 in cash and uses $300 in available card credit. The swap is atomic because it is only complete when Alice receives all the gear and Bob receives both forms of payment. Even in legitimate transactions, parties may have privacy requirements. Bob may want to share details with his accountant and tax authority, but not with competitors. Alice may want to share details with trusted parties, but not publicly. On a decentralized, permissionless blockchain, the same concept applies with different mechanics. Bob and Alice might exchange UTXOs, such as 600 of coin B1, 300 of B2, and 100 of B3 from Bob for 7,000,000 of coin A1 from Alice. The swap must execute atomically. If this order can move market price, an observer could front-run it. Shielded asset swaps can mitigate these attacks by reducing pre-trade visibility. ## How Zswap helps[​](#how-zswap-helps "Direct link to How Zswap helps") Midnight uses Zswap, a transaction scheme for data-protecting atomic asset swaps. Based on Zerocash concepts, Zswap enables transaction merging while preserving confidentiality. It supports multiple asset types and atomic swaps in a way that scales for DeFi-style workloads. ![swap](https://ucarecdn.com/9a01db50-4126-4844-9f51-7cfa4e3325fa/) The figure shows a simple example of Zswap in action. Alice intends to pay three dollars for five euros, while Bob intends to pay five euros for three dollars. Before broad disclosure, they use zero-knowledge proofs to preserve privacy. Zswap then merges these transactions into a single atomic swap between Alice and Bob, preserving confidentiality of sensitive details. ## Key features and benefits of Zswap[​](#key-features-and-benefits-of-zswap "Direct link to Key features and benefits of Zswap") | Feature | Benefits | | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | **Confidentiality**: Zswap uses zk-SNARKs to keep transaction data confidential. | Sender, receiver, and amount details do not need to be publicly exposed. | | **Multi-asset atomic exchange**: Zswap supports exchanging multiple assets in one atomic operation. | Either all parts of the exchange complete or none do, avoiding partial execution. | | **Efficient swaps**: Zswap uses sparse homomorphic commitments with aggregated opening randomness. | Swaps can execute efficiently across asset types. | | **Provable security**: Zswap is designed with formal security arguments. | Security properties can be reasoned about under explicit assumptions. | | **Built on established foundations**: Zswap draws from Zcash Sapling techniques and implementation experience. | This provides a strong and well-studied starting point. | In Zswap, transactions are designed to support safe merging while preserving confidentiality. Transaction data is separated from signature flow, a design inspired by the Zcash ecosystem. This separation enables non-interactive zero-knowledge proofs (NIZKs) for validation without requiring slower multi-party computation (MPC) protocols. To support multi-asset atomic swaps, Zswap uses sparse multi-value Pedersen commitments and relaxed signature requirements. Sparse commitments enable non-interactive transaction merging, including between parties with no prior trust relationship. The protocol reveals only limited imbalance information per asset class and avoids exposing exact transfer relationships. Zswap also enables local exchange-market workflows. Users submit exchange offers, and selected participants can match and merge them off-chain before on-chain submission. The matching flow reveals minimal information, and partial merges can drop asset types with zero imbalance. Larger exchange pools can improve liquidity and support order-book style coordination. Zswap contributes the following to Midnight: * **Formal model**: Zswap introduces a formal model for a multi-asset Zcash system with swaps, built on top of the One-Time Account (OTA) system, which abstracts a nullifier-like private UTXO mechanism. The OTA model and the proof techniques used in Zswap have independent significance and can be applied to proving the security of systems like Zcash and Monero. * **Practical instantiation**: Zswap provides a practical implementation of private non-interactive atomic swaps. It simplifies the Zcash framework by removing authorization and blinding signatures while preserving security. * **Security**: The Zswap construction is proven secure under commonly used assumptions similar to those employed in Zerocash. The removal of Zcash signatures is validated, demonstrating that the perfect hiding and binding properties of spend and output commitments are sufficient for ensuring security. * **Implementation and evaluation**: Zswap has been implemented and evaluated, demonstrating that the merging mechanism is highly effective and that the performance overhead compared to the basic single-asset protocol without swaps is minimal. Overall, Zswap provides a foundation for privacy-oriented, multi-asset atomic swaps in Midnight. For more details, read the [Zswap: ZK Snark Based Non-Interactive Multi-Asset Swaps’ research paper](https://eprint.iacr.org/2022/1002.pdf). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Examples Working Compact contract examples and full DApps. Each example demonstrates a specific feature or pattern. ## Browse by type[​](#browse-by-type "Direct link to Browse by type") [✦](/examples/contracts.md) ### [Contracts](/examples/contracts.md) [Standalone Compact contracts that isolate specific language features like witness functions, assertions, and on-chain verification.](/examples/contracts.md) [Browse contracts→](/examples/contracts.md) [✦](/examples/dapps.md) ### [DApps](/examples/dapps.md) [Complete DApps with contract code, TypeScript integration, and deployment steps you can use as a starting point for your own project.](/examples/dapps.md) [Browse DApps→](/examples/dapps.md) ## Find an example by feature[​](#find-an-example-by-feature "Direct link to Find an example by feature") Not sure which example to start from? Pick the feature or problem you are trying to solve from the dropdown, and the matrix highlights the example DApps and contracts that demonstrate it. You can also narrow the grid to just DApps or just contracts. Every example links straight to its documentation. Each column is a documented example (a full DApp or a standalone contract) and each row is a Compact or Midnight feature that example demonstrates. A Demonstrated marker means the example fully shows that feature, a Partial marker means it is in progress or only partially shown, and an empty cell means that example does not cover it. Browse by feature or problem All features (all) Show AllDAppsContracts | Feature / problem | [Calculator](/examples/contracts/calculator.md) | [Token transfers](/examples/contracts/token-transfers.md) | [Private guest list](/examples/contracts/private-guest-list.md) | [Election](/examples/contracts/election.md) | [Private reserve auction](/examples/contracts/private-reserve-auction.md) | [Battleship](/examples/contracts/battleship-simple.md) | [Bulletin board](/examples/dapps/bboard.md) | [ZK Loan](/examples/dapps/zkloan.md) | | ------------------------------------------------ | ----------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------- | ------------------------------------ | | Witness functions (private inputs) | | | | | | | | | | Private state | | | | | | | | | | Public ledger state | | | | | | | | | | Privacy boundary (disclose) | | | | | | | | | | On-chain verification of off-chain compute | | | | | | | | | | Access control to circuits | | | | | | | | | | Ledger Counter | | | | | | | | | | Ledger Set | | | | | | | | | | Ledger Map | | | | | | | | | | Ledger List | | | | | | | | | | Sealed ledger fields | | | | | | | | | | Standard library Maybe | | | | | | | | | | Opaque string on the ledger | | | | | | | | | | DApp-specific public keys (untrackable identity) | | | | | | | | | | Commitments and persistent hashing | | | | | | | | | | ZK proof of identity without revealing it | | | | | | | | | | In-circuit signature verification | | | | | | | | | | Native token (NIGHT) operations | | | | | | | | | | Shielded token operations | | | | | | | | | | Intermediate witnesses | | | | | | | | | | Explicit state machine (enums) | | | | | | | | | | Multi-step approval or turn flow | | | | | | | | | | CLI tooling | | | | | | | | | | Web UI | | | | | | | | | | Wallet and proof server integration | | | | | | | | | Demonstrated Partial or in progress Not covered DApp Contract note This matrix covers the examples that have published documentation. When a new example is added to the docs, add it here too: coverage data lives in `src/components/CoverageMatrix/data.jsx`. To contribute a new example, see the [contributing guide](https://github.com/midnightntwrk/midnight-docs/blob/main/CONTRIBUTING.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Contract examples Standalone Compact contracts that each demonstrate a specific language feature. These are not production-ready implementations. Use them to learn a feature in isolation before combining patterns in your own contracts. Looking for a specific feature? The [Examples overview](/examples.md) maps every example to what it demonstrates. [✦](/examples/contracts/calculator.md) ### [Calculator](/examples/contracts/calculator.md) [Witness functions and on-chain verification of off-chain computation with assert statements.](/examples/contracts/calculator.md) [View calculator→](/examples/contracts/calculator.md) [✦](/examples/contracts/token-transfers.md) ### [Token transfers](/examples/contracts/token-transfers.md) [Mint, send, and receive shielded and unshielded tokens using NIGHT token operations in Compact.](/examples/contracts/token-transfers.md) [View token transfers→](/examples/contracts/token-transfers.md) [✦](/examples/contracts/private-guest-list.md) ### [Private guest list](/examples/contracts/private-guest-list.md) [Set operations, native NIGHT token handling, and the privacy boundary in Midnight DApps.](/examples/contracts/private-guest-list.md) [View guest list→](/examples/contracts/private-guest-list.md) [✦](/examples/contracts/election.md) ### [Election](/examples/contracts/election.md) [Commit to private state, use Set and Map operations, and generate DApp-specific public keys.](/examples/contracts/election.md) [View election→](/examples/contracts/election.md) [✦](/examples/contracts/private-reserve-auction.md) ### [Private reserve auction](/examples/contracts/private-reserve-auction.md) [Hide reserve prices on the public ledger and reduce user trackability with DApp-specific keys.](/examples/contracts/private-reserve-auction.md) [View auction→](/examples/contracts/private-reserve-auction.md) [✦](/examples/contracts/battleship-simple.md) ### [Battleship](/examples/contracts/battleship-simple.md) [Explicit state management, private state verification, access control, List operations, and intermediate witnesses.](/examples/contracts/battleship-simple.md) [View Battleship→](/examples/contracts/battleship-simple.md) --- # Battleship Simple Version > For the complete documentation index, see [llms.txt](/llms.txt) This Compact contract implements a simple version of the game Battleship. Ships are represented by a number and the game board is represented as a single number line. This contract offers demonstration of the following features: * Explicit state management * Verification of private state data * Access control to circuits * Operations on a `List` * Intermediate witness functionality For the full DApp example with complete frontend test suite, see [example-battleship](https://github.com/midnightntwrk/example-battleship). ``` // Battleship: Two-player ZK game. Player 1 deploys (sets ships). // Player 2 joins via acceptGame(). Turn order: // PLAYER_1_SHOOT → PLAYER_2_CHECK → PLAYER_2_SHOOT → PLAYER_1_CHECK → repeat // Ship locations are committed via persistentHash; ZK proves honest hit/miss reports. // Win condition: 2 hits on the opponent's ships. pragma language_version 0.23; import CompactStandardLibrary; export enum BoardState { UNSET, SET } export enum ShotState { MISS, HIT } export enum TurnState { PLAYER_1_SHOOT, PLAYER_1_CHECK, PLAYER_2_SHOOT, PLAYER_2_CHECK, } export enum WinState { CONTINUE_PLAY, PLAYER_1_WINS, PLAYER_2_WINS } export ledger player1: Bytes<32>; export ledger player2: Bytes<32>; export ledger turn: TurnState; export ledger board1: Set>;// linear board shape export ledger board2: Set>;// hashed storage of ship locations export ledger board1State: BoardState; export ledger board2State: BoardState; export ledger player1Shot: List>;// current shot export ledger player2Shot: List>; export ledger board1Hits: Set>;// previous hits stored for later assertions export ledger board2Hits: Set>; export ledger winState: WinState; export ledger board1HitCount: Counter; export ledger board2HitCount: Counter; witness localSk(): Bytes<32>; witness localSetBoard(_x1: Uint<8>, _x2: Uint<8>): BoardState; witness localCheckBoard(x: Uint<8>): ShotState; constructor(_x1: Uint<8>, _x2: Uint<8>) { // input verification checks assert(_x1 != _x2, "Cannot use the same number twice"); assert(_x1 > 0 && _x2 > 0, "No zero index, board starts at 1"); assert(_x1 <= 20 && _x2 <= 20, "Out of bounds, please keep ships on the board"); // user id and assignment const _sk = localSk(); const pubKey = getDappPubKey(_sk); player1 = disclose(pubKey); // hash the inputs to verify them later, user needs to provide the same value and _sk const hash1 = commitBoardSpace(_x1 as Bytes<32>, _sk); board1.insert(hash1); const hash2 = commitBoardSpace(_x2 as Bytes<32>, _sk); board1.insert(hash2); // best practice example -- don't disclose(localSetBoard(_x1, _x2)), // disclose only what you need (localBoardState); const localBoardState = localSetBoard(_x1, _x2); assert(localBoardState == BoardState.SET, "Please update the state of board1 to SET"); board1State = disclose(localBoardState); // setting initial states board2State = BoardState.UNSET; winState = WinState.CONTINUE_PLAY; } export circuit acceptGame(_x1: Uint<8>, _x2: Uint<8>): [] { // caller verification checks const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player1 != disclose(pubKey), "You cannot play against yourself"); // state verification check assert(board2State == BoardState.UNSET, "There is already a player2"); // input verification checks assert(_x1 != _x2, "Cannot use the same number twice"); assert(_x1 > 0 && _x2 > 0, "No zero index, please keep ships on the board"); assert(_x1 <= 20 && _x2 <= 20, "Out of bounds, please keep ships on the board"); // user assignment player2 = disclose(pubKey); // hash inputs and store them to the ledger for comparison later const hash1 = commitBoardSpace(_x1 as Bytes<32>, _sk); board2.insert(hash1); const hash2 = commitBoardSpace(_x2 as Bytes<32>, _sk); board2.insert(hash2); // setting the state locally and verifying const localBoardState = localSetBoard(_x1, _x2); assert(localBoardState == BoardState.SET, "Please update the state of your board to SET"); // setting on-chain state board2State = disclose(localBoardState); // updating on-chain state turn = TurnState.PLAYER_1_SHOOT; } export circuit player1Shoot (x: Uint<8>): [] { // caller verification check const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player1 == disclose(pubKey), "You are not player1"); // state verification checks assert(board2State == BoardState.SET, "Player 2 has not yet set their board"); assert(turn == TurnState.PLAYER_1_SHOOT, "It is not player1 turn to shoot"); assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); // input validation assert(x > 0 && x <= 20, "Shot out of bounds, please shoot on the board"); // shots are public knowledge const currentShot = disclose(x); assert(!board2Hits.member(currentShot), "Cheat Detected: Player1: Attempt to repeat a previous HIT"); // on-chain state updates player1Shot.pushFront(currentShot); turn = TurnState.PLAYER_2_CHECK; } export circuit player2Shoot(x: Uint<8>): [] { // caller verification checks const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player2 == disclose(pubKey), "You are not player2"); // state verification checks assert(turn == TurnState.PLAYER_2_SHOOT, "It is not player2 turn to shoot"); assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); // input validation assert(x > 0 && x <= 20, "Shot out of bounds, please shoot on the board"); // shots are public knowledge const currentShot = disclose(x); assert(!board1Hits.member(currentShot), "Cheat Detected: Player2: Attempt to repeat a previous HIT"); // on-chain state updates player2Shot.pushFront(currentShot); turn = TurnState.PLAYER_1_CHECK; } export circuit checkBoard1(): [] { // caller verification check const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player1 == disclose(pubKey), "You are not player1"); // state verification checks assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); assert(turn == TurnState.PLAYER_1_CHECK, "It is not Player 1 turn to CHECK"); assert(!player2Shot.isEmpty(), "No shot to check"); // shot processing const currentShot = player2Shot.head().value; assert(!board1Hits.member(currentShot), "Cheat Detected: Player2: Attempt to repeat a previous HIT"); player2Shot.popFront(); // hash for comparison with on-chain hash const honestyCheckHash = commitBoardSpace(currentShot as Bytes<32>, _sk); // currentShot has already been exposed, but we need to satisfy the compiler here too const shotState = disclose(localCheckBoard(currentShot)); assert(shotState == ShotState.HIT || shotState == ShotState.MISS, "Please provide a valid state"); // conditional handling if(shotState == ShotState.MISS){ // don't trust, verify assert(!board1.member(honestyCheckHash), "Cheat Detected: Player 1: claimed a MISS, when it was in fact a HIT"); turn = TurnState.PLAYER_1_SHOOT; } else { // don't trust, verify assert(board1.member(honestyCheckHash), "Cheat Detected: Player 1: claimed a HIT, when is was in fact a MISS. Why would they do that?"); board1HitCount.increment(1); board1Hits.insert(currentShot); turn = TurnState.PLAYER_1_SHOOT; // did someone win? winState = board1HitCount == 2 ? WinState.PLAYER_2_WINS : WinState.CONTINUE_PLAY; } } export circuit checkBoard2(): [] { // caller verification const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player2 == disclose(pubKey), "You are not player2"); // state verification assert(board2State == BoardState.SET, "Player 2 has not set the board yet"); assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); assert(turn == TurnState.PLAYER_2_CHECK, "It is not Player 2 turn to CHECK"); assert(!player1Shot.isEmpty(), "No shot to check"); // shot processing const currentShot = player1Shot.head().value; assert(!board2Hits.member(currentShot), "Cheat Detected: Player 1: Attempt to repeat a previous HIT"); player1Shot.popFront(); // on-chain board comparison hash const honestyCheckHash = commitBoardSpace(currentShot as Bytes<32>, _sk); // state return verification const shotState = disclose(localCheckBoard(currentShot)); assert(shotState == ShotState.HIT || shotState == ShotState.MISS, "Please provide a valid state"); // conditional handling if(shotState == ShotState.MISS){ // don't trust, verify assert(!board2.member(honestyCheckHash), "Cheat Detected: Player 2: claimed a MISS, when it was in fact a HIT"); turn = TurnState.PLAYER_2_SHOOT; } else { // don't trust, verify assert(board2.member(honestyCheckHash), "Cheat Detected: Player 2: claimed a HIT, when it was in fact a MISS. Why would they do that?"); board2HitCount.increment(1); board2Hits.insert(currentShot); turn = TurnState.PLAYER_2_SHOOT; // did someone win? winState = board2HitCount == 2 ? WinState.PLAYER_1_WINS : WinState.CONTINUE_PLAY; } } // hashing a commitment to a board space circuit commitBoardSpace(_x: Bytes<32>, _sk: Bytes<32>): Bytes<32> { const hash = persistentHash>>([_x, _sk]); return disclose(hash); } // hashing a Dapp specific public key to track user interaction (only within this dapp) circuit getDappPubKey(_sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "battleship:pk:"), _sk]); } ``` --- # Calculator Contract > For the complete documentation index, see [llms.txt](/llms.txt) This Compact contract implements a simple calculator. It offers demonstration of the following features: * Witness function * On-chain verification of off-chain compute Notice that `divMod` only has the declaration of the function signature. Its logic is implemented in the Typescript frontend and is unknown to contract, though we can enforce expected execution through `assert` statements in `divide`. ``` pragma language_version 0.23; export ledger result: Uint<16>; export circuit add(num1: Uint<16>, num2: Uint<16>): [] { result = disclose(num1 + num2 as Uint<16>); } export circuit subtract(num1: Uint<16>, num2: Uint<16>): [] { result = disclose(num1 - num2 as Uint<16>); } export circuit multiply(num1: Uint<16>, num2: Uint<16>): [] { result = disclose(num1 * num2 as Uint<16>); } export circuit square(num1: Uint<16>): [] { result = disclose(num1 * num1 as Uint<16>); } // declare an off-chain function expected to divide two numbers witness divMod(num1: Uint<16>, num2: Uint<16>): [Uint<16>, Uint<16>]; // enforce correct logic on-chain for off-chain logic in divMod circuit divide(num1: Uint<16>, num2: Uint<16>): Uint<16> { const [quo, rem] = divMod(num1, num2); assert(rem < num2 && quo * num2 + rem == num1, "incorrect division"); return quo; } ``` --- # Election Contract > For the complete documentation index, see [llms.txt](/llms.txt) This Compact contract implements an election that occurs between two candidates and a set of registered voters. It offers demonstration of the following features: * Committing to private state information * Operations on `Set` and `Map` * Dapp specific public key function that keeps users from being tracked outside this dapp ``` pragma language_version 0.23; import CompactStandardLibrary; export enum VotingState { CLOSED, OPEN } // are there other choices? export enum VoteChoice { BAD, WORSE, TIE } // sealed ledger values cannot be changed after constructor execution export sealed ledger organizer: Bytes<32>; export sealed ledger candidate0: Opaque<"string">; export sealed ledger candidate1: Opaque<"string">; export ledger votingState: VotingState; export ledger hashedVoteMap: Map, Bytes<32>>; export ledger registeredVoters: Set>; export ledger totalVoteCount: Counter; export ledger candidate0VoteCounter: Counter; export ledger candidate1VoteCounter: Counter; export ledger winner: VoteChoice; witness localGetVote(): VoteChoice; witness localSk(): Bytes<32>; constructor(candidateA: Opaque<"string">, candidateB: Opaque<"string">) { const _sk = localSk(); const pubKey = getDappPubKey(_sk); organizer = pubKey; candidate0 = disclose(candidateA); candidate1 = disclose(candidateB); votingState = VotingState.CLOSED; // open to register to vote } // should be available time based export circuit registerToVote(): [] { const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(!registeredVoters.member(pubKey), "You are already registered to vote"); assert(votingState == VotingState.CLOSED, "You can only register before voting starts"); registeredVoters.insert(pubKey); } export circuit openVoting(): [] { const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(organizer == pubKey, "You are not the organizer"); assert(votingState == VotingState.CLOSED, "Voting has already been openend"); assert(!registeredVoters.isEmpty(), "There are no registered voters"); votingState = VotingState.OPEN; } export circuit commitVote(): [] { assert(votingState == VotingState.OPEN, "Voting has not opened yet"); const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(registeredVoters.member(pubKey), "You are not registered to vote."); assert(!hashedVoteMap.member(pubKey), "Attempt to double vote"); const _currentVote = localGetVote(); assert(_currentVote == VoteChoice.BAD || _currentVote == VoteChoice.WORSE, "Please provide a valid vote"); const hash = commitWithSk(_currentVote as Field as Bytes<32>, _sk); hashedVoteMap.insert(pubKey, hash); totalVoteCount.increment(1); } // check privateState for original vote, if its changed then error export circuit revealVote(): [] { assert(votingState == VotingState.CLOSED, "Voting is still open"); const _sk = localSk(); const pubKey = getDappPubKey(_sk); // we want to check that they have already voted.. assert(hashedVoteMap.member(pubKey), "You have not voted yet"); assert(registeredVoters.member(pubKey), "You are not a registered voter"); const vote = localGetVote(); assert(vote == VoteChoice.BAD || vote == VoteChoice.WORSE, "Please supply a valid vote"); // here is the money const hashedVote = commitWithSk(vote as Field as Bytes<32>, _sk); assert(hashedVoteMap.lookup(pubKey) == hashedVote, "Attempt to change the vote!"); if(disclose(vote) == VoteChoice.BAD){ candidate0VoteCounter.increment(1); } else if (disclose(vote) == VoteChoice.WORSE) { candidate1VoteCounter.increment(1); } } // should be time based export circuit closeVoting(): [] { const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(organizer == pubKey, "You are not the organizer"); assert(!hashedVoteMap.isEmpty(), "You can't close the voting with no votes"); votingState = VotingState.CLOSED; } export circuit checkWinner(): [] { const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(organizer == pubKey, "You are not an organizer"); assert(votingState == VotingState.CLOSED, "Voting is still open"); // check for a winner if(candidate0VoteCounter > candidate1VoteCounter) { winner = VoteChoice.BAD; } else if (candidate0VoteCounter < candidate1VoteCounter) { winner = VoteChoice.WORSE; } else if (candidate0VoteCounter == candidate1VoteCounter) { winner = VoteChoice.TIE; } } // hashing commitment with _sk makes it impossible to brute force a simple 1 or 2 circuit commitWithSk(_vote: Bytes<32>, _sk: Bytes<32>) : Bytes<32> { return disclose(persistentHash>>([_vote, _sk])); } // hash a random "public key" that is only traceable in this dapp circuit getDappPubKey(_sk: Bytes<32>): Bytes<32> { return disclose(persistentHash>>([pad(32, "election:pk:"), _sk])); } ``` --- # Private Guest List Contract > For the complete documentation index, see [llms.txt](/llms.txt) This Compact contract implements a party with a private guest list. It offers demonstration of the following features: * Operations on a `Set` * Native token (NIGHT) operations * Privacy boundary in Midnight DApps ``` pragma language_version 0.23; import CompactStandardLibrary; export enum PartyState { NOT_STARTED, READY, STARTED, DOORS_CLOSED, FEES_CLAIMED } export sealed ledger organizer: Bytes<32>; export sealed ledger maxListSize: Uint<16>; export sealed ledger entryFee: Uint<16>; export ledger partyState: PartyState; export ledger hashedPartyGoers: Set>; export ledger checkedInParty: Set; witness localSecret(): Bytes<32>; constructor (partySize: Uint<16>, fee: Uint<16>) { const _secret = localSecret(); const pubKey = getDappPublicKey(_secret); organizer = disclose(pubKey); assert(partySize > 0, "The party size must be greater than zero"); assert(fee > 0, "Fee must be greater than zero"); entryFee = disclose(fee); maxListSize = disclose(partySize); partyState = PartyState.NOT_STARTED; } // called by party goers export circuit rsvp(_address: UserAddress): [] { const _secret = localSecret(); const pubKey = getDappPublicKey(_secret); // caller authentication check assert(pubKey != organizer, "Organizer cannot RSVP to the party"); // state verification check assert(partyState == PartyState.NOT_STARTED, "The party has already started"); assert(hashedPartyGoers.size() < maxListSize, "The list is full"); // party goer address remains private const commitHash = commitAddress(_secret, _address.bytes); assert(!hashedPartyGoers.member(commitHash), "You are already on the list"); hashedPartyGoers.insert(commitHash);// doesn't need disclose bc persistentCommit if (hashedPartyGoers.size() == maxListSize) { // @TODO -- In the future, emit an event to the organizer here (MIP-0002) partyState = PartyState.READY; } } // start the party (organizer) export circuit startParty(): [] { const _secret = localSecret(); const pubKey = getDappPublicKey(_secret); assert(organizer == pubKey, "Only the organizer can start the party"); assert(partyState == PartyState.READY || partyState == PartyState.NOT_STARTED, "The party is not in the correct state for this operation"); partyState = PartyState.STARTED; } export circuit closeEntry(): [] { const _secret = localSecret(); const pubKey = getDappPublicKey(_secret); assert(organizer == pubKey, "Only organizer can close the doors"); assert(partyState == PartyState.STARTED, "Party in wrong state"); partyState = PartyState.DOORS_CLOSED; } // called by the party goer, so the payment can be prompted to the caller // after the execution of this circuit, party goers are public export circuit checkIn(address: UserAddress): [] { // state verification checks assert(partyState == PartyState.STARTED, "The party has not been started. Call the party police"); assert(checkedInParty.size() < hashedPartyGoers.size(), "All guests have already checked in"); const _secret = localSecret(); const commitHash = commitAddress(_secret, address.bytes); // caller verification checks assert(hashedPartyGoers.member(commitHash), "You are not on the list"); assert(!checkedInParty.member(disclose(address)), "You have already checked in"); // take in unshielded payment, party goers are now public receiveUnshielded(nativeToken(), entryFee as Uint<128>); checkedInParty.insert(disclose(address)); if(checkedInParty.size() == maxListSize) { partyState = PartyState.DOORS_CLOSED; } } export circuit claimFees(address: UserAddress): [] { const _secret = localSecret(); const pubKey = getDappPublicKey(_secret); assert(organizer == pubKey, "You are not the organizer"); // state verification checks assert(partyState == PartyState.DOORS_CLOSED, "The doors are not yet closed"); assert(checkedInParty.size() > 0, "No fees to claim"); // calculate contract balance of NIGHT tokens const totalCollected = checkedInParty.size() * entryFee; assert(unshieldedBalanceGte(nativeToken(), totalCollected), "Contract balance wrong"); // send to organizer sendUnshielded( nativeToken(), disclose(totalCollected) as Uint<128>, right(disclose(address)) ); partyState = PartyState.FEES_CLAIMED; } circuit commitAddress(_secret: Bytes<32>, _address: Bytes<32>): Bytes<32> { return persistentCommit>(_address, _secret); } // hash a publicKey specific to this DApp so that users cannot be tracked // the _secret should be a highly complex one circuit getDappPublicKey(_secret: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "private-party:pk:"), _secret]); } ``` --- # Private Reserve Auction Contract > For the complete documentation index, see [llms.txt](/llms.txt) This Compact contract implements an auction with a private reserve that also maintains the privacy of bidders with bid amounts as public information. It offers demonstration of the following features: * Hiding information on the public ledger * Reducing user trackability with specific DApp public keys * Operations on a `Map` ``` pragma language_version 0.23; import CompactStandardLibrary; export enum AuctionState { CLOSED, OPEN } export sealed ledger auctionOrganizer: Bytes<32>; export sealed ledger hiddenPrice: Bytes<32>; export sealed ledger maxBids: Uint<16>; export ledger publicPrice: Uint<16>; export ledger bidders: Map, Uint<16>>;// unique bidders, overwriting bids allowed export ledger bidCount: Counter;// number of bids export ledger highestBid: Uint<16>; export ledger auctionState: AuctionState; witness localSk(): Bytes<32>; constructor(_minPrice: Uint<16>, maxBidCount: Uint<16>) { const _sk = localSk(); const pubKey = getDappPubKey(_sk); auctionOrganizer = disclose(pubKey); const hashedPrice = commitWithSk(_minPrice as Bytes<32>, _sk); maxBids = disclose(maxBidCount); hiddenPrice = hashedPrice; highestBid = 0; auctionState = AuctionState.OPEN; } // bidders can bid more than once export circuit bid(bidAmount: Uint<16>): [] { assert(bidCount < maxBids, "Sorry, bids are full"); assert(auctionState == AuctionState.OPEN, "The auction has ended"); const _sk = localSk(); const key = getDappPubKey(_sk); const pubKey = disclose(key); const publicBid = disclose(bidAmount); if(bidders.member(pubKey)){ assert(bidders.lookup(pubKey) < publicBid, "New bid lower than your previous bid"); } bidders.insert(pubKey, publicBid); bidCount.increment(1); if(publicBid > highestBid){ highestBid = publicBid; } if(bidCount == maxBids){ auctionState = AuctionState.CLOSED; } } // allow the organizer to close the auction if maxBids is not reached export circuit closeAuction(minPrice: Uint<16>): Uint<16> { const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(disclose(pubKey) == auctionOrganizer, "You are not the auction organizer"); assert(auctionState == AuctionState.OPEN, "The auction has already been closed"); auctionState = AuctionState.CLOSED; return revealWin(minPrice); } export circuit revealWin(minPrice: Uint<16>): Uint<16> { const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(auctionOrganizer == disclose(pubKey), "You are not the auction organizer"); assert(auctionState == AuctionState.CLOSED, "The auction is still open"); const hashedPrice = commitWithSk(minPrice as Bytes<32>, _sk); assert(hashedPrice == hiddenPrice, "Attempt to change min price detected, shame on you."); // all votes are in, public price can be revealed publicPrice = disclose(minPrice); // if the publicPrice is not met, the highestBid doesn't matter if(highestBid < publicPrice){ return 0; } else { return highestBid; } } circuit commitWithSk(_minPrice: Bytes<32>, _sk: Bytes<32>): Bytes<32> { const hash = persistentHash>>([_minPrice, _sk]); return disclose(hash); } // hash a "public key" specific to this DApp so that users cannot be tracked circuit getDappPubKey(_sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "silent-auction:pk:"), _sk]); } ``` --- # Shielded and Unshielded Token Transfers > For the complete documentation index, see [llms.txt](/llms.txt) This Compact contract implements send, receive and mint functions for tokens in Compact. It offers demonstration of the following features: * Minting and receiving unshielded tokens to the contract * Sending unshielded tokens to a user * Receiving unshielded tokens * Night token operations * Shielded token operations ``` import CompactStandardLibrary; // Mint using mintUnshieldedToken() + receiveUnshielded() export circuit mintAndReceive(amount: Uint<64>): Bytes<32> { const domain = pad(32, "simple:receive"); const color = mintUnshieldedToken( disclose(domain), disclose(amount), left(kernel.self()) ); return color; } // Send to user address export circuit sendToUser(amount: Uint<64>, user_addr: UserAddress): [] { const domain = pad(32, "simple:receive"); const color = tokenType(disclose(domain), kernel.self()); sendUnshielded( color, disclose(amount) as Uint<128>, right(disclose(user_addr)) ); } export circuit receiveTokens(amount: Uint<128>): [] { const domain = pad(32, "simple:receive"); const color = tokenType(domain, kernel.self()); receiveUnshielded(color, disclose(amount)); } export circuit receiveNightTokens(amount: Uint<128>): [] { receiveUnshielded(default>, disclose(amount)); } export circuit sendNightTokensToUser(amount: Uint<64>, user_addr: UserAddress): [] { sendUnshielded( default>, disclose(amount) as Uint<128>, right(disclose(user_addr)) ); } export circuit receiveShieldedTokens(coin: ShieldedCoinInfo): [] { receiveShielded(disclose(coin)); } export circuit sendShieldedToUser(input: QualifiedShieldedCoinInfo, publicKey: ZswapCoinPublicKey, value: Uint<128>): ShieldedSendResult { return sendShielded(disclose(input), left(disclose(publicKey)), disclose(value)); } export circuit mintShieldedToSelf(domainSep: Bytes<32>, value: Uint<64>, nonce: Bytes<32>): ShieldedCoinInfo { return mintShieldedToken(disclose(domainSep), disclose(value), disclose(nonce), right(kernel.self())); } export circuit mintAndSendShielded(domainSep: Bytes<32>, mintValue: Uint<64>, mintNonce: Bytes<32>, publicKey: ZswapCoinPublicKey, sendValue: Uint<128>): ShieldedSendResult { const coin = mintShieldedToken(disclose(domainSep), disclose(mintValue), disclose(mintNonce), right(kernel.self())); const qualified = QualifiedShieldedCoinInfo { nonce: coin.nonce, color: coin.color, value: coin.value, mt_index: 0 as Uint<64> }; return sendShielded(qualified, left(disclose(publicKey)), disclose(sendValue)); } ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # DApp examples Complete DApp examples with contract code, TypeScript integration, and deployment steps. Study the architecture, then adapt the patterns to your own project. Looking for a specific feature? The [Examples overview](/examples.md) maps every example to what it demonstrates. [✦](/examples/dapps/bboard.md) ### [Bulletin board DApp](/examples/dapps/bboard.md) [Privacy-preserving message posting with ZK proofs for identity verification and cryptographic access control.](/examples/dapps/bboard.md) [View bulletin board DApp→](/examples/dapps/bboard.md) [✦](/examples/dapps/zkloan.md) ### [ZK Loan DApp](/examples/dapps/zkloan.md) [Evaluate loan eligibility against private credit data. The credit score and income never leave your machine.](/examples/dapps/zkloan.md) [View ZK Loan DApp→](/examples/dapps/zkloan.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Bulletin board DApp The bulletin board contract demonstrates privacy-preserving smart contracts on Midnight using the Compact language. This example shows how to create a contract that allows users to post and remove messages while protecting poster identity through Zero Knowledge (ZK) proofs. The bulletin board example is a privacy-focused DApp that introduces key Midnight concepts: * Writing smart contracts with private state in Compact * Using ZK proofs to verify identity without revealing it * Implementing access control through cryptographic commitments By the end of this guide, you will understand how the bulletin board contract enforces privacy rules and how to deploy and interact with the contract through the CLI. ## The bulletin board scenario[​](#the-bulletin-board-scenario "Direct link to The bulletin board scenario") Imagine a traditional cork bulletin board on an office wall with room for just one piece of paper. The office rules are simple: * Anyone can post a message when the board is vacant. * Once someone posts a message, only that person can remove it. The challenge is implementing these rules online while protecting user identity. Traditional systems require users to transmit identity credentials to a server for verification. Midnight offers a better approach: users prove their identity locally through ZK proofs without transmitting private data across the network. ## DApp architecture[​](#dapp-architecture "Direct link to DApp architecture") The bulletin board example uses a modular structure with three main components: ``` example-bboard/ ├── contract/ # Smart contract in Compact language │ ├── src/bboard.compact # The actual smart contract │ └── src/test/ # Contract unit tests ├── api/ # Application logic shared by interfaces │ └── src/ # Core DApp functionality ├── bboard-cli/ # Command-line interface │ └── src/ # CLI implementation └── bboard-ui/ # Web browser interface └── src/ # React-based UI ``` ## The bulletin board contract[​](#the-bulletin-board-contract "Direct link to The bulletin board contract") The bulletin board contract is written in Compact. It demonstrates how to build a privacy-preserving application where users can prove ownership of posted content without revealing their identity. Here is the complete contract: ``` pragma language_version 0.23; import CompactStandardLibrary; export enum State { VACANT, OCCUPIED } export ledger state: State; export ledger message: Maybe>; export ledger sequence: Counter; export ledger owner: Bytes<32>; constructor() { state = State.VACANT; message = none>(); sequence.increment(1); } witness localSecretKey(): Bytes<32>; export circuit post(newMessage: Opaque<'string'>): [] { assert(state == State.VACANT, "Attempted to post to an occupied board"); owner = disclose(publicKey(localSecretKey(), sequence as Field as Bytes<32>)); message = disclose(some>(newMessage)); state = State.OCCUPIED; } export circuit takeDown(): Opaque<'string'> { assert(state == State.OCCUPIED, "Attempted to take down post from an empty board"); assert(owner == publicKey(localSecretKey(), sequence as Field as Bytes<32>), "Attempted to take down post, but not the current owner"); const formerMsg = message.value; state = State.VACANT; sequence.increment(1); message = none>(); return formerMsg; } export circuit publicKey(sk: Bytes<32>, sequence: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "bboard:pk:"), sequence, sk]); } ``` The contract consists of three main components: ### Ledger state[​](#ledger-state "Direct link to Ledger state") Four public fields track the bulletin board state on-chain: * `state`: A `State` enum indicating whether the board is `VACANT` or `OCCUPIED`. * `message`: A `Maybe>` type that contains the current posted message, or `none` if the board is vacant. * `sequence`: A `Counter` that increments each time a post is taken down, preventing replay attacks. * `owner`: A 32-byte cryptographic commitment that represents the current poster's identity without revealing who they are. ### Circuits[​](#circuits "Direct link to Circuits") Three exported circuits define the contract's operations: * `post(newMessage)`: Posts a new message to the board. Checks that the board is vacant, then stores the message and creates an ownership commitment. * `takeDown()`: Removes the current message and returns it. Verifies that the caller is the original poster by checking their secret key against the ownership commitment. * `publicKey(sk, sequence)`: A helper circuit that generates the ownership commitment from a secret key and sequence number using a persistent hash. ### Witness[​](#witness "Direct link to Witness") The contract defines one witness function, `localSecretKey()`, which returns the user's secret key during circuit execution without exposing it on-chain or in the generated proof. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before working with the bulletin board example, ensure that you have: * Node.js version 22 or higher * Docker Desktop installed and running * Compact toolchain installed * Command-line familiarity For more information, refer to [install the toolchain](/examples/getting-started/installation). ## Set up the example[​](#set-up-the-example "Direct link to Set up the example") This section explains the process of setting up and running the bulletin board DApp locally. ### Clone the repository[​](#clone-the-repository "Direct link to Clone the repository") Get the bulletin board example from GitHub: ``` git clone https://github.com/midnightntwrk/example-bboard.git cd example-bboard ``` ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") Install all required Node.js packages: ``` npm install ``` This command installs packages for the contract, API, CLI, and UI components. ## Start the proof server[​](#start-the-proof-server "Direct link to Start the proof server") The proof server generates ZK proofs for transactions locally to protect private data. It must be running before you can deploy or interact with contracts. Start the proof server: ``` docker run -p 6300:6300 midnightntwrk/proof-server:8.0.3 -- midnight-proof-server -v ``` tip The proof server *must* stay active while using the DApp. ## Compile the contract[​](#compile-the-contract "Direct link to Compile the contract") Open a new terminal window, navigate to the `contract` directory, and install the contract-specific dependencies: ``` cd contract npm install ``` Compile the contract by running the `compact` script: ``` npm run compact ``` The `npm run compact` script runs the following command: ``` compact compile src/bboard.compact src/managed/bboard ``` This command compiles the contract and builds the TypeScript API and JavaScript implementation. You should see the following output: ``` > compact compile src/bboard.compact src/managed/bboard Compiling 2 circuits: circuit "post" (k=13, rows=4569) circuit "takeDown" (k=13, rows=4580) ``` The compiled artifacts are placed in the `src/managed/bboard` directory. ``` src/ ├── bboard.compact ├── managed │ └── bboard │ ├── compiler │ ├── contract │ ├── keys │ └── zkir ``` ## CLI interface[​](#cli-interface "Direct link to CLI interface") The command-line interface provides a text-based way to interact with the bulletin board contract. ### Launch the bulletin board CLI[​](#launch-the-bulletin-board-cli "Direct link to Launch the bulletin board CLI") Navigate to the `bboard-cli` directory and install the CLI-specific dependencies: ``` cd bboard-cli npm install ``` The `package.json` file for the `bboard-cli` folder has a script called `preprod-remote` that launches the CLI on the Preprod network. Launch the CLI by running the `preprod-remote` script: ``` npm run preprod-remote ``` The script launches the CLI and connects to the Preprod network. You should see the following output: ``` Starting test environment... Performing env health check Connected to indexer https://indexer.preprod.midnight.network/ready: "" Connected to proof server http://127.0.0.1:6300/health: {"status":"ok"} Environment started with configuration You can do one of the following: 1. Build a fresh wallet 2. Build wallet from a seed 3. Exit Which would you like to do? ``` ### Set up your wallet[​](#set-up-your-wallet "Direct link to Set up your wallet") The bulletin board CLI uses a headless wallet implementation that runs locally, separate from browser wallets like Lace Midnight Preview. #### Create a new wallet[​](#create-a-new-wallet "Direct link to Create a new wallet") Select option `1` to build a fresh wallet from the menu. The CLI generates a new wallet and displays the wallet information: ``` Initializing wallet builder for preprod Your wallet seed is: <64-character wallet seed> and your address is: Using unshielded address: waiting for funds... Your wallet initial balance is: 0 (not yet initialized) Waiting to receive tokens... Syncing wallet... ``` Save your seed phrase Store the wallet seed in a secure location. You need it to recover your wallet if needed. #### Restore an existing wallet[​](#restore-an-existing-wallet "Direct link to Restore an existing wallet") If you already have a wallet seed, then select option `2` to build wallet from a seed. Enter your wallet seed when prompted: ``` Which would you like to do? 2 Enter your wallet seed: Initializing wallet builder for preprod Building wallet without starting with configuration ``` The CLI restores your wallet and displays your addresses and balances. ### Get faucet tokens[​](#get-faucet-tokens "Direct link to Get faucet tokens") Before deploying contracts, you need tNight tokens from the faucet. 1. Copy your unshielded address from the CLI output. 2. Visit the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/). 3. Paste your unshielded address. 4. Select **Request tokens**. 5. Wait for the transaction to confirm. It usually takes 1-2 minutes. After syncing, the CLI displays your updated balances: ``` Sync complete Wallet balances after sync - Shielded: {}, Unshielded: {"0000000000000000000000000000000000000000000000000000000000000000":2000000000}, Dust: 8793832211999999997 Your NIGHT wallet balance is: 2000000000 No unregistered UTXOs found for dust generation. You can do one of the following: 1. Deploy a new bulletin board contract 2. Join an existing bulletin board contract 3. Exit Which would you like to do? ``` The wallet automatically generates tDUST network resources from your tNight holdings, which are required for contract operations. ### Deploy the contract[​](#deploy-the-contract "Direct link to Deploy the contract") With your wallet funded, deploy the bulletin board contract to Preprod. From the Contract Actions menu, select option `1` to deploy a new bulletin board contract: ``` Which would you like to do? 1 deployContract Deployed contract at address: ``` The CLI deploys your contract and displays the contract address. Transaction time Contract deployment typically takes 20-30 seconds on Preprod as the network processes your transaction and ZK proofs. ### Join an existing contract[​](#join-an-existing-contract "Direct link to Join an existing contract") If you want to interact with a contract that someone else deployed, then select option `2` to join an existing bulletin board contract. Enter the contract address when prompted: ``` Which would you like to do? 2 What is the contract address (in hex)? joinContract: { "contractAddress": "" } Joined contract at address: ``` ### Interact with the bulletin board[​](#interact-with-the-bulletin-board "Direct link to Interact with the bulletin board") Once deployed or joined, you can interact with your bulletin board contract. The bulletin board actions menu appears: ``` You can do one of the following: 1. Post a message 2. Take down your message 3. Display the current ledger state (known by everyone) 4. Display the current private state (known only to this DApp instance) 5. Display the current derived state (known only to this DApp instance) 6. Exit Which would you like to do? ``` #### Check the current state[​](#check-the-current-state "Direct link to Check the current state") Select option `3` to display the current ledger state and see what everyone can see: ``` Which would you like to do? 3 Current state is: 'vacant' Current message is: 'none' Current sequence is: 1 Current owner is: '0000000000000000000000000000000000000000000000000000000000000000' ``` The board initializes to vacant when the contract is deployed. The owner field shows zeros because no one has posted yet. #### View private state[​](#view-private-state "Direct link to View private state") Select option `4` to display the current private state that only you can see: ``` Which would you like to do? 4 Current secret key is: ``` This displays your secret key that is used to generate cryptographic commitments. This key never leaves your local machine. #### Post a message[​](#post-a-message "Direct link to Post a message") Select option `1` to post a message from the menu. Enter your message when prompted: ``` Which would you like to do? 1 What message do you want to post? Welcome to Midnight postingMessage: Welcome to Midnight ``` The CLI: 1. Generates a cryptographic commitment to your identity using your secret key 2. Creates a ZK proof proving you followed the contract rules 3. Submits the proof to Preprod 4. Waits for transaction confirmation Privacy protection Your identity is never revealed on-chain. The cryptographic commitment in the `owner` field cannot be reverse-engineered to discover your identity, but you can regenerate it to prove ownership. #### View the posted message[​](#view-the-posted-message "Direct link to View the posted message") Select option `3` to display the current ledger state again: ``` Which would you like to do? 3 Current state is: 'occupied' Current message is: 'Welcome to Midnight' Current sequence is: 1 Current owner is: '' ``` The message is now visible to anyone who queries the contract. The state changed to `occupied`, and the owner field now contains your cryptographic commitment. #### Attempt to post when occupied[​](#attempt-to-post-when-occupied "Direct link to Attempt to post when occupied") Try posting another message when the board is occupied: ``` Which would you like to do? 1 What message do you want to post? Testing Preprod BBoard postingMessage: Testing Preprod BBoard Found error 'Unexpected error executing scoped transaction '': Error: failed assert: Attempted to post to an occupied board' ``` The contract enforces rule 1: no one can post when the board is occupied. The transaction fails locally before ever reaching the network, saving network resources. #### Take down your message[​](#take-down-your-message "Direct link to Take down your message") Select option `2` to take down your message: ``` Which would you like to do? 2 Taking down message... Message taken down successfully ``` The CLI: 1. Regenerates your cryptographic commitment using your secret key and the current sequence number 2. Proves it matches the stored `owner` value 3. Submits a ZK proof of this verification 4. Removes the message and resets the board to vacant Only poster can remove If you try to take down someone else's message, the transaction fails. The contract enforces this through ZK proof verification that happens before submission. #### Verify removal[​](#verify-removal "Direct link to Verify removal") Check the board state again: ``` Which would you like to do? 3 Current state is: 'vacant' Current message is: 'none' Current sequence is: 2 Current owner is: '0000000000000000000000000000000000000000000000000000000000000000' ``` The board is vacant again, and the sequence counter has incremented to 2. This means the next post will use sequence number 2 in its cryptographic commitment. #### Exit the CLI[​](#exit-the-cli "Direct link to Exit the CLI") Select option `6` to exit when you're done: ``` Which would you like to do? 6 Exiting... Stopping wallet... Stopping test environment... Shutting down test environment... ``` The CLI safely shuts down the wallet and stops the test environment. ## Next steps[​](#next-steps "Direct link to Next steps") Now that you understand the bulletin board example: * **Explore the GitHub repository**: [Bulletin board repository](https://github.com/midnightntwrk/example-bboard) * **Build the contract yourself**: Learn how to [build the bulletin board smart contract](/tutorials/bboard/smart-contract.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Leaderboard DApp The leaderboard smart contract demonstrates privacy-preserving score tracking on Midnight using the Compact language. This example shows how to create a DApp that lets players submit scores with configurable privacy modes while protecting player identity through zero-knowledge (ZK) proofs. The leaderboard example introduces key Midnight concepts: * Writing smart contracts with structured on-chain data using `Map` and custom structs in Compact * Using ZK proofs to verify entry ownership without revealing the owner's secret key * Implementing multiple privacy modes through conditional witness invocation * Building a browser-based frontend that connects to the Lace wallet By the end of this guide, you will understand how the leaderboard contract enforces privacy rules and how to build and interact with the full DApp in your browser. ## The leaderboard scenario[​](#the-leaderboard-scenario "Direct link to The leaderboard scenario") Imagine an arcade leaderboard where players want to record their high scores. The rules are straightforward: * Anyone can submit a score at any time. * Each entry stores a score, a display name, and an ownership commitment. * Players choose how their display name appears: a custom name, their public address, or an anonymous generated name like "Crimson Tiger." * Only the original submitter can prove ownership of their entry using a ZK proof. The challenge is enforcing ownership rules while giving players full privacy control. Traditional systems require storing the player's identity on a server. Midnight offers a better approach: players prove ownership locally through ZK proofs without transmitting private data across the network. ## DApp architecture[​](#dapp-architecture "Direct link to DApp architecture") The leaderboard example uses a monorepo structure with three workspace packages and a Docker configuration for the proof server. ``` midnight-leaderboard/ ├── contract/ # Compact smart contract and TypeScript bindings │ ├── leaderboard.compact # The smart contract │ └── src/ │ ├── index.ts # Contract exports and witness wiring │ └── witnesses.ts # Witness provider ├── api/ # Shared business logic (platform-agnostic) │ └── src/ │ ├── index.ts # LeaderboardAPI class │ ├── common-types.ts # Shared types and provider interfaces │ └── utils/index.ts # Display name decoder ├── leaderboard-ui/ # React and Vite browser DApp │ └── src/ │ ├── App.tsx # Game UI, leaderboard, and wallet connection │ ├── main.tsx # Entry point with Buffer polyfill │ ├── contexts/ # Lace wallet provider bridge │ └── hooks/ # Indexer read hook └── proof-server/ # Docker config for the proof server └── Dockerfile ``` ## The leaderboard contract[​](#the-leaderboard-contract "Direct link to The leaderboard contract") The leaderboard contract is written in Compact. It demonstrates how to build a privacy-preserving application where players can submit scores with configurable display names and prove ownership of their entries without revealing their identity. Here is the complete contract: ``` pragma language_version 0.23; import CompactStandardLibrary; struct ScoreEntry { score: Uint<64>, displayName: Bytes<32>, ownerHash: Bytes<32> } export ledger scores: Map, ScoreEntry>; export ledger nextId: Counter; witness localSecretKey(): Bytes<32>; witness getCustomName(): Bytes<32>; export circuit ownerCommitment(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "leaderboard:owner:"), sk]); } export circuit submitScore( score: Uint<64>, useCustomName: Boolean ): [] { const sk = localSecretKey(); const ownerHash = ownerCommitment(sk); nextId.increment(1); const entryId = disclose(nextId.read() as Uint<64>); if (disclose(useCustomName)) { const customName = getCustomName(); scores.insert(entryId, ScoreEntry { score: disclose(score), displayName: disclose(customName), ownerHash: disclose(ownerHash) }); } else { scores.insert(entryId, ScoreEntry { score: disclose(score), displayName: disclose(persistentHash>(sk)), ownerHash: disclose(ownerHash) }); } } export circuit verifyOwnership(targetEntryId: Uint<64>): [] { assert(scores.member(disclose(targetEntryId)), "entry not found"); const entry = scores.lookup(disclose(targetEntryId)); const callerHash = ownerCommitment(localSecretKey()); assert(callerHash == entry.ownerHash, "not the owner"); } ``` The contract consists of three main components. ### Ledger state[​](#ledger-state "Direct link to Ledger state") Two public fields track the leaderboard state on-chain: * `scores`: A `Map, ScoreEntry>` that stores all submitted entries, keyed by an auto-incrementing ID. Each `ScoreEntry` holds a score, a display name, and an ownership commitment. * `nextId`: A `Counter` that auto-increments to assign a unique ID to each new entry. ### Circuits[​](#circuits "Direct link to Circuits") Three exported circuits define the contract's operations: * `ownerCommitment(sk)`: A helper circuit that derives an on-chain identity from your secret key using `persistentHash`. It produces a deterministic commitment that you can store and verify later without revealing the secret. * `submitScore(score, useCustomName)`: Creates a new leaderboard entry. It retrieves your secret key via the `localSecretKey` witness, computes the owner commitment, and inserts a new `ScoreEntry` into `scores`. The `useCustomName` flag controls whether the display name comes from the `getCustomName` witness or derives directly from the secret key hash. * `verifyOwnership(targetEntryId)`: Lets you prove you own a specific entry. It looks up the entry, recomputes the owner commitment from your secret key, and asserts that it matches the stored `ownerHash`. Nothing is written to the ledger. ### Witnesses[​](#witnesses "Direct link to Witnesses") The contract defines two witness functions: * `localSecretKey()`: Returns your secret key from private state. The key never appears on-chain or in any generated proof. * `getCustomName()`: Returns a custom display name that the TypeScript host provides at runtime. The TypeScript layer decides what value to supply based on your selected privacy mode. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before working with the leaderboard example, ensure that you have: * Node.js version 22 or higher * Docker Desktop installed and running * Compact toolchain installed * Lace wallet browser extension installed For more information, refer to [install the toolchain](/getting-started/installation.md). ## Set up the example[​](#set-up-the-example "Direct link to Set up the example") ### Clone the repository[​](#clone-the-repository "Direct link to Clone the repository") Get the leaderboard example from GitHub: ``` git clone https://github.com/midnightntwrk/midnight-leaderboard.git cd midnight-leaderboard ``` ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") Install all required Node.js packages: ``` npm install ``` This command installs packages for the contract, API, and UI components. ## Start the proof server[​](#start-the-proof-server "Direct link to Start the proof server") The proof server generates ZK proofs for transactions locally to protect private data. It must be running before you can deploy or interact with contracts. Start the proof server: ``` docker run -p 6300:6300 midnightntwrk/proof-server:8.0.3 -- midnight-proof-server -v ``` Keep the proof server running The proof server must stay active while using the DApp. ## Compile the contract[​](#compile-the-contract "Direct link to Compile the contract") Open a new terminal window at the project root and navigate to the `contract` directory: ``` cd contract npm run compact ``` This command compiles the contract and generates TypeScript bindings, circuit keys, and ZKIR files in `contract/managed/leaderboard/`. You should see the following output: ``` Compiling 2 circuits: circuit "submitScore" (k=13, rows=4720) circuit "verifyOwnership" (k=13, rows=2352) ``` Build the contract and API packages: ``` cd .. npm run build ``` ## Set up the wallet[​](#set-up-the-wallet "Direct link to Set up the wallet") The browser DApp connects to the Lace wallet for on-chain transactions. 1. Install the [Lace](https://chromewebstore.google.com/detail/lace/gafhhkghbfjjkeiendhlofajokpaflmk) browser extension and create a new wallet. 2. Set the network to **Preprod**. 3. Set the proof server to `http://localhost:6300`. 4. Fund your wallet with tNIGHT from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/). 5. Go to Tokens, click **Generate tDUST**, and confirm the transaction. About tDUST You need tDUST to pay transaction fees on Preprod. The wallet generates tDUST from your tNIGHT balance. ## Run the browser DApp[​](#run-the-browser-dapp "Direct link to Run the browser DApp") Navigate to the `leaderboard-ui` directory, install dependencies, and start the development server: ``` cd leaderboard-ui npm install npm run dev ``` Open your browser at `http://localhost:3000`. The leaderboard UI loads and connects to the Preprod indexer. ## Interact with the leaderboard[​](#interact-with-the-leaderboard "Direct link to Interact with the leaderboard") ### Connect your wallet[​](#connect-your-wallet "Direct link to Connect your wallet") Click **Connect Wallet** in the top-right corner of the UI. Lace prompts you to authorize the connection. After you approve, your wallet address and tDUST balance appear in the header. ### Deploy a new contract[​](#deploy-a-new-contract "Direct link to Deploy a new contract") Click **Deploy Contract**. The UI calls `LeaderboardAPI.deploy()`, which submits a deployment transaction through Lace. Wait for the transaction to confirm on Preprod. Transaction time Contract deployment typically takes 20 to 30 seconds on Preprod as the network processes your transaction and ZK proofs. After confirmation, the contract address appears in the UI. ### Submit a score[​](#submit-a-score "Direct link to Submit a score") The game area displays a score counter. Play the game or enter a score manually, then choose a display name mode before submitting: * **Custom name**: Enter a name up to 32 characters. The `getCustomName` witness supplies this value to the circuit. * **Public address**: The `getCustomName` witness passes your wallet address as the display name. * **Anonymous**: The contract does not invoke the `getCustomName` witness. Instead, the circuit stores `persistentHash(secretKey)` as the display name. The `localSecretKey` witness is still called to compute the owner commitment. The UI renders anonymous entries as generated names like "Crimson Tiger." Click **Submit Score**. The UI: 1. Retrieves your secret key from private state via the `localSecretKey` witness. 2. Computes your owner commitment using `ownerCommitment(secretKey)`. 3. Generates a ZK proof locally via the proof server. 4. Submits the transaction through Lace. 5. Waits for confirmation and refreshes the leaderboard. Privacy protection Your secret key never leaves your machine. The proof server generates the ZK proof locally before anything is sent to the network. ### View the leaderboard[​](#view-the-leaderboard "Direct link to View the leaderboard") The leaderboard table updates automatically after each confirmed transaction. It reads state directly from the Preprod indexer without requiring a wallet connection. Anonymous entries appear with generated names. Custom and public-address entries appear as submitted. ### Verify entry ownership[​](#verify-entry-ownership "Direct link to Verify entry ownership") Click **Verify Ownership** next to any of your entries. The UI calls `verifyOwnership(entryId)`, which generates a ZK proof that your secret key matches the `ownerHash` stored in the entry. The circuit asserts the match on-chain without writing anything to the ledger. A success message confirms ownership. If your wallet does not hold the correct secret key for that entry, the assertion fails and the proof server rejects the transaction locally before it reaches the network. Same browser required Ownership verification only works from the same browser and wallet instance that submitted the entry, because the secret key lives in the local private state store. ### Read state without a wallet[​](#read-state-without-a-wallet "Direct link to Read state without a wallet") You can view the leaderboard without connecting a wallet. The UI fetches the `scores` map directly from the indexer using the `LeaderboardIndexerProvider`. This is read-only access. Score submission and ownership verification require a wallet connection. ## Next steps[​](#next-steps "Direct link to Next steps") Now that you understand the leaderboard example: * **Explore the GitHub repository**: [Leaderboard repository](https://github.com/midnightntwrk/midnight-leaderboard) * **Build the contract yourself**: Follow the complete [Leaderboard tutorial](/tutorials/leaderboard/overview.md) to build every layer of the DApp from scratch. * **Explore the bulletin board example**: The [Bulletin board DApp](/examples/dapps/bboard.md) is a simpler starting point that shows a single-state contract with a CLI interface. --- > For the complete documentation index, see [llms.txt](/llms.txt) # ZK Loan DApp The ZK Loan example shows how a loan application can be evaluated against private credit data without that data ever leaving the user's machine. A bank-style attestation provider signs the credit profile off-chain; the smart contract verifies the signature inside a zero-knowledge circuit and writes only the loan status and authorized amount to the ledger. The credit score, monthly income, employment tenure, attestation signature, and user PIN all stay private. The blockchain learns *whether* the user qualifies for which tier, never *why*. ## What this DApp demonstrates[​](#what-this-dapp-demonstrates "Direct link to What this DApp demonstrates") This example is intentionally larger than the [Bulletin board](/examples/dapps/bboard.md) DApp. It stitches together several Midnight building blocks in one place: * **Witness-provided private inputs**: TypeScript code feeds credit data into the zero-knowledge prover at proving time without exposing it on-chain. * **Schnorr-on-Jubjub signature verification inside a circuit**: a hand-rolled Compact module (replaceable with `jubjubSchnorrVerify` once it ships in the standard library) proves the credit data came from a registered attestation provider. * **PIN-derived on-chain identity**: a witness-supplied user secret is hashed with a secret PIN to produce a per-user public key, so the same user cannot be linked across loans without knowing both the secret and the PIN. * **Two-phase approval flow**: requests above the user's tier cap are stored as `Proposed` and require a follow-up `respondToLoan` call to accept or decline. * **Witness-derived admin and identity**: caller identity (both admin and per-user) is derived from a 32-byte witness secret. `ownPublicKey()` is not used by the contract. Only the holder of the admin's secret can register providers, blacklist users, or rotate the admin role; only the holder of a user's secret can request, accept, or decline that user's loans. ## Project structure[​](#project-structure "Direct link to Project structure") The repo is a single monorepo with four workspaces — contract, CLI, attestation API, and an optional UI: ``` zkloan-credit-scorer/ ├── contract/ # Compact smart contract │ └── src/ │ ├── zkloan-credit-scorer.compact # Loan logic, eligibility tiers, ledger │ ├── schnorr.compact # In-circuit signature verification │ └── witnesses.ts # Private state (TypeScript) ├── zkloan-credit-scorer-cli/ # Interactive CLI (deploy + transact) │ ├── src/{api,cli,...}.ts │ └── standalone.yml # Local node + indexer + proof server ├── zkloan-credit-scorer-attestation-api/ # REST server signing credit data │ └── src/{signing,server,index}.ts └── zkloan-credit-scorer-ui/ # React + Vite UI (Preprod only) └── src/{components,contexts,...} ``` ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * **Node.js** v22 or newer — the SDK uses Iterator helpers, so Node 20 crashes at first sync * **npm** v10 or newer * **Docker and Docker Compose** — for the local standalone network * **Compact toolchain** — install with the `compact` devtool, then run `compact update` and verify with `compact compile --version` (last validated against `0.31.1`) * **Midnight Lace wallet** — for the Preprod (remote) flow only; see the [installation guide](/getting-started/installation.md) **Versions targeted** — the repo pins ledger v8 and the 4.x Midnight JS SDK: | Component | Version | | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | `@midnight-ntwrk/midnight-js-protocol` (provides the `/ledger`, `/compact-runtime`, `/compact-js` subpaths) | `4.1.1` | | ↳ wrapped ledger (`@midnight-ntwrk/midnight-js-protocol/ledger`) | `8.1.0` | | `@midnight-ntwrk/compact-runtime` | `0.16.0` | | `@midnight-ntwrk/midnight-js-*` | `4.1.1` | | `@midnight-ntwrk/dapp-connector-api` | `4.0.1` | | `@midnight-ntwrk/wallet-sdk` (single barrel — replaces `-facade`/`-hd`/`-shielded`/`-dust-wallet`/`-unshielded-wallet`) | `1.2.0` | | `@midnight-ntwrk/wallet-sdk-address-format` | `3.1.2` | | Compact toolchain (`compact compile`) | `0.31.1` | | Compact language pragma | `>= 0.22 && <= 0.23` | | Proof-server image | `midnightntwrk/proof-server:8.1.0` | | Indexer image | `midnightntwrk/indexer-standalone:4.3.3` | | Node image | `midnightntwrk/midnight-node:1.0.0` | Keep `@midnight-ntwrk/wallet-sdk` pinned exactly — npm's `latest` dist-tag still resolves to `1.1.0`, so a caret range or a fresh `npm install @midnight-ntwrk/wallet-sdk` gives you the older release. ## Set it up[​](#set-it-up "Direct link to Set it up") You'll end up with up to four terminals running at once: docker network, attestation API, CLI, and (optionally) UI. Follow the steps in order — each one produces what the next one needs. ### 1. Install dependencies[​](#1-install-dependencies "Direct link to 1. Install dependencies") ``` git clone https://github.com/midnightntwrk/example-zkloan.git zkloan-credit-scorer cd zkloan-credit-scorer npm install ``` This installs all four workspaces. ### 2. Compile and build the contract[​](#2-compile-and-build-the-contract "Direct link to 2. Compile and build the contract") ``` cd contract npm run compact # generates src/managed/ (JS bindings + prover/verifier keys + ZK IR) npm run build # produces dist/ that the CLI and UI consume cd .. ``` ### 3. Configure the CLI environment[​](#3-configure-the-cli-environment "Direct link to 3. Configure the CLI environment") The CLI's [`level-private-state-provider`](https://www.npmjs.com/package/@midnight-ntwrk/midnight-js-level-private-state-provider) encrypts the contract's private state on disk; it refuses to run without a strong password. ``` cd zkloan-credit-scorer-cli cp .env.example .env # Edit .env and set MIDNIGHT_STORAGE_PASSWORD ``` Password rules (enforced by v4 of the provider): * At least 16 characters * Characters from at least three of: uppercase, lowercase, digits, symbols * No 4-or-more identical characters in a row * No 4-or-more sequential character codes such as `abcd` or `1234` Losing this password means losing access to the encrypted private state — there is no recovery. ### 4. Start the local standalone network[​](#4-start-the-local-standalone-network "Direct link to 4. Start the local standalone network") Skip this step if you only plan to use the Preprod (remote) flow. The CLI workspace ships a `standalone.yml` pinned to the versions above: ``` # Terminal A cd zkloan-credit-scorer-cli docker compose -f standalone.yml up -d ``` Services come up on `ws://127.0.0.1:9944` (node), `http://127.0.0.1:8088` (indexer), `http://127.0.0.1:6300` (proof server). Wait \~15–20s for the node to become healthy: `docker compose -f standalone.yml ps`. On a brand-new chain the indexer can exit once if it connects before the node produces its first block — `standalone.yml` sets `restart: on-failure` so it recovers on its own; give it a restart or two before assuming something is wrong. ### 5. Start the attestation API[​](#5-start-the-attestation-api "Direct link to 5. Start the attestation API") The attestation API signs credit data with a Schnorr signature on Jubjub; the contract verifies the signature inside the ZK circuit. ``` # Terminal B — leave it open cd zkloan-credit-scorer-attestation-api PROVIDER_SECRET_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')" \ PORT=4000 \ npm run dev ``` On startup it prints three values you'll need next: **Provider ID** (default `1`), **public key x**, **public key y**. Save the generated `PROVIDER_SECRET_KEY` somewhere safe — every restart without it generates a new Jubjub key and invalidates any on-chain registration. ### 6. Run the CLI[​](#6-run-the-cli "Direct link to 6. Run the CLI") Two options. Both use the `.env` from step 3. **Option A — Standalone (local docker)** — Requires step 4: ``` # Terminal C cd zkloan-credit-scorer-cli npm run standalone ``` The CLI uses a pre-funded hex seed against the local `undeployed` network, so no faucet or wallet extension is required. **Option B — Preprod (remote)** — Requires a 24-word BIP-39 mnemonic for a Preprod wallet funded from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/), plus a local proof server on port `6300` (already running if you did step 4; otherwise `docker run --rm -p 6300:6300 midnightntwrk/proof-server:8.1.0 midnight-proof-server -v`): ``` # Add WALLET_MNEMONIC="…" to zkloan-credit-scorer-cli/.env first cd zkloan-credit-scorer-cli npm run preprod-remote ``` After the wallet syncs, do these first actions in order — every loan request fails inside `evaluateApplicant` until step 2 is done: 1. **Deploy** (option 1). Save the printed contract address. 2. **Register the attestation provider** (admin menu → option 8). Paste the Provider ID, x, and y from step 5. Then you can request loans, respond to proposals, change PIN, display state, and run the other admin actions. ### 7. Run the UI (Preprod only)[​](#7-run-the-ui-preprod-only "Direct link to 7. Run the UI (Preprod only)") The UI is Preprod-only — Lace cannot balance or sign transactions for the local `undeployed` chain, so use the CLI for any local iteration. ``` # Terminal D cd zkloan-credit-scorer-ui npm run dev # dev server on http://localhost:5173 npm run build # production bundle ``` To connect: 1. Install the Midnight Lace wallet extension and switch it to the Preprod network. 2. Fund the wallet from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/). 3. Make sure steps 5 and 6 (Preprod option) have already run — the attestation API is up, a Preprod contract is deployed, and the provider is registered on it. 4. Open the UI, click **Connect Lace wallet**, then paste the contract address into **01 · Contract** and click **Connect**. Wait for Lace to finish syncing (the extension shows a `Wallet syncing (…%)` banner) before submitting a loan — mid-sync submissions fail with a generic "Transaction submission failed" error. ## Build it from scratch[​](#build-it-from-scratch "Direct link to Build it from scratch") If you want to understand *why* each piece looks the way it does, work through the three-part tutorial that builds this exact DApp from an empty directory. It walks through the witness/disclose split, the Schnorr-in-circuit verification, the PIN-derived identity, and the wallet-and-provider wiring: * [Part 1 — ZK Loan smart contract](/tutorials/zk-loan/smart-contract.md): Compact contract, Schnorr verification module, witness implementation, contract compile + build. * [Part 2 — Attestation API](/tutorials/zk-loan/attestation-api.md): Off-chain Schnorr signer, REST endpoints, proof-server Docker setup. * [Part 3 — CLI and end-to-end testing](/tutorials/zk-loan/cli.md): Wallet derivation, provider wiring, interactive menu, full local-dev walkthrough. The tutorial covers every file in this repository line by line, with commentary explaining the design choices. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Get started Midnight is a blockchain platform for building privacy-preserving DApps. It enables developers to define how data is isolated, verified, and shared through zero-knowledge (ZK) proofs and programmable confidentiality controls. Use this quickstart workflow to set up your local environment and deploy your first application on the Midnight network. You’ll install the toolchain, create and configure a Midnight app, deploy your smart contract and service, and learn how to interact with your deployed components. When you complete this workflow, you’ll have a fully functioning Midnight app running on local Devnet and a clear understanding of how to develop, test, and iterate on privacy-enabled contracts. *** ### [Install the toolchain](/getting-started/installation.md) Install the Lace wallet, Midnight toolchain, and verify your environment configuration. [Start →](/getting-started/installation.md) ### [Create your first DApp](/getting-started/hello-world.md) Create your first Midnight DApp using the Compact language. [Create →](/getting-started/hello-world.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Create your first Midnight contract In this tutorial, you'll write your first Compact smart contract, deploy it to a local test network and write a Hello World message to the blockchain using privacy-preserving logic. By the end of this tutorial, you'll: * Create a Compact smart contract with state storage * Compile the contract into zero-knowledge circuits * Deploy your contract to a local test network * Write a Hello World message to the blockchain ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, ensure you have: * Completed the [install the toolchain](/getting-started/installation.md) guide * Node.js v22+ 1 ## Set up project[​](#set-up-project "Direct link to Set up project") Clone the starter repo: ``` git clone https://github.com/midnightntwrk/example-hello-world.git ``` Install dependencies: ``` yarn install ``` 2 ## Create the contract file[​](#create-the-contract-file "Direct link to Create the contract file") Create a new file named `hello-world.compact` in the `contracts` directory: ``` touch contracts/hello-world.compact ``` Open this file in VS Code: ``` code . ``` 3 ## Create the Compact Smart Contract[​](#create-the-compact-smart-contract "Direct link to Create the Compact Smart Contract") ``` pragma language_version 0.23; export ledger message: Opaque<"string">; export circuit storeMessage(newMessage: Opaque<"string">): [] { message = disclose(newMessage); } ``` * `pragma language_version` specifies which version of Compact your contract uses. * `ledger message` creates a state variable named `message` that stores a string value in the on-chain state. On-chain state is public and persistent on the blockchain. * `circuit storeMessage` is a Compact circuit (function) that defines the logic to modify on-chain state. * `newMessage: Opaque<"string">` is the input parameter. *Circuit parameters are always private by default.* The `disclose()` function marks the private value as safe to store publicly. Without it, trying to assign `newMessage` directly to the ledger returns a compiler error. 4 ## Compile the contract[​](#compile-the-contract "Direct link to Compile the contract") Compiling transforms your Compact code into zero-knowledge circuits, generates cryptographic keys, and creates TypeScript APIs and a JavaScript implementation for the contract to be used by DApps. Run the compiler from the contracts folder: ``` cd contracts compact compile hello-world.compact managed/hello-world ``` You should see the following output: ``` Compiling 1 circuits: circuit "storeMessage" (k=6, rows=26) ``` The compilation process will: 1. Parse and validate your Compact code. 2. Generate zero-knowledge circuits from your logic. 3. Create proving and verifying keys for the circuits. 4. Generate the TypeScript API and JavaScript implementation for the contract. When compilation completes, you'll see a new directory structure: ``` contracts/ ├── managed/ | └── hello-world/ | ├── compiler/ | ├── contract/ | ├── keys/ | └── zkir/ └── hello-world.compact └── index.ts ``` Here's what each directory contains: * **contract/**: The compiled contract artifacts, which includes the JavaScript implementation and type definitions. * **keys/**: Cryptographic proving and verifying keys that enable zero-knowledge proofs. * **zkir/**: Zero-Knowledge Intermediate Representation—the bridge between Compact and the ZK backend. * **compiler/**: Compiler-generated JSON output that other tools can use to understand the contract structure. 5 ## Deploy Contract to Local Devnet[​](#deploy-contract-to-local-devnet "Direct link to Deploy Contract to Local Devnet") Now that your contract is compiled, it needs to be deployed to the blockchain so that you can interact with it. Be sure the Docker engine is running and in a *separate terminal* start the proof server from the project root: ``` yarn env:up ``` Leave the proof server running for the following steps. To deploy the contract, you'll need a wallet. The local devnet package comes with 3 pre-funded wallets. Run the Hello World test script: ``` yarn test:local ``` The test script will begin to show output from your local devnet and will progress the contract deployment and interaction programatically: ``` [12:46:12.694] INFO (22064): Wallet sync complete after 23 emissions [12:46:12.703] INFO (22064): Providers initialized. Ready to test [12:46:12.707] INFO (22064): Creating private state... [12:46:32.347] INFO (22064): Setting the contract address... [12:46:32.347] INFO (22064): Contract deployed at: bba6579743ae23b44301d4a9f8df30dbd5244d63a59d8fbc2c9fc7ea521a04f8 ✓ src/test/hw.test.ts (2 tests) 39112ms ✓ Hello World Contract > Deploys the contract 19649ms ✓ Hello World Contract > Stores Hello World! 18184ms ``` ## Next steps[​](#next-steps "Direct link to Next steps") Explore the [Tutorials](/category/tutorials) for detailed explanations on building Midnight DApps. For less detailed walkthroughs of DApps that provide additional content see [Examples](/category/examples). --- # Install the toolchain > For the complete documentation index, see [llms.txt](/llms.txt) This guide covers the installation of core dependencies for developing decentralized applications (DApps) on Midnight. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin developing DApps on Midnight, ensure you have: * Google Chrome browser * Visual Studio Code * Docker Desktop: Development is supported on Linux and Mac. Windows is not supported natively at this time, if you are using Windows, development through WSL is recommended. ## Install Compact[​](#install-compact "Direct link to Install Compact") [Compact](https://github.com/midnightntwrk/compact) is Midnight's dedicated smart contract language for creating DApps that allows developers to control the level of data protection in their applications. Use the following command to install the pre-built binaries: ``` curl --proto '=https' --tlsv1.2 -LsSf https://github.com/midnightntwrk/compact/releases/latest/download/compact-installer.sh | sh ``` ### Update your shell PATH[​](#update-your-shell-path "Direct link to Update your shell PATH") The installer script automatically adds Compact to your shell's `PATH`. However, you need to restart your terminal or reload your shell configuration for the changes to take effect. To reload your shell configuration without restarting, run the following command: ``` source ~/.zshrc # for zsh # or source ~/.bashrc # for bash ``` **Manual PATH configuration** (only if needed): If Compact is not found after restarting, manually add it to your PATH: ``` export PATH="$HOME/.compact/bin:$PATH" ``` Then reload your shell configuration as shown above. ### Update the compiler version[​](#update-the-compiler-version "Direct link to Update the compiler version") Update to the latest compiler version: ``` compact update 0.31.1 ``` This command downloads the latest version of the Compact compiler and sets it as the default version. ### Verify the Compact installation[​](#verify-the-compact-installation "Direct link to Verify the Compact installation") Run these commands to verify your installation: ``` compact --version # print the version of Compact compact compile --version # print the version of the compiler which compact # print the installation path ``` **Verification**: These commands return the Compact version number, the compiler version number, and the installation path. ## Set up the proof server[​](#set-up-the-proof-server "Direct link to Set up the proof server") The proof server is required to generate zero-knowledge proofs for transactions locally. This section walks you through the process of running the proof server. ### Docker Desktop[​](#docker-desktop "Direct link to Docker Desktop") The proof server runs as a background service using Docker. Ensure the Docker engine is running for the following step. ### Run the proof server[​](#run-the-proof-server "Direct link to Run the proof server") Use the following command to start the proof server in your terminal: ``` docker run -p 6300:6300 midnightntwrk/proof-server:8.1.0 midnight-proof-server -v ``` This command occupies the terminal window while running. **Verification**: The terminal displays logs indicating the server is running and listening at . note To use a local proof-server with the Lace Midnight wallet, go to **Settings » Midnight** and select `Local (http://localhost:6300)`. The local proof server is currently the only option supported within Lace. ## Install the Compact VS Code extension[​](#install-the-compact-vs-code-extension "Direct link to Install the Compact VS Code extension") The Compact VS Code extension provides helpful syntax highlighting and code snippet completion. To install it, follow these steps: 1 Download the [VSIX package](https://raw.githubusercontent.com/midnight-ntwrk/releases/gh-pages/artifacts/vscode-extension/compact-0.2.13/compact-0.2.13.vsix). 2 In VS Code, go to **Extensions**, then **Install from VSIX** and select the extension file. **Verification**: You now see the Compact Language Support extension in your installed VS Code extensions. ## Install Complete[​](#install-complete "Direct link to Install Complete") Your development environment is now configured. You are ready to start building and interacting with privacy-preserving applications on Midnight. In order to deploy and interact with Midnight DApps, both a Midnight Node and Indexer are required. These are provided as RPC endpoints and can be found in the [Latest Stable Release](/relnotes/overview.md#environments). Subsequent Tutorials will demonstrate their use, alternatively, the [Examples](/category/examples) section provides complete DApp demonstrations. ## Troubleshoot[​](#troubleshoot "Direct link to Troubleshoot") This section covers common issues that you might encounter during installation and their solutions. ### Compact binary not found[​](#compact-binary-not-found "Direct link to Compact binary not found") If you see this error: ``` compact: command not found ``` This means the Compact binary is not in your `PATH`. Follow the instructions in [Update your shell PATH](#update-your-shell-path) to add it to your `PATH`. ### Docker Desktop not running[​](#docker-desktop-not-running "Direct link to Docker Desktop not running") If you encounter connection errors when starting the proof server, ensure Docker Desktop is running: 1. Open Docker Desktop application. 2. Wait for the Docker engine to start (the Docker icon in your system tray should be steady, not animated). 3. Try running the proof server command again. ### Port already in use[​](#port-already-in-use "Direct link to Port already in use") If you see an error that port 6300 is already in use: ``` Error: bind: address already in use ``` Either stop the process using port 6300, or run the proof server on a different port: ``` docker run -p 6301:6300 midnightntwrk/proof-server:8.1.0 midnight-proof-server -v ``` Remember to update your application configuration to use the new port. ## Next steps[​](#next-steps "Direct link to Next steps") Now that your development environment is set up, you can: * [Create your first Midnight contract](/getting-started/hello-world.md) * [Explore the Compact language](/compact.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Create a Midnight DApp This guide explains how to scaffold a Midnight DApp using the `create-mn-app` CLI tool. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") The following tools are required to run a Midnight DApp: * Compact compiler installed. See [install the toolchain](/getting-started/installation.md) for instructions. * [Docker Desktop](https://www.docker.com/products/docker-desktop/) installed and running, with Docker Compose v2. * [Node.js](https://nodejs.org/) version 22+ installed. You can use [NVM](https://github.com/nvm-sh/nvm) to install Node.js. ## Midnight CLI tool[​](#midnight-cli-tool "Direct link to Midnight CLI tool") The [`create-mn-app`](https://www.npmjs.com/package/create-mn-app) CLI tool provides starter templates for Midnight DApps. It includes a preconfigured TypeScript setup, hot reloading, and wallet operation logic. To scaffold a new DApp, run the following command: ``` npx create-mn-app [project-name] ``` info Ensure you replace `[project-name]` with the name of your new DApp. The CLI tool first prompts you to choose the type of project you want to create: * Contract * Full DApp If you are new to Midnight development, then starting with *contract* is recommended. It provides a minimal setup that focuses on compiling and deploying a Compact smart contract before working with a full application scaffold. #### Contract[​](#contract "Direct link to Contract") Selecting **Contract** scaffolds a minimal project for deploying a Compact smart contract. You are then prompted to choose a contract template: | Template | Description | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `hello-world` | Default. A message-storage contract bundled with a local devnet for compiling, deploying, and interacting with a Compact contract. | | `battleship` | A private-board state machine, cloned from [example-battleship](https://github.com/midnightntwrk/example-battleship). | Only `hello-world` ships the bundled devnet and the `--network` flag. #### Full DApp[​](#full-dapp "Direct link to Full DApp") Selecting **Full DApp** scaffolds a complete decentralized application with a browser-based or CLI interface for interacting with the contract. You are then prompted to choose a DApp template: | Template | Description | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `bboard` | Default. A privacy-preserving bulletin board, cloned from [example-bboard](https://github.com/midnightntwrk/example-bboard). | | `leaderboard` | A React + Lace browser DApp with in-browser ZK proving, cloned from [midnight-leaderboard](https://github.com/midnightntwrk/midnight-leaderboard). | note `dex` and `midnight-kitties` appear as *coming soon* in the template picker. Full DApp templates follow their upstream repository's README rather than the bundled devnet flow described below. For this guide, select **Contract** at the first prompt and then choose **hello-world** at the template selection prompt. Follow the remaining prompts to complete the setup. ``` Creating a new Midnight app in /path/to/my-app. Template: hello-world ✔ Project structure created ✔ Dependencies installed ✔ Git repository initialized ✔ Docker is ready for proof server ✔ Contract compiled successfully ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🎉 Success! Your Midnight app is ready. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` Once the installation is complete, navigate to the `my-app` directory: ``` cd my-app ``` Your project structure should look similar to this: ``` my-app/ ├── contracts/ │ └── hello-world.compact # Compact smart contract ├── src/ │ ├── cli.ts # Interact with deployed contract │ ├── deploy.ts # Deploy contract │ └── check-balance.ts # Check wallet balance ├── docker-compose.yml # Local devnet: node, indexer, proof server ├── package.json └── .midnight-state.json # Deployment state (gitignored; contract address and network) ``` The `contracts/hello-world.compact` file contains the Compact smart contract code. ``` pragma language_version >= 0.23; import CompactStandardLibrary; export ledger message: Opaque<"string">; export circuit storeMessage(customMessage: Opaque<"string">): [] { message = disclose(customMessage); } ``` [Compact](/compact.md) is Midnight's smart contract language used to define contract logic. It is similar to TypeScript but is designed for use with the Midnight runtime. The `docker-compose.yml` file defines a local devnet, a Midnight node, indexer, and [proof server](/guides/run-proof-server.md) that runs in Docker. The proof server generates Zero Knowledge (ZK) proofs for smart contracts on the Midnight network. The devnet must be running before you can deploy or interact with the contract. ## Set up the project[​](#set-up-the-project "Direct link to Set up the project") Run the setup script: ``` npm run setup ``` `npm run setup` boots a local devnet in Docker (node, indexer, and proof server), compiles the contract, and deploys it. You don't need a wallet extension or a faucet — the local `dev` preset pre-mints NIGHT to a genesis seed, which funds the deployment automatically. The CLI writes deployment state to `.midnight-state.json` (Git ignores this file), which holds the contract address and the active network. The CLI references this file when interacting with the contract. ## Interact with the contract[​](#interact-with-the-contract "Direct link to Interact with the contract") After you deploy the contract, start the interactive CLI: ``` npm run cli ``` The CLI lets you interact with the deployed contract: ``` 1. Store a message 2. Read current message 3. Check wallet balance 4. Exit ``` Choose an option from the menu and follow the prompts. To read the ledger state directly, run the end-to-end test: ``` npm run test:e2e ``` ### Deploy to a public testnet[​](#deploy-to-a-public-testnet "Direct link to Deploy to a public testnet") The local devnet is the default. Public testnets are opt-in, pass `--network` to `npm run setup`: ``` npm run setup -- --network preview ``` The first time you target a public network, the CLI generates a wallet and prints a faucet URL to fund it. Open the [preview faucet](https://midnight-tmnight-preview.nethermind.dev/) or [preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/) to fund the wallet. The network selection is sticky; switch networks later with `npm run network `. | Network | Source | When to use | | ------------ | --------------------------------------------------------------------------- | ------------------------------------------------- | | `undeployed` | Local devnet (`docker-compose.yml`) | Default. No funding or wallet extension required. | | `preview` | Public preview ([faucet](https://midnight-tmnight-preview.nethermind.dev/)) | Shared infrastructure before a release. | | `preprod` | Public preprod ([faucet](https://midnight-tmnight-preprod.nethermind.dev/)) | Closest to mainnet. | ## Templates[​](#templates "Direct link to Templates") The Midnight CLI tool provides starter templates for both contracts and full DApps. Pass a template with `--template `, or omit it and the CLI prompts you to choose. ### Hello world[​](#hello-world "Direct link to Hello world") The `hello-world` template is a message storage contract that allows you to post and retrieve messages on the blockchain. It ships with the bundled local devnet. ``` npx create-mn-app my-app ``` `hello-world` is the default and comes with dependencies installed. You don't need the `--template` flag to create a new `hello-world` project. ### Battleship[​](#battleship "Direct link to Battleship") The `battleship` template is a private-board state machine, cloned from [example-battleship](https://github.com/midnightntwrk/example-battleship). ``` npx create-mn-app my-app --template battleship ``` ### Bulletin board[​](#bulletin-board "Direct link to Bulletin board") The `bboard` template is a privacy-preserving bulletin board DApp that allows you to post and remove messages, cloned from [example-bboard](https://github.com/midnightntwrk/example-bboard). ``` npx create-mn-app my-app --template bboard ``` This template uses ZK proofs to verify the identity of the poster and the owner of the message without revealing their identity on-chain. To learn more about the Bulletin board DApp, see the [Bulletin board DApp](/examples/dapps/bboard.md) example. ### Leaderboard[​](#leaderboard "Direct link to Leaderboard") The `leaderboard` template is a React + Lace browser DApp with in-browser ZK proving, cloned from [midnight-leaderboard](https://github.com/midnightntwrk/midnight-leaderboard). ``` npx create-mn-app my-app --template leaderboard ``` note `create-mn-app` v0.4.2 removed the Counter template. You can still scaffold the retired Counter example with the `--from` flag: ``` npx create-mn-app@latest my-app --from midnightntwrk/example-counter ``` ## CLI options[​](#cli-options "Direct link to CLI options") The following options are available when creating a new DApp using the `create-mn-app` CLI tool: | Option | Description | | ------------------------- | ----------------------------------------------------------------------------------- | | `-t`, `--template ` | Select a template: `hello-world`, `battleship`, `bboard`, `leaderboard` | | `--list` | List the available templates | | `--from ` | Scaffold from a GitHub repository | | `--network ` | Set the network for the `hello-world` template (`undeployed`, `preview`, `preprod`) | | `-y` | Accept defaults without prompting | | `--dry-run` | Show what the CLI would create without writing files | | `--use-npm/yarn/pnpm/bun` | Force the use of a specific package manager | | `--skip-install` | Skip the installation of dependencies | | `--skip-git` | Skip the initialization of a git repository | | `--verbose` | Show detailed output when creating the project | | `-h`, `--help` | Show help | | `-V`, `--version` | Show the version of the CLI tool | ## Next steps[​](#next-steps "Direct link to Next steps") Now you know how to scaffold a new DApp using the Midnight CLI tool. Check out the [hello world tutorial](/getting-started/hello-world.md) to learn how to write your first Midnight contract using the Compact language. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Network Glossary ### Block[​](#block "Direct link to Block") A block is a collection of validated transactions grouped together and added to the blockchain in sequence. Each block contains a reference to the previous block, forming a chain. In Midnight, blocks are produced by active nodes and finalized through the network's finalization mechanism. ### Block producer[​](#block-producer "Direct link to Block producer") A participant in the Midnight network whose role is to propose and add new blocks to the blockchain. Block producers are selected based on the consensus mechanism and are rewarded in coins for their participation. They are responsible for ordering transactions and ensuring the integrity of each block they produce. ### Blinding factor[​](#blinding-factor "Direct link to Blinding factor") A random value used in cryptographic commitment schemes, such as Pedersen commitments, to hide the underlying data being committed to. The blinding factor ensures that two commitments to the same value produce different outputs, preventing observers from inferring the committed value by comparison. Without knowledge of the blinding factor, the committed value cannot be recovered. ### Bech32m[​](#bech32m "Direct link to Bech32m") An address encoding format used in blockchain networks for wallet addresses. It's an improved version of the original Bech32 format that provides better error detection when typing or copying addresses. ### Coin[​](#coin "Direct link to Coin") A coin is a digital asset that exists on a blockchain. It is a unit of account used as a store of value. Block producers are rewarded in coins, and coins are used to pay transaction fees. A coin is distinct from a token, which is any digital asset that means something to a decentralized application, including representing a real-world asset. That means all coins are tokens, but not all tokens are coins. ### Compact[​](#compact "Direct link to Compact") Compact is the domain-specific language, based on TypeScript, in which Midnight's smart contracts are expressed. While the language does allow contracts to be expressed concisely, the primary derivation of the name is from the noun form of the word *compact*, meaning an agreement, contract, or covenant among people or institutions. ### Concurrency[​](#concurrency "Direct link to Concurrency") Concurrency is the ability of many users to perform tasks simultaneously without blocking each other. This ensures increased throughput and makes transaction and smart contract processing more efficient. ### Commitment[​](#commitment "Direct link to Commitment") A cryptographic primitive that allows a party to commit to a chosen value while keeping it hidden. The commitment binds the value so it cannot change and hides the value from others. To verify the committed data, the user presents the original value and randomness, and the system checks that it matches the commitment. Midnight uses commitments to represent private state on the public ledger without exposing the underlying data. ### Contract address[​](#contract-address "Direct link to Contract address") A unique identifier assigned to a smart contract when it is deployed to the Midnight network. The contract address is used by DApps and wallets to locate and interact with a specific deployed contract. It is derived from the contract's deployment transaction and remains fixed for the lifetime of the contract on-chain. ### Contract deployment[​](#contract-deployment "Direct link to Contract deployment") The process of publishing a compiled Compact smart contract to the Midnight network, making it available for interaction. During deployment, the contract's initial ledger state is established and a contract address is assigned. Deployment requires a transaction to be submitted and confirmed on-chain and typically involves paying a fee in DUST. ### Consensus mechanism[​](#consensus-mechanism "Direct link to Consensus mechanism") The consensus mechanism of a blockchain is the set of rules that govern the way that the participants in the network agree to add blocks to the chain. Each block must conform to the chain’s rules, and the blocks must be chained in the correct sequence, avoiding or resolving forks in the chain. ### Cryptocurrency[​](#cryptocurrency "Direct link to Cryptocurrency") A digital asset stored on a blockchain ledger that is intended to be used as a medium of exchange for goods or services. Blockchain protocols use cryptography to ensure the security and verification of ownership and fund movements. Unlike traditional currencies, a cryptocurrency is not controlled by a government. Its value is determined by the dynamics of market supply and demand. ### Custom spend logic[​](#custom-spend-logic "Direct link to Custom spend logic") A term used to indicate a potential feature of Midnight, where spending a coin involves executing attached logic so that certain invariants of token lifecycle can be enforced. An example use case may be requiring a known/ allowed source of tokens. ### Custom token[​](#custom-token "Direct link to Custom token") Custom tokens are user-defined tokens designed to fulfill specific features and functionalities, like voting and governance. Custom tokens in Midnight are managed by the ledger alongside Midnight’s native tokens using the same mechanics. ### DApp[​](#dapp "Direct link to DApp") A DApp, short for decentralized application, is a computer program that operates on a network without a single central server, typically a blockchain. ### DApp developer[​](#dapp-developer "Direct link to DApp developer") An individual or organization that creates and maintains DApps. ### DApp operator[​](#dapp-operator "Direct link to DApp operator") An individual or organization responsible for the management, operation, and support of a decentralized application. DApp operators often engage DApp developers, or are themselves DApp developers. ### DApp connector[​](#dapp-connector "Direct link to DApp connector") A software interface that allows a DApp running in a browser or application to communicate with a user's Web3 wallet. The DApp connector handles permission requests, transaction signing, and proof submissions on behalf of the user, without exposing the user's private keys to the DApp. In Midnight, the DApp connector also coordinates with the proof server to generate ZK proofs before a transaction is submitted. ### Decentralized[​](#decentralized "Direct link to Decentralized") A system or organization where there is no single authority in control. Instead, the system or organization is run by numerous decision makers with equal or comparable standing. ### Devnet[​](#devnet "Direct link to Devnet") Short for ‘development network’, a devnet is a blockchain that behaves like the Mainnet and is used for testing DApps that are in development. It uses test tokens with no value. Some governance parameters may be set differently from Mainnet for the convenience of developers. In Midnight, the process of DApp deployment proceeds from a devnet to one or more testnets, such as Preview and Preprod, before the DApp is released on the Mainnet. Midnight's `devnet` has been deprecated in favor of the current `testnet`. ### Distributed[​](#distributed "Direct link to Distributed") A blockchain is distributed because a copy of it is stored on many computers across the world. ### Domain separator[​](#domain-separator "Direct link to Domain separator") A field used when a DApp asks a user to sign a message. It helps ensure that a message from one DApp cannot be used in a different DApp or on a different network. ### DUST[​](#dust "Direct link to DUST") A shielded, non-transferable, consumable network resource used exclusively to pay transaction fees on Midnight. ### Faucet[​](#faucet "Direct link to Faucet") A web service that distributes free test tokens to developers building on a testnet. On Midnight, the faucet provides tNIGHT, which generates tDUST for paying transaction fees during development. Faucet tokens have no real-world value and exist only for testing purposes. ### Federated Node Operators (FNO)[​](#federated-node-operators-fno "Direct link to Federated Node Operators (FNO)") A network of independent node operators that work together to maintain and secure the Midnight blockchain. These operators validate transactions, produce blocks, and ensure the network remains decentralized and reliable. Unlike a single centralized authority, FNOs distribute control across multiple trusted entities, enhancing security and reducing single points of failure. ### Fungible token[​](#fungible-token "Direct link to Fungible token") Fungible tokens are identical to one another, have the same value, and are interchangeable. ### Gadget[​](#gadget "Direct link to Gadget") A gadget is a specialized entry point, specific to zero-knowledge cryptography, designed to bring ZK Snark circuit development within reach of a wide range of developers. Midnight cryptography (Midnight's cryptographic backend library) provides several gadgets, including a signing gadget, an encryption gadget, and a hashing gadget. ### Halo 2[​](#halo-2 "Direct link to Halo 2") A high-performance ZK Snark implementation from the Electric Coin company. ### Hard-fork[​](#hard-fork "Direct link to Hard-fork") An event of changing the way transactions are being processed in a backwards-incompatible way (e.g. when introducing new features). It requires all nodes in the network to upgrade software to continue participation in the network. ### Hash[​](#hash "Direct link to Hash") In cryptography, a hash value, or hash for short, is the output of a mathematical operation called a hash function. A hash function takes a string of any length and produces a string of fixed length such that it is infeasible to derive the input value, there is a very low probability of two strings producing the same hash function, and even a small change to the input will always result in a different output. ### HD wallet[​](#hd-wallet "Direct link to HD wallet") Short for Hierarchical Deterministic wallet. A type of cryptocurrency wallet that can generate multiple addresses and private keys from a single master seed phrase, usually 12 or 24 words. This means you only need to back up one seed phrase to recover all your addresses and funds. Midnight uses HD wallets for deriving and managing the three different types of addresses used in the network: Unshielded, Shielded, and DUST. ### HRP[​](#hrp "Direct link to HRP") The human-readable part (HRP) is the text prefix in a Bech32 or Bech32m encoded address. It identifies the address type and the network the address belongs to. In Midnight, HRP prefixes distinguish between address types: `mn_addr` for unshielded addresses, `mn_shield-esk` for shielded encryption key addresses, and `mn_dust` for DUST addresses. On Testnet environments, the prefix includes the network ID, for example `mn_addr_{network_id}`. ### Kachina[​](#kachina "Direct link to Kachina") Kachina is a unified security model for data-protecting smart contracts that bridge the gap between a private state on the user’s local machine and a public state on the blockchain. It is based on the universally composable (UC) model. By relying on ZK Snarks, Kachina establishes a smart contract protocol that ensures data protection while operating within the UC security framework. ### Ledger[​](#ledger "Direct link to Ledger") The public record of contract state and token state on the blockchain. The ledger does not exist as a single document on the blockchain at any point. Instead, the current ledger, as of some block, can be synthesized by reading the blockchain up to that block. In Compact, the `ledger` declaration specifies the contract's contributions to the global ledger. ### Light client[​](#light-client "Direct link to Light client") A blockchain light client interacts with full nodes to find information about the blockchain, but only stores part of the ledger itself. By verifying headers and using Merkle proofs, light clients can ensure that the data they receive from full nodes is valid and accurate. Light clients require less processing power and storage capacity compared to full nodes, making them more suitable for devices with limited resources such as smartphones or IoT devices. ### Mainnet[​](#mainnet "Direct link to Mainnet") The fully developed and deployed blockchain where transactions are verified and recorded. ### Merkle tree[​](#merkle-tree "Direct link to Merkle tree") A data structure used in cryptography and computer science to verify the integrity and consistency of large data sets. Named after its inventor Ralph Merkle, a Merkle tree is a binary tree where each leaf node represents a hash value of a specific data block. ### Multi-asset[​](#multi-asset "Direct link to Multi-asset") Multi-asset refers to the capability of a blockchain platform or protocol to support and handle various types of digital assets or tokens simultaneously. ### NATS[​](#nats "Direct link to NATS") NATS is a lightweight, high-performance, open-source messaging system used for event-driven communication between services. In Midnight's indexer architecture, NATS serves as the internal message broker that enables different indexer components, such as the chain indexer and wallet indexer, to exchange events and data asynchronously. ### NIGHT[​](#night "Direct link to NIGHT") Midnight’s native utility token, transferable and persistent, used for governance, incentives, and as the source of DUST generation. ### Non-fungible token (NFT)[​](#non-fungible-token-nft "Direct link to Non-fungible token (NFT)") Non-fungible tokens are unique and indivisible tokens recorded on a blockchain. They can represent ownership rights to tangible assets like real estate or artwork, or to intangible assets such as a rare magical sword in a Web3 game. ### Nonce[​](#nonce "Direct link to Nonce") A unique number that is used only once in cryptographic communications. In blockchain transactions, a nonce prevents replay attacks by ensuring each transaction is unique and can't be duplicated or reused maliciously. Think of it as a one-time serial number that protects your transactions from being copied and submitted again. ### Node[​](#node "Direct link to Node") A blockchain node is a computer or device that participates in a blockchain network. It plays a crucial role in maintaining the decentralized and distributed nature of blockchain technology. There are several types of nodes, and one node can be more than one type. * An active node is one whose purpose is to mint blocks for the blockchain. * A full node stores a copy of the entire blockchain, that is, all the transactions and data records ever executed within the network. * A passive node is one that is receiving blocks and transactions from its peers (and in the future, will share these with its peers). ### Nullifier[​](#nullifier "Direct link to Nullifier") A unique value derived from a coin or private state element that is revealed on-chain when that element is consumed. Nullifiers allow the network to detect and reject double-spend attempts without revealing which specific coin or private value was spent. Once a nullifier appears on the ledger, the corresponding element can never be used again. ### Oracle[​](#oracle "Direct link to Oracle") An oracle is a service or mechanism that provides external data to smart contracts. It means smart contracts can interact with external information sources by using data from oracles to automate actions. ### Pedersen commitments[​](#pedersen-commitments "Direct link to Pedersen commitments") A cryptographic technique introduced by Torben Pedersen in a 1992 conference paper that enables the commitment to a value without revealing the value itself. It involves combining the value with a random blinding factor using mathematical operations to create a commitment. The committed value remains hidden and computationally difficult to reverse-engineer without knowing the blinding factor. Pedersen commitments are homomorphically additive, allowing one to ‘add’ commitments to two values to get a commitment to the sum of the original values. This can be further stretched to sums of arbitrary-dimension vectors by committing each dimension with a different base. ### Private oracle[​](#private-oracle "Direct link to Private oracle") The set of witness functions and the private state over which they operate constitute the private oracle for a contract. ### Private state[​](#private-state "Direct link to Private state") The portion of a smart contract's state that is stored locally on a user's device and is never published to the blockchain. Private state is only accessible to the user who owns it and is used as input to witness functions when generating zero-knowledge proofs. It contrasts with ledger state, which is public and visible to all participants on the network. ### Proof server[​](#proof-server "Direct link to Proof server") A local service that generates zero-knowledge proofs on behalf of a user's DApp. When a user initiates a transaction that involves private data, the DApp sends the relevant inputs to the proof server, which computes the ZK proof and returns it for inclusion in the transaction. The proof server runs on the user's own machine and requires a set of proving keys that are downloaded during initial setup. It does not have access to the user's private keys. ### Proving key[​](#proving-key "Direct link to Proving key") A large piece of cryptographic data generated during the setup phase of a ZK Snark scheme. The proving key is used by the proof server to construct valid zero-knowledge proofs for a specific circuit. Each Compact contract function that involves private state has a corresponding proving key. Proving keys are typically distributed alongside compiled contracts and must be present on the user's machine before proofs can be generated. ### Public state[​](#public-state "Direct link to Public state") The portion of a smart contract's state that is stored on the blockchain and is visible to all participants in the network. In Compact, public state is declared using the `ledger` keyword and forms the contract's contribution to the global ledger. Public state can be updated by submitting a valid transaction and is used to coordinate interactions between users without revealing private data. ### Prover[​](#prover "Direct link to Prover") An entity or party that aims to convince another party, known as the verifier, about the validity or truthfulness of a statement without revealing any sensitive or confidential information. The prover's role is to construct a proof that demonstrates knowledge of certain data or the ability to perform a specific computation, while maintaining confidentiality. ### Midnight Indexer[​](#midnight-indexer "Direct link to Midnight Indexer") It is a component that follows the Midnight chain to index events and data in a queryable database. Light clients can subscribe to this service to receive any relevant data such as token transactions associated with a given set of wallet addresses, or transactions related to a given smart contract. ### Qualified coin[​](#qualified-coin "Direct link to Qualified coin") A coin registered in the ledger's commitment Merkle tree with a known index and so qualified to be spent in a transaction. ### Runtime upgrade[​](#runtime-upgrade "Direct link to Runtime upgrade") An approach to evolve Substrate-based networks through storing code to process transactions on-chain (which is called runtime) and allowing to update that code with dedicated types of transactions. In some cases this approach allows to avoid executing hard-forks in a network. ### Self-sovereign identity (SSI)[​](#self-sovereign-identity-ssi "Direct link to Self-sovereign identity (SSI)") Self-sovereign identity is a lifetime portable identity for a person, organization or thing. It does not depend on any centralized authority and cannot be taken away. Individuals have the right to decide what personal information they share and with whom. They can selectively disclose only the necessary information for a specific transaction or interaction. ### Selective disclosure[​](#selective-disclosure "Direct link to Selective disclosure") A privacy mechanism that allows a user to reveal only a specific subset of their personal data or attributes to a verifier, without exposing any unrelated information. In Midnight, selective disclosure is implemented using zero-knowledge proofs, enabling users to prove the validity of a claim, such as being above a certain age, without revealing the underlying data, such as their exact date of birth. Selective disclosure is a core building block of self-sovereign identity on Midnight. ### Shielded[​](#shielded "Direct link to Shielded") Shielded tokens allow for interactions to occur without metadata leakage. Wallet addresses and transaction details are not disclosed to counterparties or made available on a public ledger. ### Smart contract[​](#smart-contract "Direct link to Smart contract") A program encoded on a blockchain that executes predefined actions when specific conditions are met. Smart contracts eliminate the need for intermediaries by enforcing the terms of the contract through computer code. Smart contracts enable transparent, secure, and tamper-resistant transactions because they are executed on a decentralized network with no single point of failure. ### Snark[​](#snark "Direct link to Snark") See ZK-Snark. ### Soft-fork[​](#soft-fork "Direct link to Soft-fork") An event of changing the way transactions are being processed in a backwards-compatible way (e.g. when adjusting some parameters). It requires active nodes in the network to upgrade software to continue participation in the network, but full and passive nodes do not require to be updated. ### SPECK[​](#speck "Direct link to SPECK") The atomic unit of DUST: 1 DUST = 1015 SPECK. ### STAR[​](#star "Direct link to STAR") The atomic unit of NIGHT: 1 NIGHT = 106 STAR. ### State[​](#state "Direct link to State") State refers to the current data or information stored within a smart contract. It represents the values of variables, storage locations, and any other relevant information that is necessary for the contract’s execution and functioning. ### Swap[​](#swap "Direct link to Swap") The exchange or trading of one cryptocurrency or token for another directly on the blockchain, without the need for an intermediary. These swaps are often facilitated through specialized smart contracts or decentralized exchanges (DEXs). ### Testnet[​](#testnet "Direct link to Testnet") A testnet is an intermediate step between a devnet and the mainnet. Like a devnet, it is a blockchain with all the characteristics of the mainnet except that it uses test tokens with no real-world value. Some governance parameters may be set differently from the main chain for the convenience of developers. The process of DApp deployment normally proceeds from a devnet to one or more testnets, such as Preview and Preprod, before the DApp is released on the mainnet. Testnet parameters may be set closer to their production values than on a devnet. ### tDUST[​](#tdust "Direct link to tDUST") Test DUST tokens used on Midnight testnets like Preprod. The 't' prefix stands for 'test', indicating these tokens have no real-world value and are only for development and testing purposes. Like regular DUST, tDUST is used to pay transaction fees and is generated from tNIGHT holdings. ### tNIGHT[​](#tnight "Direct link to tNIGHT") Test NIGHT tokens used on Midnight testnets like Preprod. The 't' prefix stands for 'test', indicating these tokens have no real-world value and are only for development and testing purposes. tNIGHT can be freely obtained from a faucet and used to test DApp functionality that involves NIGHT tokens, including generating tDUST for transaction fees. ### Token[​](#token "Direct link to Token") A token is any digital asset that means something to a decentralized application, including acting as a store of value or representing a real-world asset. ### Transaction[​](#transaction "Direct link to Transaction") The transfer or exchange of digital assets or information on a blockchain network. A transaction involves records such as the sender, recipient, and the amount or type of assets being transferred, into a block within the blockchain. Transactions are verified, validated, and added to the blockchain through a consensus mechanism, ensuring their integrity and immutability. ### Transaction balancing[​](#transaction-balancing "Direct link to Transaction balancing") If a wallet receives a transaction that is not balanced (that is - for a token type transaction the value of inputs does not equal the value of outputs), the wallet **balances** the transaction by providing necessary inputs and outputs so that it can be accepted by the ledger. ### TypeScript[​](#typescript "Direct link to TypeScript") A programming language developed by Microsoft that adds features to JavaScript. It allows developers to catch errors during development and improves code quality. TypeScript code is turned into JavaScript for execution and is commonly used for web development, providing better tooling support and productivity, particularly for larger code bases and teams. ### Unshielded[​](#unshielded "Direct link to Unshielded") Referring to tokens or transactions where metadata such as wallet addresses and transfer amounts are visible on the public ledger. Unshielded interactions do not benefit from the privacy protections provided by ZK proofs and are equivalent to standard transparent blockchain transactions. In Midnight, unshielded and shielded assets can coexist and interact within the same application. ### Universally Composable (UC) security framework[​](#universally-composable-uc-security-framework "Direct link to Universally Composable (UC) security framework") A theoretical framework described by Ran Canetti in a 2020 paper. It is used to analyze and prove the security of cryptographic protocols in a composable manner. In the UC framework, protocols are treated as building blocks that can be composed together to form more complex protocols. The framework allows for the analysis of the security properties of a protocol when it is used as a component in a larger system. ### Verifier[​](#verifier "Direct link to Verifier") An entity or party that aims to verify the validity or truthfulness of a statement presented by another party, known as the prover, without requiring full knowledge of the underlying data or computation. The verifier's role is to examine the proof provided by the prover and determine its correctness based on the agreed-upon rules and cryptographic protocols. ### Verification key[​](#verification-key "Direct link to Verification key") A compact cryptographic artifact derived from the same setup process as the proving key. The verification key is used by the network or a verifier to confirm that a submitted ZK proof is valid for a given circuit, without re-executing the computation or learning anything about the private inputs. Verification keys are small and fast to evaluate, making on-chain verification efficient. ### Wallet[​](#wallet "Direct link to Wallet") A digital tool or software that allows users to view, send, and receive digital assets securely. These wallets store private keys and public addresses, enabling users to manage their digital assets on a blockchain network. ### Web3[​](#web3 "Direct link to Web3") Web3 is a decentralized version of the WorldWide Web built on blockchain technology and cryptographic principles. It provides a trustless, and more user-centric online experience. It aims to transform the way information, value, and digital assets are shared, accessed, and interacted with. ### Web3 wallet[​](#web3-wallet "Direct link to Web3 wallet") A Web3 wallet extends a digital asset wallet by enabling connection to DApps, and allowing the management of assets other than cryptocurrency, such as NFTs. ### Witness[​](#witness "Direct link to Witness") In mathematical logic, a witness is a value that satisfies an assertion. For example, a witness for 'there exists an integer greater than 0' is the number 5. For the zero-knowledge proofs in Midnight, a witness is a function that satisfies a different kind of assertion: there exists a **function** with a specified type signature. The circuits defined in Compact can call such witness functions, but the definitions of the witnesses are outside Compact, and their effects on private state are not recorded in the public ledger. ### Zero-knowledge proof (ZKP)[​](#zero-knowledge-proof-zkp "Direct link to Zero-knowledge proof (ZKP)") A zero-knowledge proof allows someone to prove they know a secret without revealing the secret. For example, a ZKP can prove that an attribute has a value within a range without revealing its exact value. A potential client of a DApp or service can use ZKP to selectively disclose information from their self-sovereign identity without disclosing other information. ### Zero-knowledge (ZK) circuit[​](#zero-knowledge-zk-circuit "Direct link to Zero-knowledge (ZK) circuit") Arithmetic circuits are short programs, consisting of a fixed number of multiplications and additions in a modular prime field. A zero-knowledge circuit is a special case that demonstrates the existence of a solution to an arithmetic circuit without revealing the input values or intermediate steps. ### ZKIR[​](#zkir "Direct link to ZKIR") Zero-Knowledge Intermediate Representation. A low-level format that Compact smart contracts are compiled into before being converted to zero-knowledge circuits. ZKIR makes it possible to translate readable contract logic into the mathematical format needed for zero-knowledge cryptography. ### ZK Snarks[​](#zk-snarks "Direct link to ZK Snarks") A zero-knowledge succinct non-interactive argument of knowledge (ZK Snark) is a specific type of zero-knowledge proof. They are particularly efficient and powerful for two reasons. First, ZK Snarks are succinct, meaning that the proof size remains constant, regardless of the complexity or size of the statement being proved. This property is highly desirable because it provides efficient verification and reduces the amount of data that needs to be transmitted. Second, ZK Snarks are non-interactive, meaning that the prover can generate a proof without requiring any additional interaction with the verifier. This makes them more efficient than other types of ZK proofs, which typically involve multiple rounds of communication. ### Zswap[​](#zswap "Direct link to Zswap") Midnight uses Zswap – a transaction scheme that combines the strengths of Zcash and SwapCT – to create a straightforward transaction protocol based on ZK Snarks. Zswap enables the merging of transactions while preserving the confidentiality of data. It addresses the limitations of privacy-oriented cryptocurrencies by providing a mechanism for supporting multiple asset types and facilitating atomic swaps, thereby offering a scalable and secure solution for DeFi applications. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Funding a wallet Every transaction on Midnight consumes DUST, and DUST comes from NIGHT that you have registered for DUST generation. On the test networks both halves are free: a faucet sends you tNIGHT, and registering it starts tDUST accruing. This guide walks the whole path. You request tNIGHT from the faucet, register it in the Lace wallet, and then do the same programmatically with the wallet SDK when you need funding to be scriptable. For why the two-token model works this way, see [Funding and transaction cost](/guides/networks-and-environments.md#funding-and-transaction-cost). One term matters throughout. You **register** NIGHT for DUST generation, the on-chain operation the protocol and SDK also call registration. Lace labels the button **Generate tDUST** and displays the result as your tNIGHT designation. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * A [Lace wallet](/getting-started/installation.md) set up on the target test network, for the faucet and Lace procedures. * Node.js version 22 or higher, for the wallet SDK procedure. macOS, Linux, and Windows through WSL all work. * A local [proof server](/guides/run-proof-server.md) on port 6300, for the wallet SDK procedure. * [Vitest](https://vitest.dev/) alongside the packages listed below, if you want to run the verification tests. ## Getting tNIGHT from the faucet[​](#getting-tnight-from-the-faucet "Direct link to Getting tNIGHT from the faucet") Request free test tokens for the network you develop on. The faucets are rate limited, and test tokens carry no real value. On the local `undeployed` network there is no faucet and none is needed; use the [local network funding menu](/guides/networks-and-environments.md#running-a-local-network) instead. ### Procedure[​](#procedure "Direct link to Procedure") 1. Copy your **unshielded** wallet address. In Lace, open your Midnight wallet and copy the address that starts with `mn_addr_`; the faucet rejects shielded and DUST addresses. Bech32m address format Lace shows wallet addresses in Bech32m format by default. The address encodes its network, for example `mn_addr_preprod1...` on Preprod. 2. Open the faucet for your network: the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/) or the [Preview faucet](https://midnight-tmnight-preview.nethermind.dev/). The [Environment reference](/guides/networks-and-environments.md#environment-reference) lists both. ![Midnight preprod faucet](/assets/images/request-tokens-aa0c9462e1c87550aa3766ef7a695a60.png) 3. Paste the address, complete the captcha, and select **Request tokens**. The faucet confirms the submission: ``` Transaction submitted. You will shortly receive 1000 tNight in your wallet. This is the transaction ID: 00f15defb8d3... ``` ### Verification[​](#verification "Direct link to Verification") The tNIGHT balance appears in your wallet within a couple of minutes: 1,000.0 tNIGHT per Preprod faucet request. In Lace, the unshielded balance updates on the wallet's main view. In code, the balance watcher in [Registering NIGHT for DUST generation with the wallet SDK](#registering-night-for-dust-generation-with-the-wallet-sdk) resolves as soon as the funds land. ## Registering NIGHT for DUST generation in Lace[​](#registering-night-for-dust-generation-in-lace "Direct link to Registering NIGHT for DUST generation in Lace") Turn your tNIGHT into a source of tDUST. Holding NIGHT alone generates nothing; the registration transaction is what starts generation. ### Prerequisites[​](#prerequisites-1 "Direct link to Prerequisites") * tNIGHT in your wallet, from [Getting tNIGHT from the faucet](#getting-tnight-from-the-faucet). ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. In Lace, open your Midnight wallet and select **Generate tDUST**. ![The Lace wallet tokens view with the Generate tDUST button](/assets/images/delegate-dust-cfbb546850772c93f4842fec07a43aee.png) 2. Your tDUST address populates the input field. Select **Review transaction**, then **Confirm** to submit the registration. ![The Generate tDUST dialog with the address filled in and the Review transaction button](/assets/images/review-transaction-143f8b80120309ee4fd00d69cf107768.png) ### Verification[​](#verification-1 "Direct link to Verification") The tDUST tank starts filling and continues to accrue over time, up to a cap set by how much NIGHT you registered. ![The Lace tDUST tank generating tokens after registration](/assets/images/dust-tank-generation-bb9bbdc163af9bf787d5621e6588d112.png) ## Setting up the wallet SDK project[​](#setting-up-the-wallet-sdk-project "Direct link to Setting up the wallet SDK project") Prepare a TypeScript project that can talk to a Midnight network, so the wallet code in the next two procedures has somewhere to run. The three procedures that follow build up a single script, one part at a time. The wallet SDK ships as the single barrel package `@midnightntwrk/wallet-sdk`, which re-exports every wallet sub-package. That scope has no hyphen, unlike the `@midnight-ntwrk/` packages alongside it. ### Procedure[​](#procedure-2 "Direct link to Procedure") 1. Create a project and install the version-matched dependencies. Check the [support matrix](/relnotes/support-matrix.md) when versions change: package.json ``` { "type": "module", "scripts": { "start": "tsx src/index.ts" }, "dependencies": { "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-utils": "4.1.1", "@midnightntwrk/wallet-sdk": "1.2.0", "rxjs": "^7.8.1", "ws": "^8.19.0" }, "devDependencies": { "@types/ws": "^8.18.1", "tsx": "^4.19.0" } } ``` Then run `npm install`. 2. Start your local [proof server](/guides/run-proof-server.md) and confirm it answers on port 6300: ``` curl http://localhost:6300/health ``` 3. Create `src/index.ts` and add the imports and configuration. The script assigns the `ws` package as the global WebSocket before any wallet code runs, which keeps WebSocket behavior consistent across Node versions. The endpoints come from the [Environment reference](/guides/networks-and-environments.md#environment-reference): ``` import { WebSocket } from 'ws'; (globalThis as any).WebSocket = WebSocket; import { Buffer } from 'buffer'; import * as Rx from 'rxjs'; import { HDWallet, Roles, generateRandomSeed, WalletFacade, ShieldedWallet, DustWallet, UnshieldedWallet, createKeystore, PublicKey, NoOpTransactionHistoryStorage, DustAddress, MidnightBech32m, } from '@midnightntwrk/wallet-sdk'; import { toHex } from '@midnight-ntwrk/midnight-js-utils'; import * as ledger from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { unshieldedToken } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { setNetworkId, getNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('preprod'); const CONFIG = { indexerHttpUrl: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWsUrl: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preprod.midnight.network', proofServer: 'http://localhost:6300', }; ``` ### Verification[​](#verification-2 "Direct link to Verification") The proof server answers its health check, which is the one external dependency this project needs beyond the public endpoints: ``` curl http://localhost:6300/health ``` ``` {"status":"ok","timestamp":"2026-08-07 11:29:05.352783759 +00:00:00"} ``` ## Building a wallet from a seed[​](#building-a-wallet-from-a-seed "Direct link to Building a wallet from a seed") Turn a seed into a running wallet. Midnight wallets are three sub-wallets, shielded, unshielded, and DUST, derived from one seed and unified behind a `WalletFacade`, and the facade is what the registration procedure acts on. ### Prerequisites[​](#prerequisites-2 "Direct link to Prerequisites") * The project from [Setting up the wallet SDK project](#setting-up-the-wallet-sdk-project). ### Procedure[​](#procedure-3 "Direct link to Procedure") 1. Derive the wallet's three key roles from a seed. One seed produces the shielded (`Zswap`), unshielded (`NightExternal`), and `Dust` key sets by hierarchical deterministic derivation. Read the seed from the environment so re-runs reuse the same wallet, and generate one only on the first run: Save the seed The seed is the only way to restore the wallet. A script that generates a fresh seed on every run creates a new, empty wallet each time and strands the funds in the previous one. ``` const seed = process.env.WALLET_SEED ?? toHex(Buffer.from(generateRandomSeed())); if (!process.env.WALLET_SEED) { console.log(`New wallet seed, save this and set WALLET_SEED to reuse it: ${seed}`); } const deriveKeys = (seed: string) => { const hd = HDWallet.fromSeed(Buffer.from(seed, 'hex')); if (hd.type !== 'seedOk') throw new Error('Invalid seed'); const result = hd.hdWallet .selectAccount(0) .selectRoles([Roles.Zswap, Roles.NightExternal, Roles.Dust]) .deriveKeysAt(0); if (result.type !== 'keysDerived') throw new Error('Key derivation failed'); hd.hdWallet.clear(); return result.keys; }; const keys = deriveKeys(seed); ``` 2. Build the three sub-wallets and unify them behind the `WalletFacade`. The DUST wallet requires `costParameters`: `feeBlocksMargin` sets how many blocks of finalization the fee estimate allows for, and `additionalFeeOverhead` is an optional buffer added on top of the computed fee, which defaults to `0n` if you omit it: ``` const shieldedSecretKeys = ledger.ZswapSecretKeys.fromSeed(keys[Roles.Zswap]); const dustSecretKey = ledger.DustSecretKey.fromSeed(keys[Roles.Dust]); const unshieldedKeystore = createKeystore(keys[Roles.NightExternal], getNetworkId()); const shieldedConfig = { networkId: getNetworkId(), indexerClientConnection: { indexerHttpUrl: CONFIG.indexerHttpUrl, indexerWsUrl: CONFIG.indexerWsUrl, }, provingServerUrl: new URL(CONFIG.proofServer), relayURL: new URL(CONFIG.node.replace(/^http/, 'ws')), }; const unshieldedConfig = { networkId: getNetworkId(), indexerClientConnection: { indexerHttpUrl: CONFIG.indexerHttpUrl, indexerWsUrl: CONFIG.indexerWsUrl, }, txHistoryStorage: new NoOpTransactionHistoryStorage(), }; const dustConfig = { ...shieldedConfig, costParameters: { // Optional buffer added on top of the computed fee. Defaults to 0n. additionalFeeOverhead: 300_000_000_000_000n, // 0.3 DUST // Blocks to allow for finalization when estimating the fee. feeBlocksMargin: 5, }, }; const wallet = await WalletFacade.init({ configuration: { ...shieldedConfig, ...unshieldedConfig, ...dustConfig }, shielded: (cfg) => ShieldedWallet(cfg).startWithSecretKeys(shieldedSecretKeys), unshielded: (cfg) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(unshieldedKeystore)), dust: (cfg) => DustWallet(cfg).startWithSecretKey(dustSecretKey, ledger.LedgerParameters.initialParameters().dust), }); await wallet.start(shieldedSecretKeys, dustSecretKey); ``` ### Verification[​](#verification-3 "Direct link to Verification") Key derivation is deterministic, the addresses carry the network's prefixes, and the facade connects all three sub-wallets to Preprod. The connectivity test distinguishes connected from synced on purpose: a wallet connects in seconds and finishes syncing much later. wallet-construction.test.ts ``` import { describe, it, expect, afterAll } from 'vitest'; import { WebSocket } from 'ws'; (globalThis as any).WebSocket = WebSocket; import { Buffer } from 'buffer'; import * as Rx from 'rxjs'; import { HDWallet, Roles, generateRandomSeed, WalletFacade, ShieldedWallet, DustWallet, UnshieldedWallet, createKeystore, PublicKey, NoOpTransactionHistoryStorage, DustAddress, MidnightBech32m, } from '@midnightntwrk/wallet-sdk'; import { toHex } from '@midnight-ntwrk/midnight-js-utils'; import * as ledger from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { setNetworkId, getNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('preprod'); const CONFIG = { indexerHttpUrl: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWsUrl: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preprod.midnight.network', proofServer: 'http://localhost:6300', }; const deriveKeys = (seed: string) => { const hd = HDWallet.fromSeed(Buffer.from(seed, 'hex')); if (hd.type !== 'seedOk') throw new Error('Invalid seed'); const result = hd.hdWallet .selectAccount(0) .selectRoles([Roles.Zswap, Roles.NightExternal, Roles.Dust]) .deriveKeysAt(0); if (result.type !== 'keysDerived') throw new Error('Key derivation failed'); hd.hdWallet.clear(); return result.keys; }; let wallet: any; afterAll(async () => { if (wallet) await wallet.stop(); }); describe('building a funding wallet', () => { it('derives the three key roles deterministically from one seed', () => { const seed = toHex(Buffer.from(generateRandomSeed())); const first = deriveKeys(seed); const second = deriveKeys(seed); expect(Buffer.from(first[Roles.NightExternal])).toEqual(Buffer.from(second[Roles.NightExternal])); expect(Buffer.from(first[Roles.Zswap])).toEqual(Buffer.from(second[Roles.Zswap])); expect(Buffer.from(first[Roles.Dust])).toEqual(Buffer.from(second[Roles.Dust])); }); it('encodes a preprod unshielded address with the mn_addr_preprod prefix', () => { const keys = deriveKeys(toHex(Buffer.from(generateRandomSeed()))); const keystore = createKeystore(keys[Roles.NightExternal], getNetworkId()); expect(String(keystore.getBech32Address())).toMatch(/^mn_addr_preprod1/); }); it('builds the wallet facade and connects all three wallets to preprod', { timeout: 120_000 }, async () => { const keys = deriveKeys(toHex(Buffer.from(generateRandomSeed()))); const shieldedSecretKeys = ledger.ZswapSecretKeys.fromSeed(keys[Roles.Zswap]); const dustSecretKey = ledger.DustSecretKey.fromSeed(keys[Roles.Dust]); const unshieldedKeystore = createKeystore(keys[Roles.NightExternal], getNetworkId()); const shieldedConfig = { networkId: getNetworkId(), indexerClientConnection: { indexerHttpUrl: CONFIG.indexerHttpUrl, indexerWsUrl: CONFIG.indexerWsUrl, }, provingServerUrl: new URL(CONFIG.proofServer), relayURL: new URL(CONFIG.node.replace(/^http/, 'ws')), }; const unshieldedConfig = { networkId: getNetworkId(), indexerClientConnection: { indexerHttpUrl: CONFIG.indexerHttpUrl, indexerWsUrl: CONFIG.indexerWsUrl, }, txHistoryStorage: new NoOpTransactionHistoryStorage(), }; const dustConfig = { ...shieldedConfig, costParameters: { additionalFeeOverhead: 300_000_000_000_000n, feeBlocksMargin: 5 }, }; wallet = await WalletFacade.init({ configuration: { ...shieldedConfig, ...unshieldedConfig, ...dustConfig }, shielded: (cfg: any) => ShieldedWallet(cfg).startWithSecretKeys(shieldedSecretKeys), unshielded: (cfg: any) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(unshieldedKeystore)), dust: (cfg: any) => DustWallet(cfg).startWithSecretKey(dustSecretKey, ledger.LedgerParameters.initialParameters().dust), }); await wallet.start(shieldedSecretKeys, dustSecretKey); const connected = await Rx.firstValueFrom( wallet.state().pipe( Rx.filter( (s: any) => s.shielded.state.progress.isConnected && s.unshielded.state.progress.isConnected && s.dust.state.progress.isConnected, ), ), ); expect(connected.isSynced).toBe(false); expect(connected.dust.balance(new Date())).toBe(0n); const dustAddress = DustAddress.encodePublicKey(getNetworkId(), connected.dust.publicKey); expect(String(dustAddress)).toMatch(/^mn_dust_preprod1/); expect(MidnightBech32m.parse(String(dustAddress)).decode(DustAddress, getNetworkId())).toBeDefined(); }); }); ``` ``` ✓ wallet-construction.test.ts > building a funding wallet > derives the three key roles deterministically from one seed ✓ wallet-construction.test.ts > building a funding wallet > encodes a preprod unshielded address with the mn_addr_preprod prefix ✓ wallet-construction.test.ts > building a funding wallet > builds the wallet facade and connects all three wallets to preprod Test Files 1 passed (1) Tests 3 passed (3) ``` ## Registering NIGHT for DUST generation with the wallet SDK[​](#registering-night-for-dust-generation-with-the-wallet-sdk "Direct link to Registering NIGHT for DUST generation with the wallet SDK") Do from code what the Lace procedure does through the UI: fund the wallet, register its NIGHT UTXOs for DUST generation, and watch DUST accrue. This is the part worth scripting, because it is what CI and provisioning jobs need. ### Prerequisites[​](#prerequisites-3 "Direct link to Prerequisites") * A running wallet from [Building a wallet from a seed](#building-a-wallet-from-a-seed). ### Procedure[​](#procedure-4 "Direct link to Procedure") 1. Print the unshielded address, fund it from the [faucet](#getting-tnight-from-the-faucet), and watch for the funds. Balances stream in while the wallet is still syncing, and a balance only ever counts UTXOs from block-confirmed transactions, so a positive balance on a newly funded wallet means the tokens have arrived even though sync is still running. Balances arrive as `bigint` values in the smallest denomination. NIGHT divides into 106 STAR, so the faucet's 1,000 tNIGHT reads as `1000000000`. DUST divides into 1015 SPECK. Convert before displaying: ``` const formatNight = (raw: bigint) => `${raw / 1_000_000n}.${(raw % 1_000_000n).toString().padStart(6, '0')}`; const formatDust = (raw: bigint) => `${raw / 1_000_000_000_000_000n}.${(raw % 1_000_000_000_000_000n).toString().padStart(15, '0')}`; console.log(`Send tNIGHT to: ${unshieldedKeystore.getBech32Address()}`); const nightBalance = await Rx.firstValueFrom( wallet.state().pipe( Rx.throttleTime(10_000), Rx.map((state) => state.unshielded.balances[unshieldedToken().raw] ?? 0n), Rx.filter((balance) => balance > 0n), ), ); console.log(`tNIGHT received: ${formatNight(nightBalance)}`); ``` 2. Wait for the wallet to sync, then register the unregistered NIGHT UTXOs for DUST generation. Registration needs a fully synced wallet, so `waitForSyncedState` gates this step; keep the process running, because a restarted script syncs again from the beginning. The registration is built as a recipe, signed by the unshielded keystore, finalized, and submitted. To direct the generated DUST to a different wallet, decode that wallet's DUST address as the receiver instead: ``` const state = await wallet.waitForSyncedState(); const unregistered = state.unshielded.availableCoins.filter( (coin) => coin.meta?.registeredForDustGeneration !== true, ); if (unregistered.length === 0) { console.log('All NIGHT is already registered for DUST generation.'); } else { // Send the DUST elsewhere by replacing this with another wallet's address. const target = String(DustAddress.encodePublicKey(getNetworkId(), state.dust.publicKey)); const dustReceiver = MidnightBech32m.parse(target).decode(DustAddress, getNetworkId()); const recipe = await wallet.registerNightUtxosForDustGeneration( unregistered, unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signData(payload), dustReceiver, ); const finalized = await wallet.finalizeRecipe(recipe); await wallet.submitTransaction(finalized); } ``` `MidnightBech32m.parse(...).decode(DustAddress, ...)` is also the validation step: it throws on anything that is not a DUST address for the current network, so a shielded or unshielded address pasted by mistake fails here rather than producing a registration that sends DUST nowhere useful. 3. Watch the DUST balance become positive. Generation begins once the registration transaction lands on-chain: ``` await Rx.firstValueFrom( wallet.state().pipe( Rx.throttleTime(5_000), Rx.filter((s) => s.isSynced), Rx.filter((s) => s.dust.balance(new Date()) > 0n), ), ); const dustBalance = (await Rx.firstValueFrom(wallet.state())).dust.balance(new Date()); console.log(`DUST balance: ${formatDust(dustBalance)}`); await wallet.stop(); ``` DUST accrues continuously, so this balance grows between checks until it reaches the cap your registered NIGHT sets. ### Verification[​](#verification-4 "Direct link to Verification") A saved seed restores the same wallet, the denominations convert as expected, and a mistyped receiver fails before it can be registered. The assertions below come from a second test file that shares the imports, the `deriveKeys` helper, and the two formatters shown earlier in this guide: funding-helpers.test.ts ``` describe('restored capabilities', () => { it('restores the same wallet from a saved seed', () => { const seed = toHex(Buffer.from(generateRandomSeed())); const addrOf = (s: string) => String(createKeystore(deriveKeys(s)[Roles.NightExternal], getNetworkId()).getBech32Address()); expect(addrOf(seed)).toBe(addrOf(seed)); expect(addrOf(seed)).not.toBe(addrOf(toHex(Buffer.from(generateRandomSeed())))); }); it('formats the faucet amount in NIGHT and DUST denominations', () => { expect(formatNight(1000000000n)).toBe('1000.000000'); expect(formatDust(405083000000n)).toBe('0.000405083000000'); }); it('rejects a non-DUST address when decoding a DUST receiver', () => { const keys = deriveKeys(toHex(Buffer.from(generateRandomSeed()))); const unshielded = String(createKeystore(keys[Roles.NightExternal], getNetworkId()).getBech32Address()); expect(unshielded).toMatch(/^mn_addr_preprod1/); expect(() => MidnightBech32m.parse(unshielded).decode(DustAddress, getNetworkId())).toThrow(); }); }); ``` ``` ✓ funding-helpers.test.ts > restored capabilities > restores the same wallet from a saved seed ✓ funding-helpers.test.ts > restored capabilities > formats the faucet amount in NIGHT and DUST denominations ✓ funding-helpers.test.ts > restored capabilities > rejects a non-DUST address when decoding a DUST receiver Test Files 1 passed (1) Tests 3 passed (3) ``` Running the full procedure against Preprod carries this through to a submitted registration and on to a DUST balance. Re-running it against the same wallet prints the following, with the registration already in place from the first run: ``` Send tNIGHT to: mn_addr_preprod1857k0p0nmd7g6788h6pr30lkdncg8zt097eq8cl57tx78gwhqlsqnr8r65 tNIGHT received: 1000.000000 All NIGHT is already registered for DUST generation. DUST balance: 2485.035398999999999 ``` DUST accrues continuously toward the cap that your registered NIGHT sets, so this balance grows between runs. Watch it with the balance check in the final step, or in Lace's tDUST tank. ## Funding troubleshooting[​](#funding-troubleshooting "Direct link to Funding troubleshooting") The failure modes readers hit most often on the funding path, and their fixes. | Symptom | Fix | | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Faucet says `Provided address is invalid` | Use the **unshielded** address (`mn_addr_...`) with no surrounding whitespace. The faucet rejects shielded and DUST addresses. | | Faucet says `rate_limit_error` or `Reached maximum number of requests` | Wait a few hours and retry. If it persists, open a ticket at the [Midnight Service Desk](https://midnightntwrk.github.io/servicedesk/) or ask in [Discord](https://discord.gg/midnightnetwork). | | `Cannot find module` when running the script | Run `npm install` first. If it persists, delete `node_modules` and `package-lock.json`, then reinstall. | | Connection refused on port 6300 | The proof server is not running; see [Run the proof server](/guides/run-proof-server.md). | | Balance stays zero after the faucet confirms | Give it a couple of minutes; the wallet detects funds after its next sync. Confirm the address you pasted matches the printed one exactly. | | DUST stays zero after registration | Give the registration time to land on-chain, then confirm the proof server answers on `http://localhost:6300/health`. | | `Invalid dust address` when directing DUST elsewhere | DUST addresses start with `mn_dust_` plus the network name; shielded (`mn_shield-addr_...`) and unshielded (`mn_addr_...`) addresses are different types. | ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Funding and transaction cost](/guides/networks-and-environments.md#funding-and-transaction-cost): why NIGHT generates DUST and what transactions consume. * [Environment reference](/guides/networks-and-environments.md#environment-reference): faucets and endpoints per network. * [Run the proof server](/guides/run-proof-server.md): the local proof server the SDK path depends on. * [Wallet developer guide](/sdks/official/wallet-developer-guide.md): the full wallet SDK surface behind the facade. * [Support matrix](/relnotes/support-matrix.md): which wallet SDK versions pair with which network components. * [Tokens on Midnight](/tokens/overview.md): the NIGHT and DUST model in depth. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Build a cross-chain DApp with EffectStream Use this guide to build a DApp whose state lives on Midnight and an EVM chain at once. You run a working template, learn how it joins the two chains, then add a field of your own end to end. [Index contract state with EffectStream](/guides/index-state-with-effectstream.md) covers reading one Midnight contract. This guide covers the case EffectStream exists for: correlating two chains, and writing to them. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * [Bun](https://bun.sh). See [Set up Bun for Midnight development](/guides/install-bun-runtime-midnight). * [Foundry](https://www.getfoundry.sh/). `forge` compiles the Solidity artifacts, and the orchestrator checks for it on PATH before starting. * The Compact compiler, which the orchestrator also checks on PATH. The template pins `0.31.0`, so run `compact update 0.31.0`. * Roughly 8 GB of free memory, and a raised Node heap for the frontend build. Vite transforms about 9000 modules and exceeds Node's default limit, so export `NODE_OPTIONS=--max-old-space-size=8192` before starting. The template launches its own Midnight stack, so you need no separately running node or proof server. ## How a rollup joins two chains[​](#how-a-rollup-joins-two-chains "Direct link to How a rollup joins two chains") Splitting a DApp across chains usually means a bridge: a message-passing contract, a relayer, and a light client that lets one chain verify the other. That machinery exists to make execution atomic across chains. EffectStream targets the weaker requirement. When you need a consistent view of two chains rather than atomic execution across them, neither chain has to know the other exists. Both are ingested independently, and a state machine you write merges them into one database. The template splits an NFT along that line. An ERC-721 contract on the EVM chain owns transfers, because everyone needs to agree on who holds a token. A Compact circuit on Midnight takes private inputs and discloses one resulting property, because the values behind it stay private. The two sides share a key, `(contract_address, token_id)`, which the user supplies to both. The rollup joins on that key. One consequence shapes the code you write. EffectStream reads Midnight's public ledger, so what a `disclose()` call publishes is what your state machine can see. Designing the circuit designs the sync surface. A second one shows up in the logs. Each chain syncs independently, so a Midnight property can arrive before the EVM transfer that created the token. The `midnightContractState` transition handles this by inserting a placeholder row, and you will see it skip events while the two chains catch up. ## Run the template[​](#run-the-template "Direct link to Run the template") Start the whole stack and mint a token. ### Procedure[​](#procedure "Direct link to Procedure") 1. Clone the repository and enter the template: ``` git clone https://github.com/effectstream/effectstream.git cd effectstream/templates/evm-midnight-v2 ``` 2. Install dependencies: ``` bun install ``` 3. Start the stack. This compiles the Compact circuit, compiles and deploys the Solidity contracts, deploys the Midnight contract, then starts the database, sync node, batcher, and frontend: ``` bun run dev ``` 4. Open the DApp at `http://localhost:10599`, mint a token, and set a property on it. ### Verification[​](#verification "Direct link to Verification") The sync node runs independently of the frontend, so check it directly. The merged view returns each token with its EVM owner and its Midnight properties: ``` curl http://localhost:9999/api/erc721 ``` The sync node's own logs show both chains advancing together, which is the rollup working: ``` INFO effectstream-sync-block-merge: finalized block 145 @ 0xdf3de2... | {"mainNtp":[145,145],"mainEvmRPC":[794,797]} [Midnight:undeployed] Fetching blocks from 32 to 32. ``` ## Local service endpoints[​](#local-service-endpoints "Direct link to Local service endpoints") Every service the template starts. | Service | URL | | ---------------------- | ------------------------------------------------------ | | Frontend | `http://localhost:10599` | | Sync node API | `http://localhost:9999` | | Sync node OpenAPI docs | `http://localhost:9999/documentation` | | Batcher | `http://localhost:3334` | | Orchestrator API | `http://localhost:4747` | | EVM chain (main) | `http://localhost:8545` | | EVM chain (parallel) | `http://localhost:8546` | | Midnight node RPC | `http://localhost:9944` | | Midnight indexer | `http://localhost:8088/api/v3/graphql` | | Midnight proof server | `http://localhost:6300` | | Database | `postgres://postgres:postgres@localhost:5432/postgres` | ## The ingestion pipeline[​](#the-ingestion-pipeline "Direct link to The ingestion pipeline") Four files carry a chain event from the wire into your API. Read them in order to understand the template. `packages/node/config.dev.ts` declares networks, sync protocols, and primitives. One primitive per chain, each naming a `stateMachinePrefix`: ``` .addPrimitive( (syncProtocols) => syncProtocols.parallelMidnight, (network, deployments, syncProtocol) => ({ name: "MidnightContractState", type: PrimitiveTypeMidnightGeneric, startBlockHeight: 1, contractAddress: readMidnightContract("contract-round-value", { networkId: midnightNetworkConfig.id, }).contractAddress, stateMachinePrefix: "midnightContractState", contract: { ledger: CounterContract.ledger }, networkId: midnightNetworkConfig.id, }), ) ``` `contract: { ledger: CounterContract.ledger }` hands the primitive the reader that `compact compile` generates. That reader decodes anything Compact can express, which is the difference from the declarative schema in [Index contract state with EffectStream](/guides/index-state-with-effectstream.md#what-the-ledger-schema-can-read). `packages/node/grammar.ts` maps each prefix to a parser. Both prefixes use builtin grammars, so the template writes none of its own. `packages/node/state-machine.ts` holds one state transition function per prefix. Each receives the parsed payload and writes to the database. `packages/node/api.ts` serves the merged result over HTTP. ## Add a field end to end[​](#add-a-field-end-to-end "Direct link to Add a field end to end") Carry one new value from the Compact circuit to the API. Nothing generates this path for you, so a single field touches the circuit, the database schema, the queries, the state transition, and the route. Knowing that cost up front is part of choosing this pattern. ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. Open `packages/contracts-midnight/contract-round-value/src/counter.compact`. Add a ledger field, take a matching argument in `increment`, and assign it through `disclose()`. The additions are marked: ``` pragma language_version >= 0.17; import CompactStandardLibrary; export ledger round: Counter; export ledger contract_address: Bytes<64>; export ledger token_id: Bytes<64>; export ledger property_name: Bytes<32>; export ledger value: Bytes<32>; export ledger rarity: Bytes<32>; // added export circuit increment( contract_address_: Bytes<64>, token_id_: Bytes<64>, property_name_: Bytes<32>, value_: Bytes<32>, rarity_: Bytes<32>, // added ): [] { round.increment(1); contract_address = disclose(contract_address_); token_id = disclose(token_id_); property_name = disclose(property_name_); value = disclose(value_); rarity = disclose(rarity_); // added } ``` Adding an argument changes the circuit's signature, so every caller needs the new value. The frontend calls this circuit in `packages/frontend/client/src/increment.ts`, and the batcher calls it in `packages/batcher/midnight-balancing.ts`. 2. Recompile the circuit so the generated ledger reader includes the new field: ``` bun run build:midnight ``` 3. Add a column to the migration in `packages/database/migrations/`. 4. Add the column to the matching query in `packages/database/sql/sm_example.sql`, then regenerate the typed queries: ``` bun run build:pgtypes ``` 5. Decode the field in the `midnightContractState` transition in `packages/node/state-machine.ts`. A `Bytes<32>` ledger field arrives as fixed-width bytes, so `decodeField` turns it back into a string. Add a line next to the existing ones: ``` const contract_address = decodeField(payload.contract_address); const token_id = decodeField(payload.token_id); const property_name = decodeField(payload.property_name); const value = decodeField(payload.value); const rarity = decodeField(payload.rarity); // added ``` Then pass `rarity` into the `insertEvmMidnightProperty` call further down the same transition, alongside the fields already written there. 6. Return the column from `GET /api/erc721` in `packages/node/api.ts`. 7. Restart the stack and set a property from the frontend. ### Verification[​](#verification-1 "Direct link to Verification") The endpoint returns the new field alongside the existing ones. ``` curl http://localhost:9999/api/erc721 ``` ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Index contract state with EffectStream](/guides/index-state-with-effectstream.md): the read path, one Midnight contract, no local stack. * [EffectStream documentation](https://effectstream.github.io/docs/): the full API surface, the batcher, and the other cross-chain templates. * [Security and best practices](/guides/security-best-practices.md#on-chain-visibility): what `disclose()` makes public, which is what a sync node reads. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Using Compact contracts from JavaScript Compiling a Compact contract produces zero-knowledge circuits and, alongside them, a JavaScript module that runs the same contract logic. Everything you do with a contract from JavaScript goes through that module: you wire in the witnesses that supply its private data, call its circuits with native values, and decode its ledger state through typed getters. Because a circuit call runs the logic the circuit enforces on-chain, the module also makes contract behavior testable, including the paths your `assert` statements are supposed to reject, without a node, an indexer, or a proof server. Running the module off-chain covers contract logic, not the rest of the submission path. It does not generate or verify a proof, assemble or price a transaction, or account for ledger state that changed since your local run, so a call that passes here can still fail when the transaction reaches the network. This guide walks that path: implement the witnesses a contract needs, call its circuits from JavaScript, and build a unit test suite around it. The reference sections at the end list what the module exports and what its error messages mean, for when a stack trace or a type error sends you into it. The examples use the [bulletin board contract](https://github.com/midnightntwrk/example-bboard) throughout. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * The [Compact CLI](/getting-started/installation.md) installed, with `compact compile` working. * A compiled contract. This guide compiles `bboard.compact` from [example-bboard](https://github.com/midnightntwrk/example-bboard); any contract works, with your own names in place of the bulletin board's. * Node.js with [Vitest](https://vitest.dev/) and `@midnight-ntwrk/compact-runtime` installed. * A runtime version that matches your compiler. The generated code enforces this pairing at import time; check the [support matrix](/relnotes/support-matrix.md) when either changes. ## What the compiler generates[​](#what-the-compiler-generates "Direct link to What the compiler generates") Compiling a contract produces two artifacts that mirror each other: the ZK circuits the network verifies, and a JavaScript module that executes the identical contract logic off-chain. Understanding that the two are generated together, from the same source, is what makes the module trustworthy as a testing surface. When you run `compact compile`, the compiler: 1. Parses your `.compact` file and emits a ZK circuit for each exported circuit that needs a proof, that is, the impure circuits. An exported pure circuit such as the bulletin board's `publicKey` compiles to JavaScript only. 2. Generates a JavaScript implementation that mirrors the contract's structure: it identifies each circuit's signature, embeds type descriptors for every Compact type the contract uses, and wraps each circuit so you can invoke it with native JavaScript values. 3. Links the generated code against `@midnight-ntwrk/compact-runtime`, the shared library that implements field arithmetic, serialization, error types, and the ledger query machinery. The generated file and the runtime together form a complete execution environment. 4. Emits a TypeScript declaration file so the module is fully typed in a TypeScript project. The JavaScript output lands in the `contract/` subdirectory of your compilation target (for example `src/managed/bboard/contract/`), alongside the `keys/`, `zkir/`, and `compiler/` directories the compiler also emits: * `index.js`: the JavaScript implementation * `index.d.ts`: TypeScript type definitions * `index.js.map`: source map for debugging Generated code only `index.js` is regenerated on every compilation. If you add or remove circuits or change types, recompile; never edit the generated files by hand. ## Implementing witnesses for a contract[​](#implementing-witnesses-for-a-contract "Direct link to Implementing witnesses for a contract") Load the generated module and give the contract its witnesses: the functions that supply private data, such as a secret key, when a circuit asks for it. The contract cannot be instantiated without them, and the generated constructor rejects an incomplete witnesses object with a precise error, which is the behavior the verification below relies on. ### Procedure[​](#procedure "Direct link to Procedure") 1. Compile the contract, giving `compact compile` the source and the target directory. The paths below assume the contract lives at `src/bboard.compact`; in [example-bboard](https://github.com/midnightntwrk/example-bboard) it sits at `contract/src/bboard.compact`, so adjust to match your layout: ``` compact compile src/bboard.compact src/managed/bboard ``` 2. Import the module like any other ES module, from a file alongside the `managed` directory the compiler just wrote. In TypeScript, the declaration file types everything automatically: ``` import { Contract, State, ledger, pureCircuits } from './managed/bboard/contract/index.js'; ``` 3. Define the private state your witnesses read, and implement one function per witness the Compact source declares. For the bulletin board, that is `localSecretKey`: ``` import { Ledger } from './managed/bboard/contract/index.js'; import { WitnessContext } from '@midnight-ntwrk/compact-runtime'; export type BBoardPrivateState = { readonly secretKey: Uint8Array; }; export const createBBoardPrivateState = (secretKey: Uint8Array) => ({ secretKey, }); export const witnesses = { localSecretKey: ({ privateState, }: WitnessContext): [BBoardPrivateState, Uint8Array] => [ privateState, privateState.secretKey, ], }; ``` Each witness receives a `WitnessContext` carrying the ledger view, the private state, and the contract address, and returns a tuple of the updated private state and the witness value. 4. Instantiate the contract with the witnesses object: ``` const contract = new Contract(witnesses); ``` ### Verification[​](#verification "Direct link to Verification") A complete witnesses object produces a working instance, and the generated validation rejects an incomplete one. import-witnesses.test.ts ``` import { describe, it, expect } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract } from './managed/bboard/contract/index.js'; const COIN = '0'.repeat(64); const witnesses = { localSecretKey: ({ privateState }) => [privateState, privateState.secretKey], }; describe('importing the implementation', () => { it('wires the witnesses into a working contract instance', () => { const contract = new Contract(witnesses); const secretKey = new Uint8Array(32); const ctor = contract.initialState(RT.createConstructorContext({ secretKey }, COIN)); expect(ctor.currentContractState).toBeDefined(); }); it('rejects a witnesses object missing a declared witness', () => { expect(() => new Contract({})).toThrow( 'does not contain a function-valued field named localSecretKey', ); }); }); ``` ``` ✓ import-witnesses.test.ts > importing the implementation > wires the witnesses into a working contract instance ✓ import-witnesses.test.ts > importing the implementation > rejects a witnesses object missing a declared witness Test Files 1 passed (1) Tests 2 passed (2) ``` ## Calling circuits from JavaScript[​](#calling-circuits-from-javascript "Direct link to Calling circuits from JavaScript") Run contract logic off-chain by building a circuit context and invoking circuits through the instance. Build the context with the runtime helpers rather than by hand. A real `CircuitContext` carries query-context state that the wrappers check for, so hand-built objects fail validation. ### Prerequisites[​](#prerequisites-1 "Direct link to Prerequisites") * A contract instance with witnesses, from [Implementing witnesses for a contract](#implementing-witnesses-for-a-contract). ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. Create the genesis state with `initialState`, then build a circuit context from it. The constructor context takes the initial private state and a coin public key; the circuit context adds the contract address: ``` import * as RT from '@midnight-ntwrk/compact-runtime'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const secretKey = new Uint8Array(32); const ctor = contract.initialState(RT.createConstructorContext({ secretKey }, COIN)); const ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { secretKey }); ``` 2. Call an impure circuit with the context. The wrapper validates the inputs, runs the contract logic, and returns the result together with the updated context, the proof data, and the gas cost: ``` const call = contract.impureCircuits.post(ctx, 'Hello from Compact!'); // call.result -> the circuit's return value ([] for post) // call.context -> the updated circuit context // call.proofData -> input, output, and transcripts for proof generation // call.gasCost -> cost tracking for the call ``` 3. Read the resulting ledger state with the `ledger()` helper: ``` const board = ledger(call.context.currentQueryContext.state); // board.state, board.message, board.sequence, board.owner ``` 4. Call pure circuits directly, with no context at all: ``` const commitment = pureCircuits.publicKey(secretKey, new Uint8Array(32)); ``` ### Verification[​](#verification-1 "Direct link to Verification") The impure circuit transitions the board to occupied and returns proof data; the pure circuit computes deterministically without a context. circuits.test.ts ``` import { describe, it, expect } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract, State, ledger, pureCircuits } from './managed/bboard/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const key = (n) => { const a = new Uint8Array(32); a[31] = n; return a; }; const witnesses = { localSecretKey: ({ privateState }) => [privateState, privateState.secretKey], }; describe('calling contract circuits', () => { it('runs an impure circuit and returns the result, context, and proof data', () => { const contract = new Contract(witnesses); const ctor = contract.initialState(RT.createConstructorContext({ secretKey: key(7) }, COIN)); const ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { secretKey: key(7) }); const call = contract.impureCircuits.post(ctx, 'Hello from Compact!'); expect(call.result).toEqual([]); expect(call.proofData.publicTranscript.length).toBeGreaterThan(0); expect(call.gasCost).toBeDefined(); const board = ledger(call.context.currentQueryContext.state); expect(board.state).toBe(State.OCCUPIED); expect(board.message.value).toBe('Hello from Compact!'); }); it('calls a pure circuit directly, with no circuit context', () => { const commitment = pureCircuits.publicKey(key(7), key(1)); expect(commitment).toBeInstanceOf(Uint8Array); expect(commitment.length).toBe(32); expect(commitment).toEqual(pureCircuits.publicKey(key(7), key(1))); }); }); ``` ``` ✓ circuits.test.ts > calling contract circuits > runs an impure circuit and returns the result, context, and proof data ✓ circuits.test.ts > calling contract circuits > calls a pure circuit directly, with no circuit context Test Files 1 passed (1) Tests 2 passed (2) ``` ## Writing a unit test suite[​](#writing-a-unit-test-suite "Direct link to Writing a unit test suite") Test contract logic with an ordinary test framework, no node, indexer, or proof server required. A good suite exercises both directions: the paths that must succeed, and the paths your `assert` statements must reject, including a caller with the wrong private state. ### Prerequisites[​](#prerequisites-2 "Direct link to Prerequisites") * The context pattern from [Calling circuits from JavaScript](#calling-circuits-from-javascript). ### Procedure[​](#procedure-2 "Direct link to Procedure") 1. Write a setup helper that builds a fresh contract and context per test: ``` const setup = (secretKey = key(7)) => { const contract = new Contract(witnesses); const ctor = contract.initialState(RT.createConstructorContext({ secretKey }, COIN)); const ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { secretKey }); return { contract, ctx }; }; ``` 2. Assert the success paths through the typed ledger view, and the failure paths against the exact `assert` messages from the Compact source. To simulate an attacker, run a circuit with a context whose `currentPrivateState` holds a different secret: ``` const stranger = { ...occupied, currentPrivateState: { secretKey: key(9) } }; expect(() => contract.impureCircuits.takeDown(stranger)).toThrow( 'Attempted to take down post, but not the current owner', ); ``` ### Verification[​](#verification-2 "Direct link to Verification") The full suite covers the genesis state, the post and take-down lifecycle, both rejection paths, and pure-circuit determinism. bboard.test.ts ``` import { describe, it, expect } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract, State, ledger, pureCircuits } from './managed/bboard/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const key = (n) => { const a = new Uint8Array(32); a[31] = n; return a; }; const witnesses = { localSecretKey: ({ privateState }) => [privateState, privateState.secretKey], }; const setup = (secretKey = key(7)) => { const contract = new Contract(witnesses); const ctor = contract.initialState(RT.createConstructorContext({ secretKey }, COIN)); const ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { secretKey }); return { contract, ctx }; }; describe('bulletin board contract', () => { it('starts vacant', () => { const { ctx } = setup(); const board = ledger(ctx.currentQueryContext.state); expect(board.state).toBe(State.VACANT); expect(board.message.is_some).toBe(false); expect(board.sequence).toBe(1n); }); it('accepts a post on a vacant board', () => { const { contract, ctx } = setup(); const result = contract.impureCircuits.post(ctx, 'Test message'); const board = ledger(result.context.currentQueryContext.state); expect(board.state).toBe(State.OCCUPIED); expect(board.message.is_some).toBe(true); expect(board.message.value).toBe('Test message'); }); it('rejects a post on an occupied board', () => { const { contract, ctx } = setup(); const occupied = contract.impureCircuits.post(ctx, 'First message').context; expect(() => contract.impureCircuits.post(occupied, 'Second message')).toThrow( 'Attempted to post to an occupied board', ); }); it('lets the owner take the post down and returns the message', () => { const { contract, ctx } = setup(); const occupied = contract.impureCircuits.post(ctx, 'Mine to remove').context; const takeDown = contract.impureCircuits.takeDown(occupied); expect(takeDown.result).toBe('Mine to remove'); expect(ledger(takeDown.context.currentQueryContext.state).state).toBe(State.VACANT); }); it('rejects a take-down from a non-owner', () => { const { contract, ctx } = setup(); const occupied = contract.impureCircuits.post(ctx, 'Not yours').context; const stranger = { ...occupied, currentPrivateState: { secretKey: key(9) } }; expect(() => contract.impureCircuits.takeDown(stranger)).toThrow( 'Attempted to take down post, but not the current owner', ); }); it('computes a deterministic result from the owner-commitment circuit', () => { const first = pureCircuits.publicKey(key(7), key(1)); const second = pureCircuits.publicKey(key(7), key(1)); const other = pureCircuits.publicKey(key(8), key(1)); expect(first).toBeInstanceOf(Uint8Array); expect(first.length).toBe(32); expect(first).toEqual(second); expect(first).not.toEqual(other); }); }); ``` ``` ✓ bboard.test.ts > bulletin board contract > starts vacant ✓ bboard.test.ts > bulletin board contract > accepts a post on a vacant board ✓ bboard.test.ts > bulletin board contract > rejects a post on an occupied board ✓ bboard.test.ts > bulletin board contract > lets the owner take the post down and returns the message ✓ bboard.test.ts > bulletin board contract > rejects a take-down from a non-owner ✓ bboard.test.ts > bulletin board contract > computes a deterministic result from the owner-commitment circuit Test Files 1 passed (1) Tests 6 passed (6) ``` ## The generated export surface[​](#the-generated-export-surface "Direct link to The generated export surface") What the module and its declaration file export, and what each export is for. Consult this when wiring the implementation into an application or test suite. | Export | Kind | Purpose | | ---------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------- | | `Contract` | class | Instantiated with your witnesses; exposes `circuits`, `impureCircuits`, `provableCircuits`, and `initialState()` | | `pureCircuits` | object | Pure circuits callable without a circuit context | | `ledger(state)` | function | Decodes a `StateValue` or `ChargedState` into typed per-field getters | | `State` | enum | The contract's exported Compact enum, mirrored in JavaScript | | `contractReferenceLocations` | constant | Internal metadata about contract references in ledger state | The declaration file types the same surface for TypeScript projects: ``` export type Witnesses = { localSecretKey(context: __compactRuntime.WitnessContext): [PS, Uint8Array]; } // ... State enum and Circuits / ProvableCircuits types omitted ... export type ImpureCircuits = { post(context: __compactRuntime.CircuitContext, newMessage_0: string): __compactRuntime.CircuitResults; takeDown(context: __compactRuntime.CircuitContext): __compactRuntime.CircuitResults; } export type PureCircuits = { publicKey(sk_0: Uint8Array, sequence_0: Uint8Array): Uint8Array; } export type Ledger = { readonly state: State; readonly message: { is_some: boolean, value: string }; readonly sequence: bigint; readonly owner: Uint8Array; } export declare class Contract = Witnesses> { witnesses: W; circuits: Circuits; impureCircuits: ImpureCircuits; provableCircuits: ProvableCircuits; constructor(witnesses: W); initialState(context: __compactRuntime.ConstructorContext): __compactRuntime.ConstructorResult; } // ... ContractReferenceLocations omitted ... export declare function ledger(state: __compactRuntime.StateValue | __compactRuntime.ChargedState): Ledger; export declare const pureCircuits: PureCircuits; ``` The generic parameter `PS` is your private state type, which the witnesses read and update. With these declarations, a TypeScript project gets autocomplete and compile-time checking on every circuit call. Everything else in the module, the `_descriptor_*` objects and the classes generated for composite types such as `Maybe`, is internal encoding machinery. It is regenerated on every compile and its numbering shifts as the contract changes, so the exports above are the only supported surface. ## Errors from the generated module[​](#errors-from-the-generated-module "Direct link to Errors from the generated module") The generated code validates at three points: at import time, in the `Contract` constructor, and on every circuit call. The import-time check is the version guard at the top of `index.js`: ``` import * as __compactRuntime from '@midnight-ntwrk/compact-runtime'; __compactRuntime.checkRuntimeVersion('0.16.0'); ``` Match an error against this table before reading the generated source: | Error | Cause | Fix | | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | Throws at import, naming a runtime version | The installed `@midnight-ntwrk/compact-runtime` is not compatible with the version the compiler expects: for a `0.x` runtime, compatible means the same minor version and at least the expected patch | Pair the compiler and runtime using the [support matrix](/relnotes/support-matrix.md) | | `Contract constructor: expected 1 argument, received 0` | The constructor takes exactly one argument, the witnesses object | Pass the witnesses object, and nothing else | | `does not contain a function-valued field named localSecretKey` | The witnesses object is missing a witness the Compact source declares | Implement one function per declared witness, as in [Implementing witnesses for a contract](#implementing-witnesses-for-a-contract) | | `post: expected 2 arguments (as invoked from Typescript), received 0` | An impure circuit takes the circuit context plus each parameter in the Compact signature | Pass the context first, then the circuit's own arguments | | `type error: ... expected value of type CircuitContext`, citing a line in your `.compact` source | The context was built by hand, so the wrapper's check for `currentQueryContext` fails | Build contexts with `createConstructorContext` and `createCircuitContext`, as in [Calling circuits from JavaScript](#calling-circuits-from-javascript) | | `expected instance of ChargedState` | `ledger()` received a `ContractState`, which it does not accept | Pass the state from a circuit call, or a deployed contract state's `data` field | | An `assert` message from your own Compact source | Contract logic rejected the call | Nothing to fix in the harness: this is the rejection path a test asserts with `expect(...).toThrow(...)` | ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Bulletin board DApp](/examples/dapps/bboard.md): the complete application built around this contract. * [Test and debug](/compact/test-and-debug.md): debugging strategies and common failure scenarios. Its code examples predate the current `CircuitContext` API, so use the context pattern from this page. * [Security and best practices](/guides/security-best-practices.md): adversarial testing patterns that build on this harness. * [Compact runtime API reference](/api-reference/compact-runtime.md): the `CircuitContext`, `WitnessContext`, and helper functions used here. * [Support matrix](/relnotes/support-matrix.md): which compiler version pairs with which runtime version. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Deploying and operating a contract A contract that passes its off-chain tests is ready for a network. Getting it there, and keeping it working afterwards, is one workflow with four parts: wire up the providers that Midnight.js uses to reach the network, deploy the contract and hold onto its address, observe its on-chain state, and operate the maintenance authority that lets you update its circuits later. This guide walks that workflow in order. The examples deploy the [bulletin board contract](https://github.com/midnightntwrk/example-bboard) to the local network from [Networks and environments](/guides/networks-and-environments.md#running-a-local-network), so every step runs with nothing at risk; the same code moves to Preprod by swapping endpoints and funding a real wallet. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * A fully compiled contract: `compact compile` without skip flags, so the output contains `keys/` and `zkir/` alongside `contract/`. [Using Compact contracts from JavaScript](/guides/compact-javascript-runtime.md) covers the compile and the generated module. * A running network. The procedures use the local stack from [Running a local network](/guides/networks-and-environments.md#running-a-local-network); its clone also provides the wallet helpers the verification tests import. * A wallet holding NIGHT and registered for DUST generation, since every transaction costs DUST. On the local network the genesis wallet is pre-funded; on Preprod, follow [Funding a wallet](/guides/acquire-tokens.md). * Node.js 22 or later, with the `@midnight-ntwrk/midnight-js-*` packages at the version the [support matrix](/relnotes/support-matrix.md) pairs with your compiler. ## The transaction pipeline and its providers[​](#the-transaction-pipeline-and-its-providers "Direct link to The transaction pipeline and its providers") Submitting a circuit call is a pipeline, and each stage has a pluggable component. When a DApp calls a deployed contract, Midnight.js executes the contract logic locally, generates a zero-knowledge proof of that execution, balances the transaction with DUST to cover its fee, and submits the result to the network. Reading, rather than writing, follows the same shape: contract state comes from an indexer, and private state never leaves the machine. The `MidnightProviders` object names one provider per capability, and every deploy or call takes the whole object: * `privateStateProvider` stores the contract's private state, and the signing keys the SDK generates, on the local device. * `publicDataProvider` queries and subscribes to on-chain contract state through the indexer's GraphQL API. * `zkConfigProvider` supplies the prover key, verifier key, and ZKIR artifacts from the compile. * `proofProvider` sends proof requests to a proof server. * `walletProvider` exposes the wallet's receiving keys and balances transactions. * `midnightProvider` submits the finalized transaction. An optional seventh slot, `loggerProvider`, accepts a logger; the six above are required. The type is generic over your contract, so the compiler catches a circuit name or private state shape that does not match: ``` import { type MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; export type BBoardPrivateState = { readonly secretKey: Uint8Array }; export type BBoardProviders = MidnightProviders<'post' | 'takeDown', 'bboardPrivateState', BBoardPrivateState>; ``` Keep these aliases in a shared module, such as a `common-types.ts`, when your API and UI packages use the same contract types. Which implementation fills each slot depends on where the code runs; the [Provider implementations](#provider-implementations) reference lists the options. The procedures below use the Node.js implementations. ## Configuring providers for a contract[​](#configuring-providers-for-a-contract "Direct link to Configuring providers for a contract") Construct the six providers and assemble them into the object every deploy and call takes. The code below targets the local network; for a public network, swap the endpoints from the [environment reference](/guides/networks-and-environments.md#environment-reference). ### Procedure[​](#procedure "Direct link to Procedure") 1. Install the provider packages, letting the [support matrix](/relnotes/support-matrix.md) set the versions: ``` npm install @midnight-ntwrk/midnight-js-types @midnight-ntwrk/midnight-js-contracts \ @midnight-ntwrk/midnight-js-network-id @midnight-ntwrk/midnight-js-level-private-state-provider \ @midnight-ntwrk/midnight-js-indexer-public-data-provider @midnight-ntwrk/midnight-js-node-zk-config-provider \ @midnight-ntwrk/midnight-js-http-client-proof-provider @midnight-ntwrk/midnight-js-utils ``` 2. Set the network ID before touching any provider, and polyfill `WebSocket` in Node.js so the wallet SDK's indexer connection works; the public data provider ships its own implementation. Midnight.js reads the network ID when it normalizes addresses and builds transactions: ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import { WebSocket } from 'ws'; setNetworkId('undeployed'); // local network; 'preprod', 'preview', or 'mainnet' for public networks globalThis.WebSocket = WebSocket as unknown as typeof globalThis.WebSocket; ``` 3. Create the private state provider. It persists private state and signing keys to an encrypted LevelDB store on the local device. Two of its options are enforced at runtime: `accountId` is required, so stored state is scoped to one wallet and cannot leak across accounts, and the encryption password must be at least 16 characters with at least three of the four character classes (uppercase, lowercase, digits, special characters): ``` import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; const privateStateProvider = levelPrivateStateProvider({ privateStateStoreName: 'bboard-private-state', signingKeyStoreName: 'bboard-signing-keys', privateStoragePasswordProvider: () => 'Docs-Verify-2026', accountId: walletAddress, // the wallet's Bech32m address, or another per-account identifier }); ``` Derive the password, do not hardcode it The password encrypts private state and signing keys at rest. In production, derive it from wallet credentials or a key management system rather than shipping a literal in your source. 4. Create the public data provider with your indexer's query and subscription endpoints: ``` import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; const publicDataProvider = indexerPublicDataProvider( 'http://127.0.0.1:8088/api/v4/graphql', 'ws://127.0.0.1:8088/api/v4/graphql/ws', ); ``` 5. Create the ZK config provider, pointed at the compile output directory that holds `keys/` and `zkir/`. The type parameter is the union of your circuit names: ``` import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; const zkConfigProvider = new NodeZkConfigProvider<'post' | 'takeDown'>('/path/to/managed/bboard'); ``` 6. Create the proof provider from the proof server URL and the ZK config provider, which supplies the artifacts proving needs: ``` import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; const proofProvider = httpClientProofProvider('http://127.0.0.1:6300', zkConfigProvider); ``` 7. Implement the wallet and submission providers. One class can serve both slots, backed by a synced `WalletFacade`. Import the ledger types from `@midnight-ntwrk/midnight-js-protocol/ledger`, not from the ledger package directly; the protocol package re-exports the exact copies Midnight.js compiles against, and pulling in a second copy of the ledger package fails to type-check: ``` import { type CoinPublicKey, type EncPublicKey, type FinalizedTransaction, ZswapSecretKeys, DustSecretKey, } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { type WalletProvider, type MidnightProvider, type UnboundTransaction, } from '@midnight-ntwrk/midnight-js-types'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import { type WalletFacade } from '@midnight-ntwrk/wallet-sdk'; class BBoardWalletProvider implements WalletProvider, MidnightProvider { constructor( private readonly wallet: WalletFacade, private readonly zswapSecretKeys: ZswapSecretKeys, private readonly dustSecretKey: DustSecretKey, ) {} getCoinPublicKey(): CoinPublicKey { return this.zswapSecretKeys.coinPublicKey; } getEncryptionPublicKey(): EncPublicKey { return this.zswapSecretKeys.encryptionPublicKey; } async balanceTx(tx: UnboundTransaction, ttl: Date = ttlOneHour()): Promise { const recipe = await this.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: this.zswapSecretKeys, dustSecretKey: this.dustSecretKey }, { ttl }, ); return await this.wallet.finalizeRecipe(recipe); } submitTx(tx: FinalizedTransaction): Promise { return this.wallet.submitTransaction(tx); } } ``` `getCoinPublicKey` and `getEncryptionPublicKey` expose the keys that receive and decrypt shielded outputs, `balanceTx` selects DUST to cover the fee and finalizes the transaction, and `submitTx` sends it to the network. [Funding a wallet](/guides/acquire-tokens.md) covers building and syncing the `WalletFacade` and deriving the secret keys. 8. Assemble the object, passing the same instance as both `walletProvider` and `midnightProvider`: ``` const walletProvider = new BBoardWalletProvider(wallet, zswapSecretKeys, dustSecretKey); const providers: BBoardProviders = { privateStateProvider, publicDataProvider, zkConfigProvider, proofProvider, walletProvider, midnightProvider: walletProvider, }; ``` ### Verification[​](#verification "Direct link to Verification") The providers assemble against real compile artifacts and endpoints, and the private state provider enforces its `accountId` requirement. This file, like every test in this guide, runs inside the [midnight-local-dev](https://github.com/midnightntwrk/midnight-local-dev) clone from the local network setup, importing its wallet helpers. Save it under `docs-tests/` in the clone and run: ``` npx vitest run docs-tests --testTimeout=600000 --hookTimeout=600000 ``` docs-tests/providers.test.ts ``` import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import { StandaloneConfig } from '../src/config.js'; import { buildWalletFromHexSeed, closeWallet, type WalletContext } from '../src/wallet.js'; const BBOARD = new URL('../managed-bboard', import.meta.url).pathname; const GENESIS_SEED = '0'.repeat(63) + '1'; describe('configuring providers', () => { const config = new StandaloneConfig(); let ctx: WalletContext; beforeAll(async () => { ctx = await buildWalletFromHexSeed(config, GENESIS_SEED); }); afterAll(async () => { await closeWallet(ctx); }); it('rejects a private-state store configured without an accountId', () => { expect(() => (levelPrivateStateProvider as any)({ privateStateStoreName: 'docs-no-account-state', signingKeyStoreName: 'docs-no-account-keys', privateStoragePasswordProvider: () => 'Docs-Verify-2026', }), ).toThrow('accountId is required'); }); it('assembles all six providers against real artifacts and endpoints', async () => { const zkConfigProvider = new NodeZkConfigProvider<'post' | 'takeDown'>(BBOARD); const walletAndMidnightProvider = { getCoinPublicKey: () => ctx.shieldedSecretKeys.coinPublicKey, getEncryptionPublicKey: () => ctx.shieldedSecretKeys.encryptionPublicKey, balanceTx: async (tx: any, ttl: Date = ttlOneHour()) => { const recipe = await ctx.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: ctx.shieldedSecretKeys, dustSecretKey: ctx.dustSecretKey }, { ttl }, ); return await ctx.wallet.finalizeRecipe(recipe); }, submitTx: (tx: any) => ctx.wallet.submitTransaction(tx), }; const providers = { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: 'docs-bboard-private-state', signingKeyStoreName: 'docs-bboard-signing-keys', privateStoragePasswordProvider: () => 'Docs-Verify-2026', accountId: ctx.unshieldedKeystore.getBech32Address().asString(), }), publicDataProvider: indexerPublicDataProvider(config.indexer, config.indexerWS), zkConfigProvider, proofProvider: httpClientProofProvider(config.proofServer, zkConfigProvider), walletProvider: walletAndMidnightProvider, midnightProvider: walletAndMidnightProvider, }; expect(Object.keys(providers).sort()).toEqual([ 'midnightProvider', 'privateStateProvider', 'proofProvider', 'publicDataProvider', 'walletProvider', 'zkConfigProvider', ]); const verifierKey = await zkConfigProvider.getVerifierKey('post'); expect(verifierKey.length).toBeGreaterThan(0); }); }); ``` ``` ✓ docs-tests/providers.test.ts > configuring providers > rejects a private-state store configured without an accountId 1ms ✓ docs-tests/providers.test.ts > configuring providers > assembles all six providers against real artifacts and endpoints 5ms Test Files 1 passed (1) Tests 2 passed (2) ``` ## Deploying a contract[​](#deploying-a-contract "Direct link to Deploying a contract") Deploy by pairing the generated contract module with its compile artifacts, then calling `deployContract`. The contract address that comes back is how everything else reaches the contract, so capture it. ### Prerequisites[​](#prerequisites-1 "Direct link to Prerequisites") * The providers object from [Configuring providers for a contract](#configuring-providers-for-a-contract). ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. Build a `CompiledContract` from the generated module. `make` names the contract and takes the generated `Contract` class, `withWitnesses` attaches your witness implementations, and `withCompiledFileAssets` points at the compile output directory: ``` import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import { Contract } from './managed/bboard/contract/index.js'; const witnesses = { localSecretKey: ({ privateState }) => [privateState, privateState.secretKey], }; const compiled = CompiledContract.withCompiledFileAssets( CompiledContract.withWitnesses(CompiledContract.make('bboard', Contract), witnesses), '/path/to/managed/bboard', ); ``` 2. Deploy, supplying the private state identifier and the initial private state. The call executes the contract's constructor, proves it, balances the fee, submits, and resolves once the transaction is finalized: ``` import { deployContract } from '@midnight-ntwrk/midnight-js-contracts'; const deployed = await deployContract(providers, { compiledContract: compiled, privateStateId: 'bboardPrivateState', initialPrivateState: { secretKey }, }); const contractAddress = deployed.deployTxData.public.contractAddress; ``` When you do not pass a `signingKey`, `deployContract` samples a fresh one, sets it as the contract's maintenance authority, and stores it in your private state provider under the contract's address. [Operating a maintenance authority](#operating-a-maintenance-authority) covers supplying your own, and [`DeployContractOptions`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployContractOptions.md) lists every option. 3. Store `contractAddress` wherever your application needs it. Anyone reconnecting to the contract, from a CLI, a server, or a frontend, does so by address: ``` import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; const found = await findDeployedContract(providers, { contractAddress, compiledContract: compiled, privateStateId: 'bboardPrivateState', initialPrivateState: { secretKey }, }); ``` 4. Call circuits through `callTx`. Each call builds, proves, balances, and submits a transaction, resolving with its identifiers: ``` const call = await found.callTx.post('Hello from the network!'); // call.public.txId, call.public.blockHeight ``` ### Verification[​](#verification-1 "Direct link to Verification") A real deploy to the local network returns an address, the reconnected contract accepts a circuit call, and the indexer serves the resulting state: docs-tests/deploy.test.ts ``` import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { deployContract, findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import { Contract, State, ledger } from '../managed-bboard/contract/index.js'; import { StandaloneConfig } from '../src/config.js'; import { buildWalletFromHexSeed, registerNightForDust, closeWallet, type WalletContext } from '../src/wallet.js'; const BBOARD = new URL('../managed-bboard', import.meta.url).pathname; const GENESIS_SEED = '0'.repeat(63) + '1'; const secretKey = new Uint8Array(32); const witnesses = { localSecretKey: ({ privateState }: any) => [privateState, privateState.secretKey], }; describe('deploying a contract', () => { const config = new StandaloneConfig(); let ctx: WalletContext; let providers: any; let compiled: any; let contractAddress: string; beforeAll(async () => { ctx = await buildWalletFromHexSeed(config, GENESIS_SEED); await registerNightForDust(ctx); const zkConfigProvider = new NodeZkConfigProvider<'post' | 'takeDown'>(BBOARD); const walletAndMidnightProvider = { getCoinPublicKey: () => ctx.shieldedSecretKeys.coinPublicKey, getEncryptionPublicKey: () => ctx.shieldedSecretKeys.encryptionPublicKey, balanceTx: async (tx: any, ttl: Date = ttlOneHour()) => { const recipe = await ctx.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: ctx.shieldedSecretKeys, dustSecretKey: ctx.dustSecretKey }, { ttl }, ); return await ctx.wallet.finalizeRecipe(recipe); }, submitTx: (tx: any) => ctx.wallet.submitTransaction(tx), }; providers = { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: 'docs-bboard-private-state', signingKeyStoreName: 'docs-bboard-signing-keys', privateStoragePasswordProvider: () => 'Docs-Verify-2026', accountId: ctx.unshieldedKeystore.getBech32Address().asString(), }), publicDataProvider: indexerPublicDataProvider(config.indexer, config.indexerWS), zkConfigProvider, proofProvider: httpClientProofProvider(config.proofServer, zkConfigProvider), walletProvider: walletAndMidnightProvider, midnightProvider: walletAndMidnightProvider, }; compiled = CompiledContract.withCompiledFileAssets( CompiledContract.withWitnesses(CompiledContract.make('bboard', Contract), witnesses), BBOARD, ); }); afterAll(async () => { await closeWallet(ctx); }); it('deploys and returns the contract address', async () => { const deployed = await deployContract(providers, { compiledContract: compiled, privateStateId: 'bboardPrivateState', initialPrivateState: { secretKey }, }); contractAddress = deployed.deployTxData.public.contractAddress; expect(contractAddress).toMatch(/^[0-9a-f]{64,}$/); }); it('reconnects with findDeployedContract and calls a circuit', async () => { const found = await findDeployedContract(providers, { contractAddress, compiledContract: compiled, privateStateId: 'bboardPrivateState', initialPrivateState: { secretKey }, }); const call = await found.callTx.post('Deployed from the guide verification'); expect(call.public.txId).toBeDefined(); expect(call.public.blockHeight).toBeGreaterThan(0); }); it('reads the deployed state through the indexer', async () => { const state = await providers.publicDataProvider.queryContractState(contractAddress); const board = ledger(state.data); expect(board.state).toBe(State.OCCUPIED); expect(board.message.value).toBe('Deployed from the guide verification'); }); }); ``` ``` ✓ docs-tests/deploy.test.ts > deploying a contract > deploys and returns the contract address 20427ms ✓ docs-tests/deploy.test.ts > deploying a contract > reconnects with findDeployedContract and calls a circuit 18675ms ✓ docs-tests/deploy.test.ts > deploying a contract > reads the deployed state through the indexer 8ms Test Files 1 passed (1) Tests 3 passed (3) ``` ## Promoting a deployment to Preprod[​](#promoting-a-deployment-to-preprod "Direct link to Promoting a deployment to Preprod") Promote the deploy you ran in [Deploying a contract](#deploying-a-contract) to Preprod, the public testnet where your contract is visible to other developers and explorers. The code does not change; only the configuration does. If you started from the [hello world tutorial](/getting-started/hello-world.md) instead, its repository packages this whole flow as `yarn test:preprod`, with the same steps behind the script. ### Prerequisites[​](#prerequisites-2 "Direct link to Prerequisites") * A deploy working against the local network, from [Deploying a contract](#deploying-a-contract). ### Procedure[​](#procedure-2 "Direct link to Procedure") 1. Fund a Preprod wallet: request tNIGHT from the faucet, then register it for DUST generation, following [Funding a wallet](/guides/acquire-tokens.md). Without DUST, submission fails with `Wallet.InsufficientFunds`. 2. Keep the wallet secret out of your source. Load the seed or mnemonic from an environment file that your version control ignores: ``` # .env.preprod (listed in .gitignore; never commit or share it) MIDNIGHT_PREPROD_SEED=... # 64 hex characters, or a 24-word mnemonic variable ``` 3. Point the configuration at Preprod: `setNetworkId('preprod')`, the Preprod indexer and node endpoints from the [environment reference](/guides/networks-and-environments.md#environment-reference), and a proof server you run yourself, following [Run a proof server](/guides/run-proof-server.md). The proof server sees witness data in the clear, so it stays local even when the network is public. 4. Run the same deploy code from [Deploying a contract](#deploying-a-contract) against the new configuration. The first sync of a fresh Preprod wallet walks the chain's history and takes substantially longer than the local network's. ### Verification[​](#verification-2 "Direct link to Verification") Look up the printed contract address on a Preprod explorer, such as [midnightexplorer.com](https://preprod.midnightexplorer.com/) or [subscan.io](https://midnight-preprod.subscan.io/). The explorer shows the deploy transaction and each subsequent call transaction at that address. ## Observing contract and chain state[​](#observing-contract-and-chain-state "Direct link to Observing contract and chain state") Watch what your deployed contract does from the outside: read its public state through the indexer, and follow blocks and events at the node when you need the chain-level view. ### Procedure[​](#procedure-3 "Direct link to Procedure") 1. Read contract state through the public data provider and decode it with the generated `ledger()` function. Pass the state's `data` field; the surrounding `ContractState` itself is not accepted: ``` const state = await providers.publicDataProvider.queryContractState(contractAddress); const board = ledger(state.data); // board.state, board.message.value, board.sequence: typed getters, no manual decoding ``` 2. For the chain-level view, connect to the node's RPC endpoint with [`@polkadot/api`](https://polkadot.js.org/docs/api/), which speaks to any Substrate-based chain, including Midnight: ``` import { ApiPromise, WsProvider } from '@polkadot/api'; const api = await ApiPromise.create({ provider: new WsProvider('ws://127.0.0.1:9944'), }); ``` 3. Subscribe to new blocks. The callback fires once per block with its header: ``` api.rpc.chain.subscribeNewHeads((lastHeader) => { console.log(`\nBlock #${lastHeader.number} has been added`); }); ``` 4. Extract transactions and events from a block. On Substrate chains a transaction is an extrinsic: data arriving from outside the chain asking it to act, whether signed by a user, unsigned, or inherent system data such as the block timestamp: ``` const blockHash = await api.rpc.chain.getBlockHash(blockNumber); const signedBlock = await api.rpc.chain.getBlock(blockHash); signedBlock.block.extrinsics.forEach((extrinsic, index) => { console.log(`\nExtrinsic ${index}: ${extrinsic.method.section}.${extrinsic.method.method}`); }); const apiAt = await api.at(blockHash); const events = await apiAt.query.system.events(); events.forEach(({ event, phase }) => { console.log(`\nEvent: ${event.section}.${event.method}, phase: ${phase.toString()}`); console.log(`Data: ${event.data.toString()}`); }); ``` ### Verification[​](#verification-3 "Direct link to Verification") A live node delivers block headers to the subscription, and a block gives up its extrinsics and events: docs-tests/observe-chain.test.ts ``` import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { ApiPromise, WsProvider } from '@polkadot/api'; describe('observing the chain', () => { let api: ApiPromise; beforeAll(async () => { api = await ApiPromise.create({ provider: new WsProvider('ws://127.0.0.1:9944'), noInitWarn: true, }); }); afterAll(async () => { await api.disconnect(); }); it('delivers new block headers to a subscription', async () => { const header = await new Promise((resolve) => { const unsubscribe = api.rpc.chain.subscribeNewHeads((lastHeader) => { unsubscribe.then((stop) => stop()); resolve(lastHeader); }); }); expect(header.number.toNumber()).toBeGreaterThan(0); }); it('extracts extrinsics and events from a block', async () => { const header = await api.rpc.chain.getHeader(); const blockHash = await api.rpc.chain.getBlockHash(header.number.toNumber()); const signedBlock = await api.rpc.chain.getBlock(blockHash); expect(signedBlock.block.extrinsics.length).toBeGreaterThan(0); const apiAt = await api.at(blockHash); const events = await apiAt.query.system.events(); expect(events.length).toBeGreaterThan(0); expect(events[0].event.section).toBeDefined(); }); }); ``` ``` ✓ docs-tests/observe-chain.test.ts > observing the chain > delivers new block headers to a subscription 50ms ✓ docs-tests/observe-chain.test.ts > observing the chain > extracts extrinsics and events from a block 58ms Test Files 1 passed (1) Tests 2 passed (2) ``` ## Contract updatability and the maintenance authority[​](#contract-updatability-and-the-maintenance-authority "Direct link to Contract updatability and the maintenance authority") A deployed contract's circuits are bound to the proof system that compiled them. As Midnight's proving stack evolves, proving schemes, the circuit intermediate representation, or verifier key formats can change, and a circuit deployed under the old rules can reach a point where its proofs can no longer be generated or verified. Updatability is how a contract survives that, and it is a decision you make at deployment, not after. The mechanism is verifier key management. Each circuit is represented on-chain by a verifier key per proof system version, and a contract's designated authority can change them after deployment. That authority is the contract maintenance authority, a committee of public keys with a signature threshold, and it can do exactly three things: * **Insert a verifier key** for a circuit at a proof system version, restoring or adding functionality. A key must not already exist at that version; remove the old one first. * **Remove a verifier key**, after which the network rejects transactions using that circuit at that version. * **Replace the authority itself**, transferring control to a new committee, or relinquishing control entirely by setting an empty one. At the ledger level, a contract deployed with no authority configured is permanently non-upgradable: the default is an empty committee with a threshold of one, a condition no signature set can satisfy. Deploying through Midnight.js changes that picture: `deployContract` installs a single-signature authority for you, sampling a fresh signing key and storing it in your private state provider unless you supply your own. Whichever path you take, decide deliberately. A contract holding long-term state that cannot practically migrate, such as vesting schedules or an identity registry, needs a maintained authority; a contract meant to be immutable needs the authority relinquished so no key can ever change it. Whoever holds the authority's keys can rewrite what the contract accepts, so custody is a security decision: distribute control across independent parties and follow the [key custody guidance](/guides/security-best-practices.md#rotating-an-owner-key) in the security guide. Track proof system changes through the [support matrix](/relnotes/support-matrix.md) and plan circuit updates before an incompatibility arrives; where you relinquished updatability, plan contract migration instead. ## Operating a maintenance authority[​](#operating-a-maintenance-authority "Direct link to Operating a maintenance authority") Exercise the three maintenance operations against a deployed contract: disable a circuit by removing its verifier key, re-enable it by inserting one, and hand control to a new authority. ### Prerequisites[​](#prerequisites-3 "Direct link to Prerequisites") * A deployed contract and its providers, from [Deploying a contract](#deploying-a-contract). * The maintenance authority's signing key, held by your private state provider or supplied at deploy time. ### Procedure[​](#procedure-4 "Direct link to Procedure") 1. To control the authority explicitly, generate a signing key and pass it at deploy time. Reusing one key across deployments gives several contracts the same authority: ``` import { sampleSigningKey } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; const signingKey = sampleSigningKey(); const deployed = await deployContract(providers, { compiledContract: compiled, privateStateId: 'bboardPrivateState', initialPrivateState: { secretKey }, signingKey, }); ``` 2. Remove a circuit's verifier key through the per-circuit maintenance interface. Both [`DeployedContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/DeployedContract.md) and [`FoundContract`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/FoundContract.md) expose `circuitMaintenanceTx`, with one [`CircuitMaintenanceTxInterface`](/api-reference/midnight-js/@midnight-ntwrk/midnight-js-contracts/type-aliases/CircuitMaintenanceTxInterface.md) per circuit. Once the transaction lands, the network rejects calls to that circuit: ``` await deployed.circuitMaintenanceTx.takeDown.removeVerifierKey(); ``` 3. Insert a verifier key to re-enable the circuit. The ZK config provider reads it from the compile output; after a compiler upgrade, this is how the freshly compiled key replaces the stranded one: ``` const verifierKey = await zkConfigProvider.getVerifierKey('takeDown'); await deployed.circuitMaintenanceTx.takeDown.insertVerifierKey(verifierKey); ``` 4. Replace the authority when control should move, passing the new committee's signing key: ``` await deployed.contractMaintenanceTx.replaceAuthority(sampleSigningKey()); ``` ### Verification[​](#verification-4 "Direct link to Verification") Removing the verifier key makes the network reject the circuit, inserting it restores the circuit, and the authority transfer succeeds, all against a real deployment: docs-tests/maintenance.test.ts ``` import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { deployContract } from '@midnight-ntwrk/midnight-js-contracts'; import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import { sampleSigningKey } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import { Contract } from '../managed-bboard/contract/index.js'; import { StandaloneConfig } from '../src/config.js'; import { buildWalletFromHexSeed, registerNightForDust, closeWallet, type WalletContext } from '../src/wallet.js'; const BBOARD = new URL('../managed-bboard', import.meta.url).pathname; const GENESIS_SEED = '0'.repeat(63) + '1'; const secretKey = new Uint8Array(32); const witnesses = { localSecretKey: ({ privateState }: any) => [privateState, privateState.secretKey], }; describe('operating a maintenance authority', () => { const config = new StandaloneConfig(); let ctx: WalletContext; let deployed: any; beforeAll(async () => { ctx = await buildWalletFromHexSeed(config, GENESIS_SEED); await registerNightForDust(ctx); const zkConfigProvider = new NodeZkConfigProvider<'post' | 'takeDown'>(BBOARD); const walletAndMidnightProvider = { getCoinPublicKey: () => ctx.shieldedSecretKeys.coinPublicKey, getEncryptionPublicKey: () => ctx.shieldedSecretKeys.encryptionPublicKey, balanceTx: async (tx: any, ttl: Date = ttlOneHour()) => { const recipe = await ctx.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: ctx.shieldedSecretKeys, dustSecretKey: ctx.dustSecretKey }, { ttl }, ); return await ctx.wallet.finalizeRecipe(recipe); }, submitTx: (tx: any) => ctx.wallet.submitTransaction(tx), }; const providers = { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: 'docs-bboard-private-state', signingKeyStoreName: 'docs-bboard-signing-keys', privateStoragePasswordProvider: () => 'Docs-Verify-2026', accountId: ctx.unshieldedKeystore.getBech32Address().asString(), }), publicDataProvider: indexerPublicDataProvider(config.indexer, config.indexerWS), zkConfigProvider, proofProvider: httpClientProofProvider(config.proofServer, zkConfigProvider), walletProvider: walletAndMidnightProvider, midnightProvider: walletAndMidnightProvider, }; const compiled = CompiledContract.withCompiledFileAssets( CompiledContract.withWitnesses(CompiledContract.make('bboard', Contract), witnesses), BBOARD, ); deployed = await deployContract(providers, { compiledContract: compiled, privateStateId: 'bboardPrivateState', initialPrivateState: { secretKey }, signingKey: sampleSigningKey(), }); await deployed.callTx.post('Maintenance drill'); }); afterAll(async () => { await closeWallet(ctx); }); it('removing a verifier key disables the circuit on-chain', async () => { await deployed.circuitMaintenanceTx.takeDown.removeVerifierKey(); await expect(deployed.callTx.takeDown()).rejects.toThrow( "Operation 'takeDown' is undefined", ); }); it('inserting the verifier key re-enables the circuit', async () => { const zkConfigProvider = new NodeZkConfigProvider<'post' | 'takeDown'>(BBOARD); const verifierKey = await zkConfigProvider.getVerifierKey('takeDown'); await deployed.circuitMaintenanceTx.takeDown.insertVerifierKey(verifierKey); const call = await deployed.callTx.takeDown(); expect(call.public.txId).toBeDefined(); }); it('replaces the contract maintenance authority', async () => { await expect( deployed.contractMaintenanceTx.replaceAuthority(sampleSigningKey()), ).resolves.not.toThrow(); }); }); ``` ``` ✓ docs-tests/maintenance.test.ts > operating a maintenance authority > removing a verifier key disables the circuit on-chain 17403ms ✓ docs-tests/maintenance.test.ts > operating a maintenance authority > inserting the verifier key re-enables the circuit 36159ms ✓ docs-tests/maintenance.test.ts > operating a maintenance authority > replaces the contract maintenance authority 18699ms Test Files 1 passed (1) Tests 3 passed (3) ``` ## Provider implementations[​](#provider-implementations "Direct link to Provider implementations") Which implementation fills each provider slot, by environment. Packages live under the `@midnight-ntwrk/` scope at the versions the [support matrix](/relnotes/support-matrix.md) lists. | Slot | Implementation | Package | Notes | | ------------------------------------ | ------------------------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `privateStateProvider` | `levelPrivateStateProvider` | `midnight-js-level-private-state-provider` | Encrypted LevelDB on the local device. Requires `accountId`; password needs 16 or more characters and three of four character classes | | `publicDataProvider` | `indexerPublicDataProvider` | `midnight-js-indexer-public-data-provider` | Takes the indexer HTTP and WebSocket URLs. Queries run in Node.js and browsers; for browser subscriptions, pass the native `WebSocket` as its third argument | | `zkConfigProvider` | `NodeZkConfigProvider` | `midnight-js-node-zk-config-provider` | Reads `keys/` and `zkir/` from the local filesystem | | `zkConfigProvider` | `FetchZkConfigProvider` | `midnight-js-fetch-zk-config-provider` | Fetches the same artifacts over HTTP, for browsers and hosted setups | | `proofProvider` | `httpClientProofProvider` | `midnight-js-http-client-proof-provider` | Takes the proof server URL and the `zkConfigProvider` | | `walletProvider`, `midnightProvider` | your class over `WalletFacade` | `wallet-sdk` | One instance can fill both slots, as in [Configuring providers for a contract](#configuring-providers-for-a-contract) | ## Deployment troubleshooting[​](#deployment-troubleshooting "Direct link to Deployment troubleshooting") Failures you are likely to hit on this guide's path, and their fixes. Every quoted message comes from a real run. | Error | Cause | Fix | | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `accountId is required. Provide an account identifier` | `levelPrivateStateProvider` called without `accountId` | Pass a per-account identifier, such as the wallet's Bech32m address | | `PasswordValidationError: Password must contain at least 3 of: uppercase letters, lowercase letters, digits, special characters` | The private-state encryption password is too weak | Provide a password with at least three of the four character classes | | `Password is shorter than 16 characters` | The private-state encryption password fails the length rule | Use 16 characters or more | | `Wallet.InsufficientFunds` | The wallet has NIGHT but no spendable DUST | Register NIGHT for DUST generation and wait for a spendable coin; see [Funding a wallet](/guides/acquire-tokens.md) | | tsc: `Types have separate declarations of a private property 'type_'` | Ledger types imported from the ledger package directly, clashing with the copies Midnight.js compiles against | Import `ZswapSecretKeys`, `DustSecretKey`, and transaction types from `@midnight-ntwrk/midnight-js-protocol/ledger` | | `expected instance of ContractMaintenanceAuthority` (or another `expected instance of` error at deploy) | The generated contract module and Midnight.js resolve different copies of the runtime, so class checks fail across the trees | Keep the contract's `managed` output and Midnight.js in the same package tree with one `node_modules` | | `Operation 'takeDown' is undefined for contract state` | The circuit's verifier key was removed, or none exists at the current proof system version | Insert a verifier key for the circuit; see [Operating a maintenance authority](#operating-a-maintenance-authority) | | `expected instance of ChargedState` | `ledger()` was passed the whole `ContractState` from the indexer | Pass its `data` field: `ledger(state.data)` | | Indexer exits on first start of a fresh local chain | Startup race documented with the local stack | See [Local network troubleshooting](/guides/networks-and-environments.md#local-network-troubleshooting) | ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Using Compact contracts from JavaScript](/guides/compact-javascript-runtime.md): the generated module, witnesses, and the off-chain test suite that proves contract logic before you spend DUST on it. * [Funding a wallet](/guides/acquire-tokens.md): faucet tNIGHT and DUST registration, in Lace and with the wallet SDK. * [Networks and environments](/guides/networks-and-environments.md): the local stack, every endpoint, and the mainnet readiness checklist. * [Security and best practices](/guides/security-best-practices.md): the pre-deployment checklist, including upgrade-key custody. * [Midnight.js API reference](/api-reference/midnight-js.md): `deployContract`, `findDeployedContract`, and the provider interfaces in full. * [Support matrix](/relnotes/support-matrix.md): which compiler, runtime, and SDK versions pair. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Sponsor transaction fees with DUST DUST sponsorship lets one wallet pay transaction fees on behalf of another. The user authorizes the action, the sponsor pays the DUST fee, and the two roles never mix. The result is a gasless experience, a user with zero DUST can transact from their first click. What this page assumes You know that Midnight transactions cost [DUST](/concepts/dust-architecture.md), that DUST generates from NIGHT registered for DUST generation, and that circuits run on the user's device. All code on this page comes from the reference implementation in [example-private-party](https://github.com/midnightntwrk/example-private-party), summarized in its [SPONSORSHIP.md](https://github.com/midnightntwrk/example-private-party/blob/main/docs/SPONSORSHIP.md). Check the [support matrix](/relnotes/support-matrix.md) for tested component versions. ## The problem sponsorship solves[​](#the-problem-sponsorship-solves "Direct link to The problem sponsorship solves") A new user installs a wallet, opens your DApp, and clicks a button. Nothing happens, transactions cost DUST, DUST comes from holding registered NIGHT over time, and a brand-new user has neither. Sponsorship removes that wall for onboarding flows, free tiers, and enterprise deployments where the organization covers usage. ## The principle: who pays is not who is authorized[​](#the-principle-who-pays-is-not-who-is-authorized "Direct link to The principle: who pays is not who is authorized") | Role | Holds | Can do | Cannot do | | ------- | ------------------------------------ | ------------------------------- | ------------------------------------------------------------------------- | | User | The contract secret, zero DUST | Prove and authorize the action | Pay the fee | | Sponsor | NIGHT registered for DUST generation | Add a DUST fee offer and submit | Act as the user, alter the sealed transaction, or reach the user's secret | Three mechanisms enforce the separation: 1. **The smart contract authenticates by secret, not by fee payer.** In the reference example, the `checkIn` circuit requires `commitAddress(_secret, address.bytes)` to match the RSVP on the ledger. Only a caller who knows the secret can produce a valid proof, so the sponsor's money buys nothing but the fee. 2. **The user binds the transaction first.** The user proves, balances its own side, signs, and finalizes before the handoff. What crosses the wire is a bound `FinalizedTransaction` the sponsor can add a DUST fee offer to, and nothing else. 3. **The network rejects modified transactions.** A cryptographic binding ties the contract call to the transaction. Change anything after finalization, and verification fails. Never authenticate with ownPublicKey() `ownPublicKey()` is a witness: the prover's machine chooses its return value, and the protocol never checks it against the signing wallet. Any check built on it is bypassable, by the sponsor or by anyone else. Authorization must come from proving knowledge of a secret, as the reference contract does. Use `ownPublicKey()` only to route tokens to the caller. ## The flow[​](#the-flow "Direct link to The flow") The split is enforced by one option, `tokenKindsToBalance`: the user balances `['shielded', 'unshielded']` to cover the transaction's value, and the sponsor balances `['dust']` to cover its fee. The user is always the prover, so the secret that authenticates the caller never reaches the sponsor. ## The user side: prove, balance, bind[​](#the-user-side-prove-balance-bind "Direct link to The user side: prove, balance, bind") From `src/sponsor.ts` in the reference implementation. The hex string this returns is the network boundary: in production this function runs where the user's keys live, such as a browser wallet. src/sponsor.ts (user side) ``` export async function prepareSponsoredCall< C extends Contract.Any, PCK extends Contract.ProvableCircuitId, >( logger: Logger, user: MidnightWalletProvider, providers: PartyProviders, call: CallTxOptionsWithPrivateStateId, ): Promise { const unsubmitted = await createUnprovenCallTx(providers, call); // Proving happens here, on the user's side — which is why the secret that // authenticates the caller never reaches the sponsor. const unboundTx = await providers.proofProvider.proveTx(unsubmitted.private.unprovenTx); // Balance only the user's own value side (no DUST), sign, and bind. const finalized = await user.balanceOwnValueAndFinalize(unboundTx); return toHex(finalized.serialize()); } ``` Note what is not here, no DUST, no fee estimation, no sponsor keys. A wallet with zero DUST can run every line. Inside `balanceOwnValueAndFinalize`, the wallet calls `balanceUnboundTransaction` with `tokenKindsToBalance: ['shielded', 'unshielded']`, then `signRecipe`, then `finalizeRecipe`. ## The sponsor side: pay the fee, submit[​](#the-sponsor-side-pay-the-fee-submit "Direct link to The sponsor side: pay the fee, submit") Typically a small backend service. It can apply acceptance policy, such as rate limits and allowlists, before spending anything. src/sponsor.ts (sponsor side) ``` export async function sponsorAndSubmit( logger: Logger, sponsor: MidnightWalletProvider, userTxHex: string, ): Promise { // The marker triple matches FinalizedTransaction = Transaction. const userTx = Transaction.deserialize( 'signature', 'proof', 'binding', fromHex(userTxHex), ); // Attach a DUST fee offer paid by the sponsor, then submit. const sponsored = await sponsor.addDustFeesAndFinalize(userTx); const txId = await sponsor.wallet.submitTransaction(sponsored); return txId; } ``` Inside `addDustFeesAndFinalize`, the wallet calls `balanceFinalizedTransaction` with `tokenKindsToBalance: ['dust']`, then `signRecipe`, then `finalizeRecipe`. The sponsor is a payer, never an author. ## Why the order is important[​](#why-the-order-is-important "Direct link to Why the order is important") The user proves, balances, signs, and finalizes **first**. Because the sponsor receives an already-bound transaction, the guarantees fall out of the mechanism itself: | Guarantee | Why it holds | | ----------------------------------------- | --------------------------------------------------------------------------------------- | | The sponsor cannot alter the call | The transaction is bound before handoff; the network rejects modifications | | The sponsor cannot reach the secret | The user generated the proof; only the proof travels | | The sponsor cannot act as the user | The contract authenticates by secret, which the sponsor does not hold | | The user cannot spend the sponsor's funds | The sponsor balances only `['dust']`, signs its own additions, and applies policy first | | DUST cannot be extracted from the sponsor | DUST is not transferable; it can only be spent on fees the sponsor approves | Follow this exact ordering If the user hands over an unbalanced or unsigned transaction, the receiving side could reshape it. Balance, sign, and finalize on the user's side before anything leaves the user's machine. ## Run the reference example[​](#run-the-reference-example "Direct link to Run the reference example") The implementation ships in [example-private-party](https://github.com/midnightntwrk/example-private-party), where a zero-DUST guest checks in to a party while a sponsor pays the fee. ``` yarn env:up # start the local environment yarn wait:dust # wait until the sponsor wallet has generated DUST yarn test:sponsorship # run the sponsored flow, including the negative cases yarn sponsor:serve # or run the sponsor as an HTTP service ``` | File | What it contains | | ------------------------------ | ------------------------------------------------------------------------------------------------------------ | | `src/sponsor.ts` | `prepareSponsoredCall` (user side) and `sponsorAndSubmit` (sponsor side) | | `src/wallet.ts` | The role-specific balancing methods described above | | `src/test/sponsorship.test.ts` | Security validation: the sponsored happy path, plus proof that the payer cannot act and the actor cannot pay | | `scripts/sponsor-service.ts` | The sponsor as a small HTTP service | To adopt the pattern, swap in your own smart contract. Your contract supplies the authorization rule; the two functions and their ordering stay the same. ## Reference[​](#reference "Direct link to Reference") **Token units:** | Resource | Atomic unit | Ratio | | -------- | ----------- | -------------------- | | NIGHT | STAR | 1 NIGHT = 10^6 STAR | | DUST | SPECK | 1 DUST = 10^15 SPECK | **DUST facts that shape sponsor economics:** DUST is not transferable and only pays fees. It generates from registered NIGHT toward a cap, roughly 5 DUST per NIGHT under initial parameters, and decays when the backing NIGHT is spent. Fees for the whole transaction are collected in the guaranteed phase, so a fallible-phase failure still consumes the fee. Smart contracts do not hold or spend DUST in the current protocol; sponsorship is a wallet-side mechanism. **Errors you may meet** (submission failures surface as `1010: Invalid Transaction: Custom error: N`): | Code | Name | Fix | | ----- | ------------------------------------ | ------------------------------------------------------------------------------------ | | `170` | `InvalidDustSpendProof` | Regenerate the DUST spend proof through the proof server | | `173` | `InsufficientDustForRegistrationFee` | Wait for generation before registering; see `waitForGeneratedDust` in the wallet SDK | | `196` | `DustDoubleSpend` | Stale wallet view reused spent DUST; resync the sponsor wallet and rebuild | ## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions") **Does registering NIGHT for DUST generation transfer or spend the NIGHT?** No. Registration designates UTXOs for generation; the NIGHT stays in the wallet and remains spendable, although spending it stops generation. **Can the sponsor perform the action it is paying for?** No. Proving the circuit requires a secret the sponsor does not hold, so proof generation fails on the sponsor's machine before any fee is involved. **Can a user drain the sponsor?** No. The sponsor balances only `['dust']`, signs its own additions, and can reject requests by policy before spending. DUST itself cannot be transferred out. **Can a smart contract hold DUST and sponsor fees itself?** No. DUST spends preserve the owner's public key, and DUST wallets are wallet-side constructs. Sponsorship runs through a sponsor wallet or service. ## Next steps[​](#next-steps "Direct link to Next steps") * Clone [example-private-party](https://github.com/midnightntwrk/example-private-party) and run `yarn test:sponsorship`. * Read the repository's [SPONSORSHIP.md](https://github.com/midnightntwrk/example-private-party/blob/main/docs/SPONSORSHIP.md) technical summary. * Review [how transaction fees work](/concepts/how-midnight-works/semantics.md) for the guaranteed and fallible phase model behind fee collection. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Index contract state with EffectStream Use this guide to build an indexer for a Midnight contract. An indexer watches the contract's public state, keeps its own records, and answers questions the chain does not. The procedures target the `preview` network and a contract you need not deploy, so the whole guide runs with no local stack. Reading one chain is the smallest thing [EffectStream](https://effectstream.github.io/docs/) does; [Additional resources](#additional-resources) points to the cross-chain path. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * [Bun](https://bun.sh). EffectStream runs TypeScript directly and uses Bun as its package manager. See [Set up Bun for Midnight development](/guides/install-bun-runtime-midnight). * Network access to the hosted `preview` indexer listed in the [environment reference](/guides/networks-and-environments.md#environment-reference). * `curl`, or any HTTP client, for the verification steps. These procedures read from a hosted indexer over HTTPS, so they need no Docker, no Midnight node, no proof server, and no Compact Toolchain. The compatibility matrix does not cover EffectStream The EffectStream packages depend on no `@midnight-ntwrk/*` package, so the [support matrix](/relnotes/support-matrix.md) governs the contract half of a project and not this half. ## Why a DApp needs an indexer[​](#why-a-dapp-needs-an-indexer "Direct link to Why a DApp needs an indexer") A Midnight contract stores its current public state and nothing else. Who holds the top score? What changed in the last hour? The chain answers neither. It keeps no history you can query, and it computes no totals. An indexer answers them. It watches state changes, applies a function you write to each one, and stores the result in a database you control. It handles changes in chain order, so replaying the same history rebuilds the same database. Midnight already runs an indexer, and this guide connects to it rather than replacing it. The Midnight indexer reports what the chain holds, and your DApp reaches it through the `publicDataProvider` in [Deploying and operating a contract](/guides/deploy-and-operate.md#the-transaction-pipeline-and-its-providers). EffectStream reads from that indexer and builds your own derived state on top. Reading the ledger has two consequences. A change reaches your code only after several blocks of confirmation, so a chain reorganization cannot leave your database holding state the chain later drops. And your code sees exactly what the contract discloses, which makes [What the ledger schema can read](#what-the-ledger-schema-can-read) a contract decision. ## Run the indexer[​](#run-the-indexer "Direct link to Run the indexer") Build and run a node that watches a Midnight contract and prints each state change. The contract used here is a counter already running on `preview`, so you deploy nothing. ### Procedure[​](#procedure "Direct link to Procedure") 1. Create an empty project directory, then add a `package.json` with the single dependency an EffectStream node needs. Pin the version here rather than in the import statement: package.json ``` { "name": "midnight-indexer", "private": true, "scripts": { "start": "bun index.ts" }, "dependencies": { "@effectstream/node-sdk": "0.104.0" } } ``` 2. Install with Bun. Run a real install rather than relying on the auto-install cache: the SDK reaches packages that import themselves by name, and resolving those imports needs a `node_modules` directory the cache never creates: ``` bun install ``` 3. Create `index.ts` alongside `package.json`. A single `runNode` call describes the whole node, taking a name, a database, the sources to watch, and one transition function per source: index.ts ``` import { midnightContract, pglite, runNode } from "@effectstream/node-sdk"; await runNode({ appName: "midnight-indexer", database: pglite(), sources: { counter: midnightContract({ network: "preview", address: "c1a9ec7c4d2566f59456fd915a0438bf4dc9b8671d4c2308d30af796c51ad20f", startBlockHeight: "latest", ledger: { round: "uint128" }, }), }, transitions: { counter: ({ state, blockHeight }) => { console.log(`round ${state.round} at block ${blockHeight}`); }, }, }); ``` `pglite()` gives the node an embedded PostgreSQL-compatible database, held in memory unless you pass a `dataDir`. The `sources` key, `counter` here, is yours to choose, and `transitions` reuses it so the two stay paired. Setting `network` selects the hosted indexer, and `address` takes the contract's 64-character hex address with no `0x` prefix. [What the ledger schema can read](#what-the-ledger-schema-can-read) covers the `ledger` option, and whether it works for the contract you have in mind. 4. Start the node: ``` bun start ``` 5. Read the decoded state in the transition, which receives an object. Unsigned integers arrive as decimal strings, because a `uint128` does not fit in a JavaScript number, and byte fields and map keys arrive as `0x`-prefixed hex strings. Convert with `BigInt(state.round)` when you need arithmetic. Replay history to confirm the wiring A transition fires on state changes, not on blocks, so a quiet contract prints nothing. Set `startBlockHeight` to a low block number to replay past changes. ### Verification[​](#verification "Direct link to Verification") The node connects to preview and logs each block it fetches, like this: ``` [Midnight:preview] Fetching blocks from 456487 to 456487. 04:28:20 INFO effectstream-sync-block-merge: finalized block 20 @ undefined... | {"clock":[20,20]} 04:28:21 INFO effectstream-sync-block-merge: finalized block 21 @ undefined... | {"clock":[21,21],"midnight-counter":[456486,456486]} ``` A `round N at block M` line appears whenever the contract's state changes. A contract nobody is calling produces no such line, which is the case the tip above covers. ## What the ledger schema can read[​](#what-the-ledger-schema-can-read "Direct link to What the ledger schema can read") The `ledger` option declares how to decode public state, which is why a node needs no compiled contract artifacts. It also decides which contracts a node can read at all, so check it against your contract before you plan around it. EffectStream matches schema keys to ledger fields by position. The first key reads the first field, the second key reads the second, and so on until your schema runs out. A schema accepts these types: * `"uint8"` through `"uint128"`, decoded little-endian into decimal strings * `"bytes"`, decoded into a `0x`-prefixed hex string * `"boolean"` * `{ type: "map", value: }`, nesting arbitrarily, with keys as `0x` hex strings * `{ type: "option", value: }`, decoding to `null` when absent A `struct`, `Vector`, or `enum` fails at parse time. Because the match is positional, one unreadable field blocks every field after it. A struct sitting third in a ledger costs you the fourth field and the fifth as well. Some contracts need the compiler-generated decoder instead A schema cannot express structs, enums, or wrapped types, and Compact contracts use all three. When your contract's ledger holds one near the top, use EffectStream's full configuration API instead, which takes the decoder the Compact compiler generates and reads anything the language can express. See the [EffectStream documentation](https://effectstream.github.io/docs/home/chains/midnight). When you control the contract, you can design its ledger so a schema reads it. Put the fields an indexer needs at the top, and structs and digests at the bottom. Flatten a struct that needs indexing into sibling top-level declarations keyed the same way: a `Map, GameState>` holding four small numbers becomes four `Map, Uint<8>>` declarations, which costs nothing on-chain. ``` // An indexer reads these, in this order. export ledger status: Map, Uint<8>>; export ledger winner: Map, Uint<8>>; export ledger scores: Map, Map, Uint<8>>>; // Structs and digests go last. export ledger commitments: Map, GameKeys>; ``` The matching schema stops where the structs begin: ``` ledger: { status: { type: "map", value: "uint8" }, winner: { type: "map", value: "uint8" }, scores: { type: "map", value: { type: "map", value: "uint8" } }, } ``` Which fields go at the top is the question [Security and best practices](/guides/security-best-practices.md#on-chain-visibility) asks about `disclose()`: what should a public reader see? Identity commitments and Merkle roots serve in-circuit checks, so they belong at the bottom. ## Serve indexed state over HTTP[​](#serve-indexed-state-over-http "Direct link to Serve indexed state over HTTP") Expose what the node records so the rest of your application can read it. `runNode` hosts an HTTP server. ### Prerequisites[​](#prerequisites-1 "Direct link to Prerequisites") * A running node, from [Run the indexer](#run-the-indexer). ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. Replace `index.ts` with this version. It records the value in a variable instead of logging it, and adds an `api` function to serve it: index.ts ``` import { midnightContract, pglite, runNode } from "@effectstream/node-sdk"; let round = "waiting for the next contract update"; await runNode({ appName: "midnight-indexer", database: pglite(), sources: { counter: midnightContract({ network: "preview", address: "c1a9ec7c4d2566f59456fd915a0438bf4dc9b8671d4c2308d30af796c51ad20f", startBlockHeight: "latest", ledger: { round: "uint128" }, }), }, transitions: { counter: ({ state }) => { round = state.round; }, }, api: async (server) => { server.get("/round", async (_request, reply) => reply.send({ round })); }, }); ``` 2. Restart the node and request the endpoint. The server listens on port 9999 unless you set `apiPort` on `runNode`. Choose the database mode deliberately `pglite()` holds data in memory by default, so every run starts at the chain tip and misses whatever happened while the node was down. Passing `pglite({ dataDir: "./data" })` persists the database, and the node then resumes from the block height it recorded. ### Verification[​](#verification-1 "Direct link to Verification") The endpoint answers with the value the last transition recorded, or the starting value when no transition has fired yet: ``` curl http://localhost:9999/round ``` ``` {"round":"waiting for the next contract update"} ``` ## Indexer troubleshooting[​](#indexer-troubleshooting "Direct link to Indexer troubleshooting") Failures on this guide's path, and their fixes. | Symptom | Cause | Fix | | ------------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Install fails resolving a package that imports itself by name | Bun's auto-install cache created no `node_modules` anchor | Run `bun install` before `bun start` | | The first transition takes far longer than expected | EffectStream holds each change for several blocks of confirmation | Wait. The delay keeps the database consistent with settled state | | A comparison against a decoded number never matches | Unsigned integers decode to decimal strings, not numbers | Convert with `BigInt(state.field)` before comparing | | Parse error naming an array where a scalar belongs | A `struct`, `enum`, or `Vector` sits at a schema position | Use the compiler-generated decoder, or reorder the ledger if you control the contract; see [What the ledger schema can read](#what-the-ledger-schema-can-read) | ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [EffectStream documentation](https://effectstream.github.io/docs/): the full API surface, and the cross-chain templates that pair Midnight with an EVM chain, Bitcoin, or Cardano. * [Deploying and operating a contract](/guides/deploy-and-operate.md): the providers a DApp uses to reach the Midnight indexer directly, and how to deploy a contract of your own to index. * [Networks and environments](/guides/networks-and-environments.md): every endpoint, network ID, and the local stack. * [Security and best practices](/guides/security-best-practices.md): what a chain observer sees, and how `disclose()` decides it. * [Support matrix](/relnotes/support-matrix.md): the versions governing the contract half of a project. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Proving transactions locally Midnight uses zero-knowledge (ZK) cryptography to enable shielded transactions and data protection. An essential element of this architecture is ZK functionality provided by a Midnight *proof server*, which generates proofs locally that are verified on-chain. The information that a DApp sends to the proof server includes private data, such as details of token ownership or a DApp's private state. To protect your data, you should access only a local proof server, or perhaps one on a remote machine that you control, over an encrypted channel. This guide explains why proving happens on your machine and walks you through running the proof server, verifying it, connecting your DApp to it, choosing a network, and generating tDUST. For the wallet-user walkthrough of starting the container from Docker Desktop, see [Run the proof server](/guides/run-proof-server.md). ## Why Midnight needs Docker, the proof server and proof generation[​](#why-midnight-needs-docker-the-proof-server-and-proof-generation "Direct link to Why Midnight needs Docker, the proof server and proof generation") If you have tried to build on Midnight, you have probably hit this within the first ten minutes: ``` Error: connect ECONNREFUSED 127.0.0.1:6300 ``` Somewhere in the setup guide there was a `docker run` command. You skipped it, or Docker was not running, and now nothing works. The reasonable question at that point is, why does a blockchain SDK need Docker at all? This guide answers that by following the actual chain of reasoning, from what happens when you call a smart contract on Midnight, to why that requires a separate local service, to why that service ships as a container. It then gets you running, verified, and past the two things that most commonly go wrong next, choosing a network, and generating tDUST. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * [Docker Desktop](https://www.docker.com/products/docker-desktop/) installed and running * Node.js v22 or later * The Compact toolchain installed. See [install the Midnight toolchain](/getting-started/installation.md). ## Step 1: Your smart contract runs locally[​](#step-1-your-smart-contract-runs-locally "Direct link to Step 1: Your smart contract runs locally") On most chains, you submit a transaction and validators execute your smart contract. Everyone sees the inputs. On Midnight, execution happens on your device. When you call a *circuit*, Midnight's term for a smart contract function, it runs locally and produces two things: * A **public transcript**: the on-chain values it read and wrote, and the rules it followed. * A **private transcript**: your *witness* data, the secret inputs that never leave your machine. What reaches the network is the public transcript plus a ZK proof that the transcript is correct, meaning your hidden values satisfy every constraint in the circuit. The network learns that the rules were followed. It never learns your inputs. This is the core of Midnight's privacy model, and it is also why your local environment has a component other chains do not. ## Step 2: Proving is expensive, verifying is cheap[​](#step-2-proving-is-expensive-verifying-is-cheap "Direct link to Step 2: Proving is expensive, verifying is cheap") One asymmetry drives everything here. Verifying a proof is fast. Under Midnight's deployed cost model, proof verification costs a constant of roughly 3.3 milliseconds plus a small term that scales with size. That is what keeps on-chain verification affordable. Creating a proof is the expensive half. Midnight's proving system is PLONK-family with KZG commitments over the BLS12-381 curve. In practice this means proving requires a large set of shared public parameters, called a structured reference string, in addition to the proving key for your own circuit. That work does not belong in a browser tab, and reimplementing it in JavaScript is not practical. So the prover ships as a native service, the proof server. Its job description is short: * It accepts an unproven transaction plus the key material for the circuits involved: proving key, verifier key, and ZKIR. * It runs heavy math. * It returns proofs. What the proof server cannot do The proof server does not hold your wallet keys. It cannot sign a transaction and it cannot spend funds. It builds proofs, and that is the entire job. It does see your witness data, because that is what it proves things about. Which leads directly to the next point. ## Step 3: Why it runs on your machine[​](#step-3-why-it-runs-on-your-machine "Direct link to Step 3: Why it runs on your machine") Because the proof server receives your private inputs, using someone else's proof server means handing your secrets to a stranger. Run it locally, or at most on a remote machine you control, over an encrypted channel. Run locally, the data path is short. Your private data goes from your wallet, to a process on the same machine, and stops. The proof server reaches outward once, at startup, to download the public proving parameters from and prepare the built-in key material for shielded token and DUST operations. That data is public and identical for every user. Your witness data is never part of it. Offline and mirrored parameters Pass `--no-fetch-params` to skip the startup download, and set `MIDNIGHT_PARAM_SOURCE` to point at your own mirror. This also explains why the first start is much slower than every later one. The image itself is around 100 MB. The parameters it fetches on the first run are the slow part. ## Step 4: Why Docker specifically[​](#step-4-why-docker-specifically "Direct link to Step 4: Why Docker specifically") This is the question developers actually ask, so the alternatives deserve a straight answer. | Approach | Why it is not the default | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | npm install | The prover is compiled Rust with native cryptographic dependencies. Shipping it through npm means prebuilt binaries for every operating system and architecture, or asking every developer to install a Rust toolchain. | | Native binary download | Workable, but you inherit platform-specific linking, permissions, and PATH problems. You also lose the version pinning that matters when the node, indexer, and proof server have to stay compatible. | | In-browser WASM | Increasingly real. Some wallets now compile the prover to WASM and prove in the tab. It is not the path the tooling and tutorials assume, and cold-start key loading is its own tradeoff. | | Hosted proof server | Defeats the purpose. The proof server sees your witness data. | | Docker | One command, identical behavior across macOS, Linux, and WSL. Version-pinnable, so it stays in step with the node and indexer. Isolated, so it does not touch your system. Disposable, so a broken state is fixed by restarting a container. | Docker is not a stylistic preference. It is the lowest-friction way to distribute a native cryptographic service to developers across three operating systems while keeping versions aligned. ## Run the proof server[​](#run-the-proof-server "Direct link to Run the proof server") ``` docker run -p 6300:6300 midnightntwrk/proof-server:8.1.0 midnight-proof-server -v ``` Or run it with Docker Compose. Save the following as `proof-server.yml`: ``` services: proof-server: image: 'midnightntwrk/proof-server:8.1.0' command: ['midnight-proof-server', '-v'] ports: - '127.0.0.1:6300:6300' environment: RUST_BACKTRACE: 'full' healthcheck: test: ['CMD-SHELL', 'echo > /dev/tcp/127.0.0.1/6300'] interval: 10s timeout: 5s retries: 20 start_period: 10s ``` Start it with: ``` docker compose -f proof-server.yml up -d ``` You should see output similar to: ``` starting service: "actix-web-service-0.0.0.0:6300", workers: 12, listening on: 0.0.0.0:6300 ``` Leave it running. Every transaction you prove goes through it. Pin the version tag At the time of writing, 8.1.0 is the current stable tag. The `latest` tag exists but lags behind: it was last republished in May 2026, while 8.1.0 and the 9.0.0 release candidates came after. Pinning also keeps the proof server aligned with your node and indexer versions. Check the [compatibility matrix](/relnotes/support-matrix.md) for the version tested against your target network. ### A note on port 6300[​](#a-note-on-port-6300 "Direct link to A note on port 6300") The proof server has a `--port` flag and a `MIDNIGHT_PROOF_SERVER_PORT` environment variable, so the port is configurable. Leave it on 6300 anyway. Lace hardcodes `localhost:6300` for the Undeployed network, and the examples you are likely to copy assume it. If 6300 is genuinely occupied on your host, remap only the host side and update your DApp configuration to match: ``` docker run -p 6301:6300 midnightntwrk/proof-server:8.1.0 midnight-proof-server -v ``` ## Verify it is working[​](#verify-it-is-working "Direct link to Verify it is working") A running container does not guarantee a working proof server. Run these three checks: ``` curl http://localhost:6300/health # {"status":"ok","timestamp":"..."} curl http://localhost:6300/version # 8.1.0 curl http://localhost:6300/ready # {"status":"ok","jobsProcessing":0,"jobsPending":0,"jobCapacity":0,"timestamp":"..."} ``` `/ready` is the most useful during development. If `jobsPending` climbs while `jobsProcessing` stays flat, proving jobs are queuing. The server keeps a small pool of proving workers, two by default, adjustable with `--num-workers`. HTTP workers versus proving workers The `workers: 12` line in the startup log counts HTTP workers, scaled to your CPU count. It is not the number of proving workers. ## Connect your DApp[​](#connect-your-dapp "Direct link to Connect your DApp") The proof server is reached through a provider. ``` import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; const zkConfigProvider = new NodeZkConfigProvider<'myCircuit'>( '/path/to/contract/build', ); const proofProvider = httpClientProofProvider( 'http://localhost:6300', zkConfigProvider, ); ``` Two providers, two jobs. The `zkConfigProvider` serves the compiler artifacts, meaning the proving key, verifier key, and ZKIR for each circuit. The `proofProvider` carries them to the server alongside your transaction. Use `NodeZkConfigProvider` for artifacts on the filesystem, and `FetchZkConfigProvider` when they are hosted over HTTP. Both belong in your providers object: ``` const providers = { privateStateProvider, publicDataProvider, zkConfigProvider, proofProvider, walletProvider, midnightProvider, }; ``` If you are a wallet user rather than a builder, Lace points at the same place. Go to **Settings → Midnight → Local** and select `http://localhost:6300`. That is currently the only proving option Lace supports. ### Where proving sits in a transaction[​](#where-proving-sits-in-a-transaction "Direct link to Where proving sits in a transaction") 1. Execute the circuit locally, producing an unproven transaction. 2. Generate ZK proofs through the `proofProvider`. This is the proof server's step. 3. Balance the transaction through the `walletProvider`. 4. Submit to the network through the `midnightProvider`. 5. Wait for finalization through the `publicDataProvider`. Step 2 is the only step the proof server takes part in. If your DApp hangs, look there first. Keys and circuit out of sync The prover verifies its own proof before returning it. If your keys and circuit do not match, the error says check that your keys match rather than failing silently at submission. In practice this almost always means stale build artifacts. **Solution**: Recompile the smart contract. ## Choose a network[​](#choose-a-network "Direct link to Choose a network") Network selection is the second most common stumbling block, and the answer is simpler than it looks. | Network | Network ID | What it is | Use it when | | ---------- | ------------ | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | Undeployed | `undeployed` | A local stack you run yourself: node, indexer, and proof server | You are developing and iterating. Fastest loop, no faucet, no waiting. | | Preview | `preview` | Live test network, the primary development environment maintained by core engineering | You need to test against a real network with current features. | | Preprod | `preprod` | Live pre-production network for final testing before Mainnet | You are validating close-to-production behavior. | | Mainnet | `mainnet` | Production | You are shipping. | Start on Undeployed. tDUST generates in minutes rather than hours, there is no faucet queue, and you can reset the whole chain by restarting containers. Move to Preview or Preprod when you need to test against infrastructure you do not control. Whichever you choose, set it explicitly. **Undeployed:** ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('undeployed'); export const CONFIG = { indexer: 'http://localhost:8088/api/v4/graphql', indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', node: 'ws://localhost:9944', proofServer: 'http://localhost:6300', }; ``` **Preprod:** ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('preprod'); export const CONFIG = { indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preprod.midnight.network', proofServer: 'http://127.0.0.1:6300', }; ``` **Preview:** ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('preview'); export const CONFIG = { indexer: 'https://indexer.preview.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preview.midnight.network', proofServer: 'http://127.0.0.1:6300', }; ``` The `proofServer` value is a local address in every case. Proving is your machine's job regardless of which network you target. The local stack uses fixed ports: node on 9944, indexer on 8088, and proof server on 6300. These are exactly the defaults Lace hardcodes for Undeployed, so selecting **Undeployed** in Lace connects with no further configuration. ## Generate tDUST[​](#generate-tdust "Direct link to Generate tDUST") Once the proof server is running, the next wall is fees. Midnight transactions are paid for in DUST, and on test networks you use tDUST. DUST behaves unlike any gas token you have used before. You cannot transfer DUST and you cannot buy it. It is a resource generated by held NIGHT over time. The mechanism, briefly: * NIGHT and DUST use different keys, so a registration table links a NIGHT public key to a DUST address. This step is called *designation*. * A NIGHT UTXO generates DUST toward a cap proportional to the NIGHT it holds. Under the initial parameters that is 5 DUST per NIGHT, reaching the full cap in roughly a week. * Generation is linear from zero, so you have usable DUST long before the cap. Expect roughly 12 hours on a fresh wallet on a live network, and about 5 minutes on a local network. * Spend DUST and it regenerates. Spend the backing NIGHT and the DUST decays to zero. ### Why tDUST looks stuck at zero[​](#why-tdust-looks-stuck-at-zero "Direct link to Why tDUST looks stuck at zero") This is the most common report from newly created wallets, and it is usually not stuck. It never started. A DUST UTXO is created only when a NIGHT UTXO is created **and** that key already has a registration table entry. Designation is not retroactive, so tNIGHT that arrived before you designated a DUST address generates nothing. Order matters: 1. Create your wallet. 2. Request tNIGHT from the faucet. 3. Designate a DUST address. If you funded the wallet first and are now watching a zero balance, you do not need a new wallet. Designate the DUST address, then create a fresh tNIGHT UTXO by sending tNIGHT to yourself. The new UTXO generates normally. Beyond ordering, check these: * **You are waiting less time than you think.** On a live network, allow hours rather than minutes. * **You are looking at a wallet on a different network.** Preview and Preprod are separate chains with separate faucets and separate balances. * **The transaction sat too long.** DUST spends carry a timestamp and a grace period of about 3 hours. A transaction built and left overnight is rejected. ## What to remember[​](#what-to-remember "Direct link to What to remember") The proof server is not incidental tooling. It is where Midnight's core tradeoff physically lives: heavy, privacy-preserving work on your machine, and a millisecond public check on-chain. * It runs on your machine because it sees your witness data. * It never touches your wallet keys, and it cannot sign or spend. * It ships in Docker because that is the cleanest way to distribute a native cryptographic service across three operating systems with versions pinned. * Pin the tag, keep it running, and point everything at `localhost:6300`. Start on Undeployed, designate your DUST address before you fund the wallet, and the first ten minutes stop being the hard part. ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Run the proof server](/guides/run-proof-server.md): the wallet-user walkthrough of starting the container from Docker Desktop. * [Install the Midnight toolchain](/getting-started/installation.md): the Compact compiler and developer tools. * [Quickstart](/getting-started/quickstart.md): a local devnet with node, indexer, and proof server from one compose file. * [Networks and environments](/guides/networks-and-environments.md): endpoints and network IDs for every environment. * [Funding a wallet](/guides/acquire-tokens.md): the faucet, registration in Lace, and the wallet SDK path. * [DUST architecture](/concepts/dust-architecture.md): the NIGHT and DUST model in depth. * [Support matrix](/relnotes/support-matrix.md): which proof server versions pair with which network components. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Networks and environments Use this guide to understand the networks Midnight operates, pick the right one for the task in front of you, point your DApp at it, fund a wallet on it, and move to mainnet when you are ready. It explains the network landscape, gives you the exact endpoints and IDs to configure tools against, and walks through each task ending with a test you run to prove it worked. If you are starting from nothing, scaffold a project with the [quickstart](/getting-started/quickstart.md) first and return here when you need to choose or switch networks. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * Node.js version 22 or higher installed. * Docker installed and running, for the local network and the [proof server](/guides/run-proof-server.md). * [Vitest](https://vitest.dev/) and `@midnight-ntwrk/midnight-js-network-id` installed in your test workspace, for the verification tests. ## The Midnight networks[​](#the-midnight-networks "Direct link to The Midnight networks") Midnight operates one production network and maintains three environments for development. Every environment runs the same stack, so a DApp moves between them by changing configuration, not code. Four networks make up the landscape: * **`undeployed`** is the local development network: a Midnight node, indexer, and proof server running in Docker on your machine. Its genesis wallet is pre-funded, so you can deploy within minutes of starting it. See [Running a local network](#running-a-local-network). * **`preview`** is a public test network for early development and experimentation, maintained by core engineering. * **`preprod`** is a public test network for final validation before mainnet. Of the test networks, it tracks mainnet most closely. * **`mainnet`** is the production network. Tokens on mainnet carry real value, and there is no faucet. Each public network identifies itself over RPC: the `system_chain` method returns `Midnight Preview`, `Midnight Preprod`, or `Midnight Mainnet`. Every network exposes the same three services your DApp talks to: a node (JSON-RPC over HTTPS and WebSocket), an indexer (GraphQL over HTTP and WebSocket), and a proof server. The node and indexer are network-specific; the proof server runs locally on port 6300 no matter which network you target, because it handles your private data. The [Environment reference](#environment-reference) lists every endpoint. The testnet-02 name is retired Older articles and tools sometimes reference a network named `testnet-02`. That network has been retired and its endpoints no longer resolve. Use `preview` or `preprod` instead. ## Network selection at a glance[​](#network-selection-at-a-glance "Direct link to Network selection at a glance") Which network to target for a given task. Consult this before you configure anything; the setup and funding consequences of each choice are listed alongside. | Task | Network | Funding | Value at risk | | ----------------------------------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------- | ------------- | | Iterating on a contract, running tests, CI | `undeployed` | Genesis wallet is pre-funded, no faucet needed | None | | Testing against shared public infrastructure early in development | `preview` | Free tNIGHT from the [Preview faucet](https://midnight-tmnight-preview.nethermind.dev/), rate limited | None | | Final validation before a production launch | `preprod` | Free tNIGHT from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/), rate limited | None | | Running in production | `mainnet` | Real NIGHT, which generates DUST after registration | Real | Start on `undeployed` for speed, move to `preview` or `preprod` when you need shared infrastructure or a persistent chain, validate on `preprod` before launch, and treat `mainnet` as a deliberate final step. [Funding and transaction cost](#funding-and-transaction-cost) explains what each choice costs. ## Environment reference[​](#environment-reference "Direct link to Environment reference") The endpoints, network ID, and funding source for each environment. Configure wallets, indexers, and tooling against these values; other pages link here rather than restating them. * Local (undeployed) * Preview * Preprod * Mainnet The local development network, run via [midnight-local-dev](https://github.com/midnightntwrk/midnight-local-dev). All services run in Docker on your machine; set it up in [Running a local network](#running-a-local-network). | Service | Value | | ------------------- | ------------------------------------------------------------------------------------------------ | | Network ID | `undeployed` | | Node RPC | `http://localhost:9944` | | Indexer (GraphQL) | `http://localhost:8088/api/v4/graphql` | | Indexer (WebSocket) | `ws://localhost:8088/api/v4/graphql/ws` | | Proof server | `http://localhost:6300` | | Faucet | None. The genesis wallet is pre-funded and the funding menu transfers 50,000 tNIGHT per account. | | Address prefixes | `mn_addr_undeployed`, `mn_shield-addr_undeployed`, `mn_dust_undeployed` | | Block explorers | None | Public test network for early development and experimentation. | Service | Value | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Network ID | `preview` | | Node RPC | `https://rpc.preview.midnight.network` | | Node WebSocket | `wss://rpc.preview.midnight.network` | | Indexer (GraphQL) | `https://indexer.preview.midnight.network/api/v4/graphql` | | Indexer (WebSocket) | `wss://indexer.preview.midnight.network/api/v4/graphql/ws` | | Proof server | `http://localhost:6300` (always local) | | Faucet | | | Address prefixes | `mn_addr_preview`, `mn_shield-addr_preview`, `mn_dust_preview` | | Block explorers | [Midnight Explorer](https://preview.midnightexplorer.com/), [Subscan](https://midnight-preview.subscan.io/), [1am](https://explorer.1am.xyz/?network=preview) | Public test network for final validation before mainnet. | Service | Value | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Network ID | `preprod` | | Node RPC | `https://rpc.preprod.midnight.network` | | Node WebSocket | `wss://rpc.preprod.midnight.network` | | Indexer (GraphQL) | `https://indexer.preprod.midnight.network/api/v4/graphql` | | Indexer (WebSocket) | `wss://indexer.preprod.midnight.network/api/v4/graphql/ws` | | Proof server | `http://localhost:6300` (always local) | | Faucet | | | Address prefixes | `mn_addr_preprod`, `mn_shield-addr_preprod`, `mn_dust_preprod` | | Block explorers | [Midnight Explorer](https://preprod.midnightexplorer.com/), [Subscan](https://midnight-preprod.subscan.io/), [1am](https://explorer.1am.xyz/?network=preprod) | The production network. | Service | Value | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | Network ID | `mainnet` | | Node RPC | `https://rpc.mainnet.midnight.network` | | Node WebSocket | `wss://rpc.mainnet.midnight.network` | | Indexer (GraphQL) | `https://indexer.mainnet.midnight.network/api/v4/graphql` | | Indexer (WebSocket) | `wss://indexer.mainnet.midnight.network/api/v4/graphql/ws` | | Proof server | `http://localhost:6300` (always local) | | Faucet | None. See [Funding and transaction cost](#funding-and-transaction-cost). | | Address prefixes | `mn_addr`, `mn_shield-addr`, `mn_dust` | | cNgD DApp | | | Block explorers | [Midnight Explorer](https://midnightexplorer.com/), [Subscan](https://midnight.subscan.io/), [1am](https://explorer.1am.xyz/) | Addresses are Bech32m encoded, and the prefix names the address type and the network: `mainnet` uses the bare prefix, for example `mn_addr`, while every other network appends its name, for example `mn_addr_preprod`. Wallet viewing keys follow the same rule with the `mn_shield-esk` prefix. Midnight provides the public node and indexer endpoints for development and testing. For a production DApp, consider running your own [node](/nodes.md) or using a dedicated infrastructure provider. ## Running a local network[​](#running-a-local-network "Direct link to Running a local network") Run the full Midnight stack, a node, an indexer, and a proof server, in Docker on your machine with [midnight-local-dev](https://github.com/midnightntwrk/midnight-local-dev). The tool initializes a pre-funded genesis wallet and presents a funding menu, so you can deploy and transact within minutes, with no faucet and nothing at risk. ### Procedure[​](#procedure "Direct link to Procedure") 1. Clone the repository and install its dependencies: ``` git clone https://github.com/midnightntwrk/midnight-local-dev.git cd midnight-local-dev npm install ``` 2. Start the network: ``` npm start ``` The command pulls the Docker images (versions are pinned in `standalone.yml`), starts the node, indexer, and proof server with health checks, initializes the genesis master wallet that holds the pre-mined NIGHT, registers it for DUST so it can pay fees, and then presents the funding menu: ``` Choose an option: [1] Fund accounts from config file (NIGHT + DUST registration) [2] Fund accounts by public key (NIGHT transfer only) [3] Display wallets [4] Exit ``` 3. Fund the wallets you develop with. Option `1` reads a JSON file of accounts (copy `accounts.example.json` to `accounts.json` and add your 24-word mnemonics), transfers tNIGHT to each, and registers each account for DUST generation. Option `2` transfers tNIGHT to Bech32m addresses you paste, and the recipients register for DUST themselves. Either way, each account receives 50,000 tNIGHT, up to 10 accounts per operation. 4. If you only need the containers, skip the wallet tooling and use Docker Compose directly. In this mode you handle genesis funding and DUST registration yourself: ``` docker compose -f standalone.yml up -d # start docker compose -f standalone.yml ps # status docker compose -f standalone.yml logs -f # logs docker compose -f standalone.yml down # stop ``` ### Verification[​](#verification "Direct link to Verification") The local endpoints answer: the node reports the dev chain and serves its health check, the indexer serves blocks, and the proof server accepts connections. local-network.test.ts ``` import { describe, it, expect } from 'vitest'; describe('local network', () => { it('node is healthy', async () => { const res = await fetch('http://localhost:9944/health').then((r) => r.json()); expect(res.isSyncing).toBe(false); }); it('indexer serves blocks', async () => { const res = await fetch('http://localhost:8088/api/v4/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ block { height } }' }), }).then((r) => r.json()); expect(res.data.block.height).toBeGreaterThan(0); }); it('proof server reports ok', async () => { const res = await fetch('http://localhost:6300/health').then((r) => r.json()); expect(res.status).toBe('ok'); }); }); ``` ``` ✓ local-network.test.ts > local network > node is healthy ✓ local-network.test.ts > local network > indexer serves blocks ✓ local-network.test.ts > local network > proof server reports ok Test Files 1 passed (1) Tests 3 passed (3) ``` ## Local network troubleshooting[​](#local-network-troubleshooting "Direct link to Local network troubleshooting") The failure modes you are most likely to hit with the local stack, and their fixes. | Symptom | Fix | | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Bind for 0.0.0.0:9944 failed: port is already allocated` | A previous run still holds the port. Run `docker compose -f standalone.yml down`, or find the holder with `lsof -i :9944`. | | Indexer exits on first start with `block number 1 not found` | A startup race on a fresh chain: the indexer asked for a block the node had not produced yet. Start it again with `docker start midnight-indexer`; it latches on once blocks exist. | | `Operation failed: Expected undeployed address, got Preprod address` | The wallet is on the wrong network. In Lace, switch to the Undeployed network under **Settings**, then use that unshielded address. | | Containers do not start | Confirm Docker is running, then run `docker compose -f standalone.yml pull` and `up`, and read `docker compose -f standalone.yml logs -f` for the failing service. | | Wallet sync is slow after startup | The indexer is catching up with the node. Confirm the node produces blocks with `curl http://localhost:9944/health` and watch the indexer logs. | ## Connecting a DApp to a network[​](#connecting-a-dapp-to-a-network "Direct link to Connecting a DApp to a network") Point a DApp at a chosen network by setting the network ID and wiring the matching endpoints. The common trap is mixing values from different networks, for example a `preprod` network ID with a `preview` indexer URL; keep the ID and the endpoints together in one place so they cannot drift apart. ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. Choose the target network using [Network selection at a glance](#network-selection-at-a-glance). 2. Set the network ID before initializing any providers. Midnight.js reads this value when it normalizes addresses and builds transactions (the `deployContract` and `callTx` paths), so it must be set before any contract operation: ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('preprod'); /** Supported network IDs: 'mainnet', 'preview', 'preprod', 'undeployed' */ ``` There is no default: `getNetworkId()` throws `Network ID has not been configured` until you call `setNetworkId`. The call stores the string as-is, so a misspelled network name does not fail here; it surfaces later, in the components that consume the ID. 3. Keep the network ID and its endpoints together in one configuration object, using the values from the [Environment reference](#environment-reference). Note that the proof server URL stays local for every network: ``` const NETWORKS = { undeployed: { node: 'http://localhost:9944', indexer: 'http://localhost:8088/api/v4/graphql', indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', proofServer: 'http://localhost:6300', }, preprod: { node: 'https://rpc.preprod.midnight.network', indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', proofServer: 'http://localhost:6300', }, } as const; const network = NETWORKS['preprod']; ``` 4. Pass the endpoints to your providers. The full providers object, including private state, ZK configuration, and wallet providers, is covered in [Configuring providers for a contract](/guides/deploy-and-operate.md#configuring-providers-for-a-contract): ``` import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; const publicDataProvider = indexerPublicDataProvider(network.indexer, network.indexerWS); ``` 5. In a project scaffolded with `create-mn-app` (the `hello-world` template), select the network with the setup script instead. The selection is sticky until you switch: ``` npm run setup -- --network preview # runs on preview and makes it active npm run network preprod # switch the active network later ``` The scaffold's network scripts accept `undeployed`, `preview`, and `preprod`. Mainnet is not a scaffold target; wire it through providers as shown above. ### Verification[​](#verification-1 "Direct link to Verification") Each network ID round-trips through the SDK, and the configured endpoints answer with the expected chain identity and a current block height. networks.test.ts ``` import { describe, it, expect } from 'vitest'; import { setNetworkId, getNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; const rpc = (url: string, method: string) => fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method, params: [], id: 1 }), }).then((r) => r.json()); const indexerBlock = (url: string) => fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ block { height } }' }), }).then((r) => r.json()); const networks = [ { id: 'preview', chain: 'Midnight Preview', node: 'https://rpc.preview.midnight.network', indexer: 'https://indexer.preview.midnight.network/api/v4/graphql', }, { id: 'preprod', chain: 'Midnight Preprod', node: 'https://rpc.preprod.midnight.network', indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql', }, { id: 'mainnet', chain: 'Midnight Mainnet', node: 'https://rpc.mainnet.midnight.network', indexer: 'https://indexer.mainnet.midnight.network/api/v4/graphql', }, ]; describe.each(networks)('$id', ({ id, chain, node, indexer }) => { it('sets the network ID', () => { setNetworkId(id); expect(getNetworkId()).toBe(id); }); it('reaches the node RPC', async () => { const res = await rpc(node, 'system_chain'); expect(res.result).toBe(chain); }); it('reaches the indexer', async () => { const res = await indexerBlock(indexer); expect(res.data.block.height).toBeGreaterThan(0); }); }); ``` ``` ✓ networks.test.ts > 'preview' > sets the network ID ✓ networks.test.ts > 'preview' > reaches the node RPC ✓ networks.test.ts > 'preview' > reaches the indexer ✓ networks.test.ts > 'preprod' > sets the network ID ✓ networks.test.ts > 'preprod' > reaches the node RPC ✓ networks.test.ts > 'preprod' > reaches the indexer ✓ networks.test.ts > 'mainnet' > sets the network ID ✓ networks.test.ts > 'mainnet' > reaches the node RPC ✓ networks.test.ts > 'mainnet' > reaches the indexer Test Files 1 passed (1) Tests 9 passed (9) ``` The `undeployed` network is not in the matrix because it only exists while your local containers run. With the [local network](#running-a-local-network) up, the same checks pass against `http://localhost:9944` and `http://localhost:8088/api/v4/graphql`. ## Funding and transaction cost[​](#funding-and-transaction-cost "Direct link to Funding and transaction cost") Every transaction on Midnight consumes DUST, and where the DUST comes from is the main practical difference between the networks. Understanding the two-token model once saves you a confused hour on each network later. NIGHT is the native utility token; holding it is what entitles you to DUST. DUST is a shielded, non-transferable resource that fees are paid in. Registered NIGHT generates DUST over time up to a cap of about 5 DUST per NIGHT, refilling in roughly a week, so a funded wallet regenerates its capacity to transact rather than spending it away permanently. [Tokens on Midnight](/tokens/overview.md) introduces the model and [DUST architecture](/concepts/dust-architecture.md) covers generation, decay, and the protocol parameters. **On the local network**, the genesis wallet is pre-funded and already registered for DUST, and the funding menu transfers tNIGHT to your own test wallets. DUST generates in about 5 minutes. There is no faucet because none is needed; see [Running a local network](#running-a-local-network). **On `preview` and `preprod`**, request free tNIGHT from the network's faucet (the Preprod faucet sends 1,000 tNIGHT per request; both faucets are rate limited), then register it for tDUST generation in your wallet. The [Funding a wallet](/guides/acquire-tokens.md) guide walks through the faucet, the Lace **Generate tDUST** flow, and the scriptable wallet SDK path. Test tokens carry no real value. **On `mainnet`**, there is no faucet. Today most NIGHT is held on Cardano as cNIGHT, and DUST generation is cross-chain: you register your Cardano reward address together with a Midnight DUST public key (the [cNgD DApp](https://midnight-dust-mainnet.nethermind.io/) handles this), and your cNIGHT holdings then generate DUST on Midnight. The registration must finalize on Cardano and reach a Midnight node, which takes about 12 hours, so fund your production wallet well before launch day. ## Preparing a DApp for mainnet[​](#preparing-a-dapp-for-mainnet "Direct link to Preparing a DApp for mainnet") Move a DApp that works on `preprod` to the production network. The mechanics are the same configuration change as any other network switch; what makes mainnet different is that funding is cross-chain and slow, mistakes cost real value, and public test infrastructure guarantees do not apply. ### Prerequisites[​](#prerequisites-1 "Direct link to Prerequisites") * A DApp deployed and validated on `preprod`, connected as in [Connecting a DApp to a network](#connecting-a-dapp-to-a-network). ### Procedure[​](#procedure-2 "Direct link to Procedure") 1. Validate the full deploy and interaction flow on `preprod` first. It is the network closest to mainnet, so anything that fails there will fail in production. 2. Fund the production wallet. Register your cNIGHT for DUST generation through the [cNgD DApp](https://midnight-dust-mainnet.nethermind.io/) and allow about 12 hours for the registration to take effect, as described in [Funding and transaction cost](#funding-and-transaction-cost). Confirm the wallet shows a DUST balance before you attempt a transaction. 3. Point the configuration at mainnet. Set the network ID and swap the endpoints; nothing else in the DApp changes: ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; setNetworkId('mainnet'); const network = { node: 'https://rpc.mainnet.midnight.network', indexer: 'https://indexer.mainnet.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.mainnet.midnight.network/api/v4/graphql/ws', proofServer: 'http://localhost:6300', }; ``` The `create-mn-app` scaffold does not offer a mainnet target, so wire the providers yourself as in [Configuring providers for a contract](/guides/deploy-and-operate.md#configuring-providers-for-a-contract). 4. Decide your infrastructure. The public endpoints are provided for development and testing; for production, run your own [node](/nodes.md) and indexer or use a dedicated infrastructure provider. 5. Work through the [Mainnet readiness checklist](#mainnet-readiness-checklist) before announcing anything. ### Verification[​](#verification-2 "Direct link to Verification") The mainnet endpoints answer with the production chain identity and a current block height. Run the connection test from this guide filtered to mainnet: ``` npx vitest run networks.test.ts -t mainnet ``` ``` ↓ networks.test.ts > 'preview' > sets the network ID ↓ networks.test.ts > 'preview' > reaches the node RPC ↓ networks.test.ts > 'preview' > reaches the indexer ↓ networks.test.ts > 'preprod' > sets the network ID ↓ networks.test.ts > 'preprod' > reaches the node RPC ↓ networks.test.ts > 'preprod' > reaches the indexer ✓ networks.test.ts > 'mainnet' > sets the network ID ✓ networks.test.ts > 'mainnet' > reaches the node RPC ✓ networks.test.ts > 'mainnet' > reaches the indexer Test Files 1 passed (1) Tests 3 passed | 6 skipped (9) ``` ## Mainnet readiness checklist[​](#mainnet-readiness-checklist "Direct link to Mainnet readiness checklist") Work through this list before a production launch. Each item links to the page that explains it. * [ ] **The full flow is validated on `preprod`.** Deploy, interact, and observe state end to end on the network closest to mainnet. * [ ] **The security checklist is complete.** Work through the [pre-deployment security checklist](/guides/security-best-practices.md#pre-deployment-security-checklist) for the contract and the DApp around it. * [ ] **The updatability decision is made.** Decide whether and how the contract can be upgraded before it holds real value. See [Contract updatability and the maintenance authority](/guides/deploy-and-operate.md#contract-updatability-and-the-maintenance-authority). * [ ] **The production wallet generates DUST.** cNIGHT is registered, the roughly 12-hour registration delay has passed, and the wallet shows a DUST balance. See [Funding and transaction cost](#funding-and-transaction-cost). * [ ] **Every endpoint in the configuration is a mainnet endpoint.** No `preview` or `preprod` URL remains. See the [Environment reference](#environment-reference). * [ ] **The infrastructure decision is made.** You run your own node and indexer, or you have a dedicated provider; the public endpoints are for development and testing. * [ ] **Key custody is settled.** The keys that control the contract and the funds have an owner, a backup, and a rotation path. See [Security and best practices](/guides/security-best-practices.md). * [ ] **You can observe the DApp in production.** You know which [block explorer](#environment-reference) and indexer queries you will use to confirm the deployment and watch activity. ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Environments and endpoints](/relnotes/network.md): the release-notes view of the per-network endpoints. * [Node endpoints](/nodes/node-endpoints.md): RPC quickstart, common queries, and the Insomnia collection. * [midnight-local-dev on GitHub](https://github.com/midnightntwrk/midnight-local-dev): the local network tool, its pinned image versions, and its README. * [Run the proof server](/guides/run-proof-server.md): the local proof server every network setup depends on. * [Deploying and operating a contract](/guides/deploy-and-operate.md): the complete providers object a DApp passes to the SDK, and what comes after deployment. * [Funding a wallet](/guides/acquire-tokens.md): the faucet, the Lace registration flow, and the wallet SDK path. * [Security and best practices](/guides/security-best-practices.md): hardening a contract and DApp before mainnet. --- # Create a Next.js wallet connector > For the complete documentation index, see [llms.txt](/llms.txt) This guide explains how to create a Next.js application that connects to the Midnight Lace wallet using the DApp Connector API. You'll build a wallet connection button that displays connection status, providing a foundation for building more complex DApps. The code examples focus on core functionality and intentionally omit CSS styling. You can add your preferred styling solution such as Tailwind, styled-components, or CSS modules to match your application's design. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, make sure you have: * Basic knowledge of TypeScript and JavaScript * Familiarity with React and Next.js fundamentals * Node.js and npm installed on your system * [Midnight Lace wallet extension](https://chromewebstore.google.com/detail/lace/gafhhkghbfjjkeiendhlofajokpaflmk) installed in your browser ### Set up a Next.js project[​](#set-up-a-nextjs-project "Direct link to Set up a Next.js project") If you don't have a Next.js project yet, create one using the following command: ``` npm create-next-app@latest ``` When prompted, select the following options: * **TypeScript**: Yes * **ESLint**: Yes * **Tailwind CSS**: Yes (optional, but recommended) * **App Router**: Yes * **Other options**: Choose based on your preference Then navigate to the project directory and install the DApp Connector API package: ``` cd npm install @midnight-ntwrk/dapp-connector-api ``` note This guide uses the DApp Connector API v4.0.0. For more information, see the [DApp Connector API documentation](/api-reference/dapp-connector.md). After completing this tutorial, you'll understand: * How to integrate wallet connections in Next.js applications * The differences between client and server components when working with wallets * How to manage wallet state in Next.js * Best practices for using the DApp Connector API in Next.js 1 ## Create the wallet connection component[​](#create-the-wallet-connection-component "Direct link to Create the wallet connection component") You'll build a client-side component that handles wallet connection. Since wallet interactions require browser APIs, this component must run on the client side using Next.js's `"use client"` directive. Create `app/components/ConnectWalletButton.tsx`: ``` "use client"; // Next.js directive for client-side rendering import { useState } from "react"; import "@midnight-ntwrk/dapp-connector-api"; import type { InitialAPI } from "@midnight-ntwrk/dapp-connector-api"; export default function ConnectWalletButton() { const [connected, setConnected] = useState(false); const [walletAddress, setWalletAddress] = useState(null); const handleConnect = async () => { try { // Access the Midnight Lace wallet through the window object const wallet: InitialAPI = await window.midnight!.mnLace; // Connect to the specified network (use 'undeployed' for local development) const connectedApi = await wallet.connect('preprod'); // Retrieve the shielded addresses from the wallet const addresses = await connectedApi.getShieldedAddresses(); const address = addresses.shieldedAddress; // Check if the connection is established const connectionStatus = await connectedApi.getConnectionStatus(); if (connectionStatus) { setConnected(true); setWalletAddress(address); console.log("Connected to wallet:", address); } } catch (error) { console.log("Failed to connect:", error); } }; const handleDisconnect = () => { setConnected(false); setWalletAddress(null); }; return (

); } ``` This component manages the wallet connection flow: 1. **Client-side rendering**: The `"use client"` directive ensures this component runs in the browser where wallet APIs are available. 2. **State management**: Uses React's `useState` hook to track connection status and wallet address. 3. **Connection logic**: The `handleConnect` function accesses the wallet through `window.midnight.mnLace`, connects to the specified network, and retrieves the wallet's shielded address. 4. **User feedback**: Displays the wallet address (truncated) and provides connect/disconnect actions. 2 ## Add the component to your layout[​](#add-the-component-to-your-layout "Direct link to Add the component to your layout") Now integrate the wallet button into your application's layout so it appears on every page. Update `app/layout.tsx`: ``` import type { Metadata } from "next"; import "./globals.css"; import ConnectWalletButton from "./components/ConnectWalletButton"; export const metadata: Metadata = { title: "Midnight Wallet Connector", description: "Connect to Midnight Lace wallet", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return (
{children}
); } ``` The `ConnectWalletButton` component now appears at the top of every page in your application. Next.js's layout system makes it easy to create persistent UI elements across routes. 3 ## Create a welcome page[​](#create-a-welcome-page "Direct link to Create a welcome page") Create a simple landing page that encourages users to connect their wallet. For this, replace the content of `app/page.tsx` with the following: ``` export default function Home() { return (

Welcome to Midnight

Connect your Lace wallet to get started with privacy-preserving decentralized applications on the Midnight Network.

Click the "Connect Wallet" button in the top right corner to authorize this application to access your Midnight Lace wallet.

); } ``` 4 ## Run your application[​](#run-your-application "Direct link to Run your application") Start the Next.js development server: ``` npm run dev ``` Open your browser and navigate to `http://localhost:3000`. When you click **Connect Wallet**, the Midnight Lace wallet extension prompts you to authorize the connection. ![Connect Wallet](/assets/images/connect-wallet-next-d338583212c680c9863df7b4fb57279e.png) The wallet asks you to choose your preferred authorization level: * **Always**: Grants persistent authorization. The application remains authorized even after closing your browser, and you won't need to reconnect on future visits. * **Only once**: Grants temporary authorization. You must reauthorize the connection each time you visit the application. ![Authorize Connection](/assets/images/dapp-connection-option-7b27aa0921e8ddbb847782a6df664523.png) After approval, the button changes to "Disconnect" and displays your truncated wallet address. ![Connected Wallet](/assets/images/connected-wallet-next-9eb345170bcffe9a9e8e5048b6fa3ac5.png) 5 ## Verify the connection[​](#verify-the-connection "Direct link to Verify the connection") You can verify that your wallet is connected to the application: 1. Open the Midnight Lace wallet extension in your browser. 2. Click on your wallet name in the top right corner, then select **Settings**. 3. Navigate to **Authorized DApps**. You should see `http://localhost:3000` listed as an authorized application. ![Authorized DApps](/assets/images/authorized-dapps-891a1f6fb597ecaec35fbd0eee1075d5.png) You can revoke access at any time from this panel by clicking the **trash** icon next to the application. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") These are some of the common issues you might encounter and how to resolve them. ### "window is not defined" error[​](#window-is-not-defined-error "Direct link to \"window is not defined\" error") This error occurs because Next.js tries to render components on the server by default, but wallet APIs only exist in the browser environment. **How to fix it**: Make sure your wallet component includes the `"use client"` directive at the top of the file. ### Wallet not detected[​](#wallet-not-detected "Direct link to Wallet not detected") This error means the browser cannot access `window.midnight`, which indicates the Midnight Lace wallet extension is not available. **How to fix it**: * Verify the Midnight Lace wallet extension is installed and enabled. * Refresh the page after installing the extension. * Check the browser console for extension-related errors. * Ensure you're testing in a browser, not during server-side rendering. ### Connection fails[​](#connection-fails "Direct link to Connection fails") This error occurs when the wallet connection attempt is unsuccessful, which can happen for several reasons related to configuration or wallet state. **How to fix it**: * Confirm that you're using the correct network ID. For local development, use `'undeployed'`. For Preprod environment, use `'preprod'`. * Make sure the Lace wallet is unlocked. * Check the browser console for specific error messages. * Verify the DApp Connector API package is correctly installed. ## Next steps[​](#next-steps "Direct link to Next steps") Now that you have a working wallet connector in Next.js, you can extend your application: * **Create protected routes**: Use Next.js middleware to restrict access to pages that require wallet connection. * **Transfer coins**: Build a form that allows users to send tokens to other addresses. * **Display balances**: Show the user's token balances on a dashboard page. * **Transaction history**: Create a page that queries and displays transaction history. ## Reference[​](#reference "Direct link to Reference") * [DApp Connector API documentation](/api-reference/dapp-connector.md) * [Next.js documentation](https://nextjs.org/docs) * [Midnight Lace wallet](https://chromewebstore.google.com/detail/lace/gafhhkghbfjjkeiendhlofajokpaflmk) --- # Create a React wallet connector > For the complete documentation index, see [llms.txt](/llms.txt) In this guide, you'll create a React application that connects to a Midnight wallet using the DApp Connector API. You'll build a simple interface that displays connection status and wallet addresses, providing a foundation for more complex decentralized applications. The code examples focus on core functionality and intentionally omit CSS styling. You can add your preferred styling solution (Tailwind, styled-components, CSS modules, etc.) to match your application's design. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, make sure you have: * Basic knowledge of TypeScript and JavaScript * Familiarity with React fundamentals (components, state, hooks) * Node.js and npm installed on your system * A Midnight wallet extension installed in your browser ### Set up a React project[​](#set-up-a-react-project "Direct link to Set up a React project") If you don't have a React project yet, create one using Vite: ``` npm create vite@latest my-wallet-app -- --template react-ts cd my-wallet-app ``` Then install the DApp Connector API package: ``` npm install @midnight-ntwrk/dapp-connector-api ``` After completing this tutorial, you'll understand: * The Midnight wallet connection flow * How to use the DApp Connector API * Best practices for managing wallet state in React applications 1 ## Define TypeScript interfaces[​](#define-typescript-interfaces "Direct link to Define TypeScript interfaces") Start by creating type definitions for your components. These interfaces provide type safety and clear contracts between components. Create a new file `types.ts` within the `src` directory and add the following code: ``` export interface WalletCardProps { isConnected: boolean; walletAddress: string | null; onConnect: () => void; onDisconnect: () => void; } ``` The `WalletCardProps` interface defines the shape of data your `WalletCard` component will receive. It includes the connection state, the wallet address, and callback functions for connect and disconnect actions. 2 ## Create the WalletCard component[​](#create-the-walletcard-component "Direct link to Create the WalletCard component") Now you'll build the `WalletCard` component, which displays the wallet connection status and provides connect/disconnect buttons. Create `WalletCard.tsx` within the `src` directory and add the following code: ``` import React from "react"; import type { WalletCardProps } from "./types"; const WalletCard: React.FC = ({ isConnected, walletAddress, onConnect, onDisconnect, }) => { return (

Connection Status

{isConnected ? "Connected" : "Disconnected"}
{isConnected && walletAddress ? ( <>

Wallet Address:

{walletAddress}

) : (

Please connect your wallet to proceed.

)}
{isConnected ? ( ) : ( )}
); }; export default WalletCard; ``` This component handles the presentation layer of your wallet connection. It shows the current status, displays the address when connected, and provides appropriate action buttons based on the connection state. 3 ## Select a wallet[​](#select-a-wallet "Direct link to Select a wallet") Wallets inject their Initial API instances under the global `window.midnight` object, each keyed by a freshly generated UUID rather than a fixed name. A single browser may also have more than one wallet available at once, for example when two wallets are loaded from the same seed phrase. Because of this, you read the entries on `window.midnight` and choose one, rather than reaching for a hardcoded key. Create a new file `selectWallet.ts` within the `src` directory and add the following code: ``` import type { InitialAPI } from '@midnight-ntwrk/dapp-connector-api'; export const listWallets = (): InitialAPI[] => { const injected = window.midnight; return injected ? Object.values(injected) : []; }; export const selectWallet = (): InitialAPI => { const wallets = listWallets(); if (wallets.length === 0) { throw new Error('No Midnight wallet found. Please install a Midnight wallet extension.'); } return wallets[0]; }; ``` The `selectWallet` function reads the installed wallets and returns the first one, which keeps this example focused on the connection flow. When more than one wallet is available, the DApp Connector API specification expects you to let the user choose rather than picking for them. Use `listWallets` to render the options, and when displaying each wallet, render its `name` and `icon` safely to prevent XSS. 4 ## Integrate the DApp Connector API[​](#integrate-the-dapp-connector-api "Direct link to Integrate the DApp Connector API") Next, we'll use the `App` component to manage the wallet connection logic using the DApp Connector API and the `selectWallet` helper from the previous step. Create or open `App.tsx` within the `src` directory and replace the existing code with the following: ``` import React, { useState } from 'react'; import WalletCard from './WalletCard'; import '@midnight-ntwrk/dapp-connector-api'; import { selectWallet } from './selectWallet'; const App: React.FC = () => { const [isConnected, setIsConnected] = useState(false); const [walletAddress, setWalletAddress] = useState(null); const handleConnect = async () => { console.log('Connect button clicked'); let isConnected = false; let address = null; try { const wallet = selectWallet(); // Connect to the specified network (use 'undeployed' for local development) const connectedApi = await wallet.connect('preprod'); // Retrieve the unshielded address from the wallet const { unshieldedAddress } = await connectedApi.getUnshieldedAddress(); address = unshieldedAddress; // Optional: Get the service URI configuration const serviceUriConfig = await connectedApi.getConfiguration(); console.log('Service URI Config:', serviceUriConfig); // Check if the connection is established const connectionStatus = await connectedApi.getConnectionStatus(); if (connectionStatus.status === 'connected') { isConnected = true; console.log("Connected to the wallet:", address); } } catch (error) { console.log("An error occurred:", error); } setIsConnected(isConnected); setWalletAddress(address); }; const handleDisconnect = () => { setWalletAddress(null); setIsConnected(false); }; return (

Midnight Wallet Connector

); }; export default App; ``` Let's break down the wallet connection process: 1. **Select a wallet**: The `selectWallet` helper reads the installed wallets from `window.midnight` and returns one to connect to. It throws if no wallet is found, which the surrounding `try/catch` handles. 2. **Connect to network**: Call the `connect()` method and pass the network ID as an argument. In our example, we used `'preprod'`. You can use `'undeployed'` for local development or `'preview'` for the Preview network. 3. **Retrieve the address**: After connecting to the network, call the `getUnshieldedAddress()` method to get the wallet's unshielded address. Request the shielded address only when your application actually needs it. 4. **Check status**: Verify the connection with `getConnectionStatus()`, which resolves to an object whose `status` is `'connected'` or `'disconnected'`. The `handleConnect` event handler manages all these steps and updates your component's state accordingly. When users click the **Connect Wallet** button, their wallet will prompt them to authorize the connection. 5 ## Set up the entry point[​](#set-up-the-entry-point "Direct link to Set up the entry point") Create the entry point that bootstraps your React application. For this, create or open `main.tsx` within the `src` directory and replace the existing code with the following: ``` import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import App from './App.tsx'; createRoot(document.getElementById('root')!).render( , ); ``` Finally, create or open `index.html` in the project root and replace the existing code with the following: ``` Midnight Wallet Connector
``` 6 ## Run your application[​](#run-your-application "Direct link to Run your application") After setting up the entry point, start your development server: ``` npm run dev ``` Now, open your browser and navigate to the local development URL (typically `http://localhost:5173`). When you click **Connect Wallet**, your wallet extension will prompt you to authorize the connection. ![Connect Wallet](/assets/images/connect-wallet-94a66543da3707fc5245b64212af2f4b.png) After approval, your application will display the connection status and your wallet's unshielded address. ![Connected Wallet](/assets/images/connected-wallet-e22df750152a55e1483b0623fa8cb1a8.png) ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") The following are some common issues you might encounter and how to resolve them. ### Wallet not detected[​](#wallet-not-detected "Direct link to Wallet not detected") If you see errors about `window.midnight` being undefined, or `No Midnight wallet found`: * Verify a Midnight wallet extension is installed and enabled in your browser. * Refresh the page after installing or enabling the extension. * Confirm you are reading the wallet from `window.midnight` by enumeration (`Object.values(window.midnight)`) and not from a fixed key such as `window.midnight.mnLace`. Wallets inject their Initial API under a UUID key, so a hardcoded name resolves to `undefined`. * Check the browser console for any extension-related errors. ### Connection fails[​](#connection-fails "Direct link to Connection fails") If the connection attempt fails: * Ensure the network ID specified in the `connect()` method matches the network ID configured in your wallet. * Check that the wallet is unlocked and synced. * Review the browser console for specific error messages. * Verify the DApp Connector API package is correctly installed. ## Next steps[​](#next-steps "Direct link to Next steps") Now that you have a working wallet connector, you can extend your application with additional functionality: * **Transfer coins**: Implement a form that allows users to send tokens to other addresses. * **Sign messages**: Add a text input where users can sign arbitrary messages with their wallet. * **Display balances**: Show the user's token balances for different assets. * **Transaction history**: Query and display the user's transaction history. * **Multi-network support**: Add a network selector to switch between different Midnight networks. ## Reference[​](#reference "Direct link to Reference") * [DApp Connector API documentation](/api-reference/dapp-connector.md) * [Example application with full styling](https://github.com/bochaco/react-mn-wallet-connect) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Proof server Midnight uses zero-knowledge (ZK) cryptography to enable shielded transactions and data protection. An essential element of this architecture is ZK functionality provided by a Midnight *proof server*, which generates proofs locally that are verified on-chain. The information that a DApp sends to the proof server includes private data, such as details of token ownership or a DApp's private state. To protect your data, you should access only a local proof server, or perhaps one on a remote machine that you control, over an encrypted channel. This guide shows you how to run the proof server locally in order to process transactions on the Midnight Network. The wallet communicates with the proof server to invoke ZK functionality and generate ZK proofs for your transactions. This guide is aimed at Midnight Network users, rather than DApp Builders. ## Install Docker Desktop[​](#install-docker-desktop "Direct link to Install Docker Desktop") If you don't have Docker, then download and install Docker for your operating system (macOS, Windows, or Linux): New users might need to set up an account. ## Install the proof server[​](#install-the-proof-server "Direct link to Install the proof server") Docker hosts completed code in Images. The Midnight proof server is available as a Docker Image. 1. Inside Docker Desktop, use the search bar to locate `midnightntwrk/proof-server:latest`. 2. Pull the image. After pulling the image, the code for the proof server is hosted in a Container in Docker Desktop. ## Start the proof server[​](#start-the-proof-server "Direct link to Start the proof server") Start the proof server by clicking **Run** button in the same search result, or by navigating to your Containers and clicking the **Run** button there. To inspect the proof server, navigate to Containers and **View Details** -- there is no action required here, but you should see some output indicating that the server has started. The proof server listens on port 6300 and *this should not be changed*. ## Stop the proof server[​](#stop-the-proof-server "Direct link to Stop the proof server") To stop the proof server, simply stop the container. For processing transactions on the Midnight network, the proof server must be running, so if you have stopped it, start it again now. ## Your privacy[​](#your-privacy "Direct link to Your privacy") The proof server exists to protect your privacy. It does not open any network connections; it simply listens on its assigned port for requests from your wallet. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Security and best practices Use this guide to harden a Compact contract and the DApp around it. You can read its sections in any order: some explain a threat or mechanism, some walk through a single task and end with a test you run to prove it holds, and some give you lookup tables. Three adversaries shape the decisions throughout. A **chain observer** reads the public ledger. A **malicious prover** controls their own frontend and supplies every witness value. An **operator of off-chain infrastructure**, such as an indexer or proof server, sees the data you route to them. For the language-level security model behind these patterns, read [Smart contract security](/compact/smart-contract-security.md). ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") These apply to every procedure in this guide: * A compiled Compact contract to secure. If you are starting fresh, follow [build your first contract](/getting-started/hello-world.md). * The [Compact CLI](/getting-started/installation.md) installed, with `compact compile` working. * Node.js with [Vitest](https://vitest.dev/) and `@midnight-ntwrk/compact-runtime` for the verification tests. * Familiarity with witnesses and `disclose()`. If either is new, read [Smart contract security](/compact/smart-contract-security.md) first. ## The Midnight security threat model[​](#the-midnight-security-threat-model "Direct link to The Midnight security threat model") Every security control in a Compact contract defends against one of three adversaries. Knowing which one a given circuit faces tells you which control it needs. A **chain observer** reads the public ledger. Zero-knowledge proofs hide your witness data, but a transaction still reveals which circuit and contract you called, the arguments to ledger operations, any values you disclose, and the timing. The [On-chain visibility](#on-chain-visibility) reference lists exactly what is and is not exposed. A **malicious prover** controls their own frontend and supplies every witness value, including the result of `ownPublicKey()`. The protocol does not check those values against the wallet that signed the transaction, so the only thing constraining a lying prover is the set of `assert` statements in your circuit. Anything you do not constrain, the prover chooses. An **operator of off-chain infrastructure** sees what you send them. An indexer that holds your viewing key can read your shielded history, and a proof server processes your private witness inputs to build a proof. Both are trust decisions, covered in [Viewing keys](#viewing-keys) and [Proving and private data](#proving-and-private-data). ## On-chain visibility[​](#on-chain-visibility "Direct link to On-chain visibility") What a chain observer can and cannot see for any transaction. Consult it when deciding what a circuit may safely expose. | What the observer sees | Visible on-chain? | | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | Which exported circuit you called | Yes, the entry point is part of the transaction | | Which contract you called | Yes, the contract address is public | | Arguments to ledger operations (`Set` and `Map` keys and values, `Counter` amounts) | Yes | | Values you disclose into a public position (a ledger write, an exported-circuit return, or a contract-to-contract call) | Yes | | When the transaction landed on-chain | Yes, block timing is observable | | Witness function return values | No, unless you disclose them into a public position | | Internal circuit computation | No | | The leaf inserted into a `MerkleTree` or `HistoricMerkleTree` | No, this is the one ledger operation that hides its argument | Wrapping a value in `disclose()` does not publish it. `disclose()` clears the compiler's private-data check so the value may cross a public boundary; the value becomes visible only when it crosses one, through a ledger write, a return from an exported circuit, or a contract-to-contract call. ## Authenticating a caller with a derived identity[​](#authenticating-a-caller-with-a-derived-identity "Direct link to Authenticating a caller with a derived identity") Gate a circuit so only one caller can run it, by deriving the caller's identity from a secret they must know rather than trusting `ownPublicKey()`, which is a witness the prover controls. ### Procedure[​](#procedure "Direct link to Procedure") 1. Declare a secret witness so the caller's secret stays in private state: ``` pragma language_version 0.23.0; import CompactStandardLibrary; export ledger owner: Bytes<32>; witness secretKey(): Bytes<32>; ``` 2. Derive a public identity by hashing the secret with a domain separator. The hash is one-way, so publishing it reveals nothing about the secret: ``` circuit derivePublicKey(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "myapp:owner"), sk]); } ``` 3. Store the commitment once, at setup. Writing the derived identity to the ledger moves a private value into a public position, which is what requires `disclose()`: ``` export circuit claimOwnership(): [] { owner = disclose(derivePublicKey(secretKey())); } ``` 4. Gate the circuit by re-deriving the identity and asserting it matches. Only a caller who knows the secret can produce a matching hash: ``` export circuit withdraw(): [] { assert(derivePublicKey(secretKey()) == owner, "not owner"); // ... privileged action ... } ``` 5. Implement the witness in TypeScript, generating the secret with a cryptographically secure source and storing it in private state: ``` const sk = new Uint8Array(32); crypto.getRandomValues(sk); // never Math.random() export const witnesses = { secretKey: ({ privateState }) => [privateState, privateState.sk], }; ``` Never authenticate with ownPublicKey() `ownPublicKey()` is a witness. The prover chooses its return value, and the protocol does not check it against the signing wallet, so `assert(ownPublicKey().bytes == owner)` compares two prover-controlled values and is bypassable. It is only safe when you route a value *to* the caller, as the [shielded token tutorial](/tokens/shielded-token.md) does. Witness or circuit argument A witness is not the only way to keep the secret private. Circuit inputs are private by default too, so you can pass the secret as an argument and derive the same identity: ``` export circuit withdraw(sk: Bytes<32>): [] { assert(derivePublicKey(sk) == owner, "not owner"); } ``` A witness reads the secret from the contract's private state on the device; an argument lets the caller supply it per call. Both keep the secret off-chain. Choose the witness when the secret should persist with the contract's state, and the argument when the caller already holds it. ### Verification[​](#verification "Direct link to Verification") The owner succeeds, and the contract rejects an attacker who copies the stored key into a forged private state. access-control.test.ts ``` import { describe, it, expect, beforeEach } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract } from '../managed/access-control/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const key = (n) => { const a = new Uint8Array(32); a[31] = n; return a; }; const OWNER = key(1), ATTACKER = key(2); describe('access control', () => { let contract, ctx; beforeEach(() => { contract = new Contract({ secretKey: (w) => [w.privateState, w.privateState.sk] }); const ctor = contract.initialState(RT.createConstructorContext({ sk: OWNER }, COIN)); ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { sk: OWNER }); ctx = contract.impureCircuits.claimOwnership(ctx).context; }); it('lets the owner withdraw', () => { expect(() => contract.impureCircuits.withdraw(ctx)).not.toThrow(); }); it('rejects an attacker who forges the stored owner key', () => { const attackerCtx = { ...ctx, currentPrivateState: { sk: ATTACKER } }; expect(() => contract.impureCircuits.withdraw(attackerCtx)).toThrow('not owner'); }); }); ``` ``` ✓ access-control.test.ts > access control > lets the owner withdraw ✓ access-control.test.ts > access control > rejects an attacker who forges the stored owner key Test Files 1 passed (1) Tests 2 passed (2) ``` ## Restricting a circuit to a group[​](#restricting-a-circuit-to-a-group "Direct link to Restricting a circuit to a group") Let any member of a group run a circuit without revealing which member, by verifying a Merkle membership proof and binding it to the caller so no one else can replay it. ### Prerequisites[​](#prerequisites-1 "Direct link to Prerequisites") * The derived-identity pattern from [Authenticating a caller with a derived identity](#authenticating-a-caller-with-a-derived-identity). ### Procedure[​](#procedure-1 "Direct link to Procedure") 1. Store member identities in a `HistoricMerkleTree`, which hides which leaf a proof refers to and accepts proofs against earlier roots. Export the derivation so an admin can compute a member's identity to enroll it: ``` pragma language_version 0.23.0; import CompactStandardLibrary; export ledger members: HistoricMerkleTree<10, Bytes<32>>; export ledger actions: Counter; witness secretKey(): Bytes<32>; export circuit derivePublicKey(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "myapp:member"), sk]); } export circuit addMember(pk: Bytes<32>): [] { members.insert(disclose(pk)); } ``` 2. Verify a membership proof and bind it to the caller. The binding assert is the security-critical line: without it, anyone who observed a valid path in a public transaction could replay it: ``` export circuit act(path: MerkleTreePath<10, Bytes<32>>): [] { assert(members.checkRoot(disclose(merkleTreePathRoot<10, Bytes<32>>(path))), "not a member"); assert(path.leaf == derivePublicKey(secretKey()), "path not bound to caller"); actions.increment(1); } ``` A membership proof hides you only among the other members, so a tree with three leaves gives almost no privacy. Grow the set before you rely on it, and store commitments rather than guessable raw keys. When you only need to prove a property, disclose the boolean result, not the value: `disclose(age >= 18)`. Comparisons like `>=` work on `Uint`, not `Field`. See [Explicit disclosure](/compact/reference/explicit-disclosure.md). ### Verification[​](#verification-1 "Direct link to Verification") A member acts with their own path; the binding assert rejects a non-member who replays that path. group-access.test.ts ``` import { describe, it, expect, beforeEach } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract, ledger, pureCircuits } from '../managed/group-access/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const key = (n) => { const a = new Uint8Array(32); a[31] = n; return a; }; const ALICE = key(1), MALLORY = key(2); describe('group membership', () => { let contract, ctx, alicePath; beforeEach(() => { contract = new Contract({ secretKey: (w) => [w.privateState, w.privateState.sk] }); const ctor = contract.initialState(RT.createConstructorContext({ sk: ALICE }, COIN)); ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { sk: ALICE }); ctx = contract.impureCircuits.addMember(ctx, pureCircuits.derivePublicKey(ALICE)).context; alicePath = ledger(ctx.currentQueryContext.state) .members.findPathForLeaf(pureCircuits.derivePublicKey(ALICE)); }); it('lets a member act with their own path', () => { expect(() => contract.impureCircuits.act(ctx, alicePath)).not.toThrow(); }); it("rejects a non-member replaying a member's path", () => { const malloryCtx = { ...ctx, currentPrivateState: { sk: MALLORY } }; expect(() => contract.impureCircuits.act(malloryCtx, alicePath)).toThrow('path not bound to caller'); }); }); ``` ``` ✓ group-access.test.ts > group membership > lets a member act with their own path ✓ group-access.test.ts > group membership > rejects a non-member replaying a member's path Test Files 1 passed (1) Tests 2 passed (2) ``` ## Compact arithmetic behavior[​](#compact-arithmetic-behavior "Direct link to Compact arithmetic behavior") How Compact handles integer overflow and underflow. Unlike some languages, it does not silently wrap. | Operation | Behavior | Your responsibility | | --------------------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | Subtraction `a - b` where `b > a` | Aborts at runtime with `result of subtraction would be negative` | Assert bounds first so the failure carries a clear message | | Addition `a + b` | The result type widens beyond the operand width, so you cannot assign it back to a same-width field | Assert bounds, then narrow with a cast (`(a + b) as Uint<64>`), or store in a wider field | | Any circuit input | Private and unvalidated by default | Assert ranges, non-zero values, and state preconditions before use | ## Validating inputs before computing[​](#validating-inputs-before-computing "Direct link to Validating inputs before computing") Never compute on unchecked inputs. Compact fails safe on arithmetic, but you still validate to enforce your domain rules and to fail with a clear message. ### Procedure[​](#procedure-2 "Direct link to Procedure") 1. Recognize the built-in guard. A subtraction that would go negative aborts at runtime rather than wrapping: ``` pragma language_version 0.23.0; import CompactStandardLibrary; export ledger balance: Uint<64>; constructor() { balance = 5; } export circuit unsafeSub(amount: Uint<64>): [] { balance = balance - disclose(amount); } ``` 2. Assert your own preconditions so failures are explicit and enforce rules the language cannot know, such as domain limits: ``` export circuit safeSub(amount: Uint<64>): [] { const amt = disclose(amount); assert(amt <= balance, "insufficient balance"); balance = balance - amt; } ``` For the full set of validation patterns, see [input validation and access control](/compact/smart-contract-security.md#input-validation-and-access-control). For how addition and subtraction fail, see [Compact arithmetic behavior](#compact-arithmetic-behavior). ### Verification[​](#verification-2 "Direct link to Verification") The underflow aborts, the guarded circuit gives a clear error, and a valid amount applies. arithmetic.test.ts ``` import { describe, it, expect } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract, ledger } from '../managed/arithmetic/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const fresh = () => { const contract = new Contract({}); const ctor = contract.initialState(RT.createConstructorContext({}, COIN)); return { contract, ctx: RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, {}) }; }; describe('arithmetic safety', () => { it('traps on subtraction underflow instead of wrapping', () => { const { contract, ctx } = fresh(); expect(() => contract.impureCircuits.unsafeSub(ctx, 10n)) .toThrow('result of subtraction would be negative'); }); it('rejects an over-balance amount with a clear message', () => { const { contract, ctx } = fresh(); expect(() => contract.impureCircuits.safeSub(ctx, 10n)).toThrow('insufficient balance'); }); it('applies a valid subtraction', () => { const { contract, ctx } = fresh(); const r = contract.impureCircuits.safeSub(ctx, 3n); expect(ledger(r.context.currentQueryContext.state).balance).toBe(2n); }); }); ``` ``` ✓ arithmetic.test.ts > arithmetic safety > traps on subtraction underflow instead of wrapping ✓ arithmetic.test.ts > arithmetic safety > rejects an over-balance amount with a clear message ✓ arithmetic.test.ts > arithmetic safety > applies a valid subtraction Test Files 1 passed (1) Tests 3 passed (3) ``` ## Block-time predicates[​](#block-time-predicates "Direct link to Block-time predicates") The standard-library predicates for reasoning about block time. Each takes a `Uint<64>` count of seconds since the Unix epoch and returns a `Boolean`. There is no raw block-time accessor. | Predicate | Returns true when | | -------------------- | --------------------------------------------- | | `blockTimeLt(time)` | the current block time is before `time` | | `blockTimeLte(time)` | the current block time is at or before `time` | | `blockTimeGt(time)` | the current block time is after `time` | | `blockTimeGte(time)` | the current block time is at or after `time` | Block time advances one step per block, and the producer sets the timestamp within protocol-enforced bounds. Treat a time gate as accurate to the scale of blocks, not seconds, and never use block time as a randomness source. ## Enforcing a deadline[​](#enforcing-a-deadline "Direct link to Enforcing a deadline") Allow an action only before a cutoff time. ### Procedure[​](#procedure-3 "Direct link to Procedure") 1. Store the cutoff and mark it `sealed` so no later circuit can move it. A sealed field is set once, during construction: ``` pragma language_version 0.23.0; import CompactStandardLibrary; export sealed ledger deadline: Uint<64>; export ledger claimed: Boolean; constructor(deadlineTime: Uint<64>) { deadline = disclose(deadlineTime); claimed = false; } ``` 2. Gate the action on the block time. The node evaluates the predicate against the block that includes the transaction: ``` export circuit claim(): [] { assert(blockTimeLt(deadline), "expired"); claimed = true; } ``` For the available predicates, see [Block-time predicates](#block-time-predicates). ### Verification[​](#verification-3 "Direct link to Verification") Set the block time in the circuit context (the seventh argument of `createCircuitContext`) to exercise both sides of the deadline. deadline.test.ts ``` import { describe, it, expect } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract } from '../managed/deadline/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const DEADLINE = 2_000_000_000; // seconds since the epoch const claimAt = (time) => { const contract = new Contract({}); const ctor = contract.initialState(RT.createConstructorContext({}, COIN), BigInt(DEADLINE)); const ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, {}, undefined, undefined, time); return () => contract.impureCircuits.claim(ctx); }; describe('deadline', () => { it('allows the claim before the deadline', () => { expect(claimAt(DEADLINE - 100)).not.toThrow(); }); it('rejects the claim at or after the deadline', () => { expect(claimAt(DEADLINE + 100)).toThrow('expired'); }); }); ``` ``` ✓ deadline.test.ts > deadline > allows the claim before the deadline ✓ deadline.test.ts > deadline > rejects the claim at or after the deadline Test Files 1 passed (1) Tests 2 passed (2) ``` ## Preventing replay attacks[​](#preventing-replay-attacks "Direct link to Preventing replay attacks") Allow a one-time action to happen exactly once. A nullifier records that it has happened without revealing the secret behind it. ### Procedure[​](#procedure-4 "Direct link to Procedure") 1. Derive a nullifier from the secret with a domain-separated `persistentHash`, folding in a round number so the same secret can act once per round, and store used nullifiers in a `Set`: ``` pragma language_version 0.23.0; import CompactStandardLibrary; export ledger spent: Set>; witness secretKey(): Bytes<32>; circuit nullifier(round: Uint<64>, sk: Bytes<32>): Bytes<32> { const roundBytes = round as Field as Bytes<32>; return persistentHash>>([pad(32, "myapp:nul"), roundBytes, sk]); } ``` 2. Assert the nullifier is not already present, then insert it. A second attempt with the same round and secret produces the same nullifier and fails: ``` export circuit act(round: Uint<64>): [] { const nul = nullifier(round, secretKey()); assert(!spent.member(disclose(nul)), "already acted this round"); spent.insert(disclose(nul)); // ... one-time action ... } ``` The domain separator for a nullifier must differ from any commitment's, or the two hashes are equal for the same secret and an observer can link them. For ordering defenses against **front-running**, publish a `persistentCommit(move, rand)` first and reveal in a second transaction, protecting the reveal with a nullifier. See [the commitment/nullifier pattern](/concepts/how-midnight-works/keeping-data-private.md#the-commitmentnullifier-pattern) and [the bulletin board tutorial](/tutorials/bboard/smart-contract.md) for the sequence-counter variant. ### Verification[​](#verification-4 "Direct link to Verification") The contract rejects a replay in the same round; a new round succeeds. replay.test.ts ``` import { describe, it, expect } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract } from '../managed/replay/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const SK = (() => { const a = new Uint8Array(32); a[31] = 1; return a; })(); const setup = () => { const contract = new Contract({ secretKey: (w) => [w.privateState, w.privateState.sk] }); const ctor = contract.initialState(RT.createConstructorContext({ sk: SK }, COIN)); const ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { sk: SK }); return { contract, ctx: contract.impureCircuits.act(ctx, 1n).context }; }; describe('replay protection', () => { it('rejects a replay in the same round', () => { const { contract, ctx } = setup(); expect(() => contract.impureCircuits.act(ctx, 1n)).toThrow('already acted this round'); }); it('allows an action in a new round', () => { const { contract, ctx } = setup(); expect(() => contract.impureCircuits.act(ctx, 2n)).not.toThrow(); }); }); ``` ``` ✓ replay.test.ts > replay protection > rejects a replay in the same round ✓ replay.test.ts > replay protection > allows an action in a new round Test Files 1 passed (1) Tests 2 passed (2) ``` ## Rotating an owner key[​](#rotating-an-owner-key "Direct link to Rotating an owner key") Give a key holder a way to move to a new key. The witness secret lives only in local private state, so if it is lost or compromised, the on-chain commitment is permanent. Build the rotation path before you need it. ### Prerequisites[​](#prerequisites-2 "Direct link to Prerequisites") * The derived-identity pattern from [Authenticating a caller with a derived identity](#authenticating-a-caller-with-a-derived-identity). ### Procedure[​](#procedure-5 "Direct link to Procedure") 1. Add a rotation circuit in which the current owner proves control, then writes a new owner commitment. The incoming owner generates their own secret locally and shares only the derived public value, so no secret crosses the wire: ``` export circuit rotateOwner(newOwner: Bytes<32>): [] { assert(derivePublicKey(secretKey()) == owner, "not owner"); owner = disclose(newOwner); } ``` There is no recovery by default You cannot recover a witness secret from the chain. If the only holder of a role loses their secret and you built no rotation path or backup, you lose that role permanently. Decide your recovery model before you deploy: multiple authorized keys, a recovery circuit gated on a separate secret, or a threshold of guardians. ### Verification[​](#verification-5 "Direct link to Verification") After rotation, the new key acts and the old key no longer does. rotation.test.ts ``` import { describe, it, expect, beforeEach } from 'vitest'; import * as RT from '@midnight-ntwrk/compact-runtime'; import { Contract, pureCircuits } from '../managed/rotation/contract/index.js'; const COIN = '0'.repeat(64); const ADDR = RT.sampleContractAddress(); const key = (n) => { const a = new Uint8Array(32); a[31] = n; return a; }; const OLD = key(1), NEW = key(2); describe('key rotation', () => { let contract, ctx; beforeEach(() => { contract = new Contract({ secretKey: (w) => [w.privateState, w.privateState.sk] }); const ctor = contract.initialState(RT.createConstructorContext({ sk: OLD }, COIN)); ctx = RT.createCircuitContext(ADDR, COIN, ctor.currentContractState, { sk: OLD }); ctx = contract.impureCircuits.claimOwnership(ctx).context; ctx = contract.impureCircuits.rotateOwner(ctx, pureCircuits.derivePublicKey(NEW)).context; }); it('lets the new key act after rotation', () => { expect(() => contract.impureCircuits.withdraw({ ...ctx, currentPrivateState: { sk: NEW } })).not.toThrow(); }); it('rejects the old key after rotation', () => { expect(() => contract.impureCircuits.withdraw({ ...ctx, currentPrivateState: { sk: OLD } })).toThrow('not owner'); }); }); ``` ``` ✓ rotation.test.ts > key rotation > lets the new key act after rotation ✓ rotation.test.ts > key rotation > rejects the old key after rotation Test Files 1 passed (1) Tests 2 passed (2) ``` ## Durable and bounded on-chain state[​](#durable-and-bounded-on-chain-state "Direct link to Durable and bounded on-chain state") Two long-term properties can slip past you while a contract still works in testing. **Store only durable hashes.** Compact offers persistent and transient variants of its hash and commitment functions. The transient variants are circuit-optimized, and their algorithm may change between compiler versions, so a value stored on-chain today may not match a recomputation after an upgrade. Use `persistentHash` and `persistentCommit` for anything written to the ledger, and reserve the transient variants for in-circuit intermediate values. See [Cryptographic primitive selection](#cryptographic-primitive-selection). **Bound your growth.** Ledger collections grow forever and every entry is public. A nullifier `Set` gains an entry on each action and never shrinks; a `Map` keyed by user grows with your user base. For a long-lived contract, scope that growth rather than accumulating without limit: derive nullifiers per epoch so you can retire old sets, or key state so it can expire. Design the bound in from the start, because you cannot retroactively shrink public state. ## Cryptographic primitive selection[​](#cryptographic-primitive-selection "Direct link to Cryptographic primitive selection") Which hashing and commitment primitive to use. Store only the persistent variants on the ledger. | Function | Output | Stable across upgrades | Hides input without a guess | | --------------------- | ----------- | ---------------------- | ------------------------------------ | | `persistentHash` | `Bytes<32>` | Yes (SHA-256) | No, anyone can check a guessed input | | `persistentCommit` | `Bytes<32>` | Yes | Yes, randomness clears witness taint | | `transientHash` | `Field` | No | No | | `transientCommit` | `Field` | No | Yes, but do not store on-chain | Use `persistentCommit` when a value must be hidden and later revealed, and `persistentHash` for identities and nullifiers where binding is enough. Never reuse a commitment's randomness across values. ## Proving and private data[​](#proving-and-private-data "Direct link to Proving and private data") Generating a zero-knowledge proof requires your private witness values. The proof server performs arithmetic directly over those values, so whichever proof server does the proving receives them in the clear. This trust boundary often goes unnoticed because the proof itself reveals nothing; the machine that builds it sees everything. Running the proof server locally, in Docker on port 6300, keeps private inputs on your own machine, where no external party sees them. This is the safe default. A remote or shared proof server, by contrast, receives your full witness data to compute the proof. Transport encryption stops a network eavesdropper from reading the payload in transit, but the operator still decrypts and processes your private values. Choosing a remote server is a trust decision about the operator, not a transport setting. With wallet-delegated proving, your DApp hands the built proof preimage to the wallet, which builds the proof using whatever proof server it runs. Your DApp still computes the witness values itself; delegation only moves the proving step. Confirm where the wallet ultimately proves before you rely on it for sensitive data. ## Viewing keys[​](#viewing-keys "Direct link to Viewing keys") A viewing key is a wallet-level key, Bech32m-encoded and derived from your wallet seed separately from your spending key. It decrypts your shielded transaction data so software can display your balance and history, but it cannot spend. Because it decrypts your history, anyone who holds it can read your entire shielded transaction history. The Midnight indexer's `connect` mutation takes a viewing key and opens a session that scans the chain for your transactions, which is what makes connecting to a third-party indexer a trust decision. A well-behaved indexer stores connected viewing keys encrypted at rest, but you are still trusting the operator. There is no viewing-key rotation: a viewing key is bound to the wallet seed, and you cannot revoke it independently, so once you share it, assume the holder can read your history indefinitely. Never log, transmit, or persist a user's viewing key outside the wallet and the indexer it connects to, and run your own indexer for sensitive applications. ## Pre-deployment security checklist[​](#pre-deployment-security-checklist "Direct link to Pre-deployment security checklist") Work through this list before mainnet. Each item links to the module that explains it. * [ ] **Assert every assumption about witness data.** A witness value you do not constrain is a value the prover chooses. See [The Midnight security threat model](#the-midnight-security-threat-model). * [ ] **Validate inputs before you compute.** Check bounds, ranges, non-zero values, and state preconditions. See [Validating inputs before computing](#validating-inputs-before-computing). * [ ] **Test with a malicious private state.** Supply deliberately wrong witness values and confirm your asserts reject them. The [Battleship tutorial](/tutorials/bship/test-suite.md) shows a full adversarial suite. * [ ] **Audit every `disclose()`.** Confirm what becomes public, when, and that it is the minimum the circuit needs. * [ ] **Check your domain separators.** Every commitment and nullifier derivation uses a distinct domain string, and no commitment shares a domain with its nullifier. * [ ] **Store only durable hashes** and **bound your state growth.** See [Durable and bounded on-chain state](#durable-and-bounded-on-chain-state). * [ ] **Confirm error messages leak nothing.** An assert message must not embed private state. * [ ] **Provide a key-recovery path.** Confirm no role is permanently lockable by a single lost secret. See [Rotating an owner key](#rotating-an-owner-key). * [ ] **Decide where you prove.** Confirm private witness inputs are only sent to a proof server you trust. See [Proving and private data](#proving-and-private-data). * [ ] **Decide viewing-key handling.** Confirm you never log, transmit, or persist a user viewing key outside the wallet and its indexer. See [Viewing keys](#viewing-keys). * [ ] **Decide your upgrade-key custody.** If the contract is upgradeable, distribute control across independent parties. See [Contract updatability and the maintenance authority](/guides/deploy-and-operate.md#contract-updatability-and-the-maintenance-authority). * [ ] **Get an external review.** No amount of self-testing replaces a second set of eyes on a security-critical contract. ## Additional resources[​](#additional-resources "Direct link to Additional resources") * [Smart contract security](/compact/smart-contract-security.md): the language-level security model, sealed fields, and cryptographic primitives. * [Private data](/concepts/how-midnight-works/keeping-data-private.md): commitments, nullifiers, and Merkle trees in depth. * [Explicit disclosure](/compact/reference/explicit-disclosure.md): how the compiler tracks private data and when it requires `disclose()`. * [OpenZeppelin Compact contracts](/sdks/community/openzeppelin-compact-contracts.md): reference `Ownable`, `AccessControl`, and other modules built on the derived-identity pattern. Note that the library lacks a security audit. * [Test and debug](/compact/test-and-debug.md): broader testing strategies for Compact contracts. * [Deploying and operating a contract](/guides/deploy-and-operate.md): wiring the indexer and private-state providers your DApp uses, and maintaining the contract after deployment. --- # Windows Compact setup > For the complete documentation index, see [llms.txt](/llms.txt) This guide covers setting up the Midnight development environment on Windows using Windows Subsystem for Linux (WSL). We'll walk you through the essential setup steps, including installing and configuring WSL, Docker Desktop, and the Midnight Lace wallet. By the end of this tutorial, you'll have a development-ready environment for building DApps on the Midnight Network, running the proof server, and interacting with the network. ### Install Ubuntu[​](#install-ubuntu "Direct link to Install Ubuntu") Developing DApps for the Midnight network often requires compiling and running various components (like the proof server or complex scripts) that are traditionally Linux-based. The Windows Subsystem for Linux (WSL) is a critical component that allows you to run a native Linux environment directly within Windows without the overhead of a traditional virtual machine. Step-by-step installation: Open the Start Menu on your Windows desktop. Search for Windows PowerShell (or Command Prompt) and right-click on the result. Select **Run as administrator.** This elevation is necessary to install system-level features like WSL. ![Windows Start menu with PowerShell right-click menu showing Run as administrator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azunze475qiad8qvnmea.png) In the command terminal, enter the following streamlined installation command: ``` wsl --install -d ubuntu ``` ![PowerShell terminal executing the wsl installation command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udzzpfa7fmvnkerruifw.png) This command performs three primary functions automatically: It enables the required Windows features for WSL (Virtual Machine Platform and Windows Subsystem for Linux). It downloads and installs the recommended Ubuntu distribution (the default and most widely supported Linux environment). ![Ubuntu distribution download and installation progress in the terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/15y290h3vgsdliqmbc69.png) It restarts the necessary services. info The initial download and installation of the required components and the Ubuntu image can take anywhere from 5 to 15 minutes, depending on your internet connection and system speed. Do not close the window until the process is complete. After the installation process completes, a new Ubuntu terminal window will open automatically. You will be prompted to create a UNIX username and a password. ![Ubuntu terminal prompt for creating a new UNIX username and password](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ea6re5ha4k6d8z56cerz.png) note When entering your password, the characters will not be displayed on the screen for security reasons (this is standard Linux terminal behavior). Type your desired password carefully and press Enter. Once successfully configured, your new username will be displayed as part of your terminal prompt (for example, `yourusername@DESKTOP-XXXXXX:~$`).  ![Ubuntu terminal showing the successful configuration and user prompt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mj4xgis8a9jpgjth6gc5.png) This confirms that WSL is correctly installed and the Ubuntu distribution is ready for use. ### Verification and best practices[​](#verification-and-best-practices "Direct link to Verification and best practices") To ensure WSL is running the correct version, you can execute this command in the Windows PowerShell: ``` wsl -l -v ``` You should see a list showing Ubuntu and confirming its STATE is Running (or Stopped) and its VERSION is 2 (WSL 2 is required for optimal performance and Docker integration). ## Install and configure Docker desktop[​](#install-and-configure-docker-desktop "Direct link to Install and configure Docker desktop") Open your preferred web browser and navigate to the official **Docker** website at [docker.com/products/docker-desktop](https://www.docker.com/products/docker-desktop). ![Official Docker Desktop download page for Windows](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tbyf3h7vt6seaff0yuma.png) Look for the **Docker Desktop for Windows** download link. Ensure you download the installer that matches your CPU architecture (for example, **Windows - AMD64** for modern systems). Run the downloaded installer (for example, `Docker Desktop Installer.exe`). During the installation, make sure the box for **Use WSL 2 instead of Hyper-V** is checked. This is vital for Docker to integrate seamlessly with the Linux environment you just set up. Follow the prompts to complete the installation. A system restart may be required. After the reboot, launch **Docker Desktop** from your **Start Menu**. It will take a few moments to start up, showing the whale icon in your system tray. ### Verification and integration[​](#verification-and-integration "Direct link to Verification and integration") Once Docker Desktop is running, open the **Settings** menu (the gear icon). Click **Resources**, then navigate to the **WSL integration** tab. Ensure that the **Enable integration with my default WSL distro** option is toggled **ON**, and specifically verify that your **Ubuntu** distribution is enabled. This connection allows Docker to manage containers directly from your Linux terminal. ## Set up and run the midnight proof server[​](#set-up-and-run-the-midnight-proof-server "Direct link to Set up and run the midnight proof server") The **Midnight Proof Server** is the core component that your DApps will communicate with to execute zero-knowledge proofs and transactions. It is run via **Docker** for consistency. ### Download the Docker image[​](#download-the-docker-image "Direct link to Download the Docker image") Open your **Docker Desktop** application and navigate to the **Explore** section (or use the search field at the top). Search for `midnightntwrk/proof-server` and download the latest image. ![Docker Desktop Images tab showing the downloaded proof-server image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmmocxc6tumxqr7k4801.png) ### Run the proof server[​](#run-the-proof-server "Direct link to Run the proof server") To start the proof server, open your **Ubuntu** terminal and run the following command: ``` docker run -p 6300:6300 midnightntwrk/proof-server:8.1.0 -- midnight-proof-server -v ``` You should see output similar to: ``` actix_server::server: starting service: "actix-web-service-0.0.0.0:6300", workers: 14, listening on: 0.0.0.0:6300 ``` tip Keep this terminal window open. The proof server *must* stay active to compile and deploy contracts. ## Install the Compact compiler[​](#install-the-compact-compiler "Direct link to Install the Compact compiler") Compact is Midnight's smart contract language. Since you are using a Windows machine, you must install the compiler inside your **WSL Ubuntu terminal** to ensure it works with the rest of the Midnight toolchain. 1. Open your Ubuntu terminal (WSL). 2. Run the following command to install the Compact binaries: ``` curl --proto '=https' --tlsv1.2 -LsSf https://github.com/midnightntwrk/compact/releases/latest/download/compact-installer.sh | sh ``` 3. The installer script automatically updates your path. To apply these changes to your current session, reload your shell configuration: ``` source ~/.bashrc ``` 4. Verify the installation by checking the version: ``` compact --version ``` 5. Update to the latest version to ensure you have the most recent features: ``` compact update ``` ## Install the Compact VS Code extension[​](#install-the-compact-vs-code-extension "Direct link to Install the Compact VS Code extension") The Compact VS Code extension provides syntax highlighting and real-time error checking, which is essential for writing smart contracts. 1. Download the Compact VS Code extension VSIX package from the [releases page](https://raw.githubusercontent.com/midnight-ntwrk/releases/gh-pages/artifacts/vscode-extension/compact-0.2.13/compact-0.2.13.vsix). 2. Open VS Code. 3. Go to the **Extensions** view (press `Ctrl+Shift+X`), click the **...** (More Actions) menu at the top-right of the extensions pane, and select **Install from VSIX...**. 4. Select the `.vsix` file you just downloaded to complete the installation. ## Next steps[​](#next-steps "Direct link to Next steps") Now that your environment is ready, you can begin building. To get started and write your first smart contract, refer to the [hello world](/getting-started/hello-world.md) tutorial. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Set up Bun for Midnight development Bun is a modern JavaScript runtime and toolkit that can offer significantly faster performance compared to Node.js and npm. This guide walks you through using Bun with Midnight Network development, covering installation, configuration, compatibility considerations, best practices, and much more. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before starting this guide, ensure you have: * Basic knowledge of JavaScript/TypeScript * Familiarity with command-line interfaces * Understanding of package managers (npm, yarn) note Docker is not required for this tutorial. It's only needed when running actual Midnight proof servers. Here's what your complete project will look like by the end of this guide: ![Image](https://github.com/user-attachments/assets/3841162f-4485-47cc-98eb-4f9c1c786629) ## Install Bun[​](#install-bun "Direct link to Install Bun") In this section, you'll install Bun on your development machine. ### Install Bun on Mac[​](#install-bun-on-mac "Direct link to Install Bun on Mac") 1. Run the command below: ``` curl -fsSL https://bun.sh/install | bash ``` This script: * Downloads the appropriate Bun binary for your system. * Installs it to `~/.bun/bin`. 2. Verify the installation: Close and reopen your terminal, then run: ``` bun --version ``` Example of expected output: ![Image](https://github.com/user-attachments/assets/2d817253-4b67-4c07-8562-c02a3db0e643) If bun --version returns "command not found." manually add Bun to your PATH. ``` export PATH="$HOME/.bun/bin:$PATH” ``` ### Install Bun on linux or WSL[​](#install-bun-on-linux-or-wsl "Direct link to Install Bun on linux or WSL") Follow the steps below to install Bun on Linux or Windows Subsystem for Linux (WSL). 1. Install required dependencies Bun’s installer requires unzip to extract the binary. ``` sudo apt update sudo apt install unzip -y ``` 2. Install Bun Run the official Bun installation script: ``` curl -fsSL https://bun.sh/install | bash ``` 3. Reload your shell configuration Update your environment so the bun command is available: ``` source ~/.bashrc ``` 4. Verify the installation ``` bun --version ``` You should see the installed Bun version printed to the terminal. 5. Fix “command not found” (if needed) If bun is not found, add Bun’s install directory to your `PATH`: ``` export PATH="$HOME/.local/bin:$PATH" ``` ## Install using the installer script[​](#install-using-the-installer-script "Direct link to Install using the installer script") Here, you will install the Compact compiler. This is a standalone tool (separate from Bun) used to turn Compact smart contracts (written in the Compact language) into code that can run on the Midnight blockchain. 1. Install using the Compact installer: ``` curl --proto '=https' --tlsv1.2 -LsSf \ https://github.com/midnightntwrk/compact/releases/latest/download/compact-installer.sh | sh ``` By default, the installer places the compact binary in `$HOME/.local/bin` 2. Update the compiler After installation, update the Compact compiler to the version used in this tutorial: ``` compact update ``` 3. Verify the installation Confirm that Compact is installed and correctly configured: ``` compact check ``` If the installation is successful, you should see output similar to the following: ``` compact: aarch64-darwin -- Up to date -- 0.31.0 ``` 4. Fix “command not found” (PATH issue) If you see an error such as: ``` compact: command not found ``` it means the directory where Compact was installed `($HOME/.local/bin)` is not included in your PATH. Add it to your current terminal session: ``` export PATH="$HOME/.local/bin:$PATH" ``` ## Install Midnight packages with Bun[​](#install-midnight-packages-with-bun "Direct link to Install Midnight packages with Bun") With both Bun and the Compact compiler installed, you can now create a Midnight application project. 1. Initialize a new project: ``` mkdir my-midnight-app cd my-midnight-app bun init -y ``` This creates a basic `package.json`. 2. Create the required directories: The project requires separate folders for smart contracts and application source code. ``` mkdir src contracts ``` 3. Install the Midnight runtime package Install a specific version to avoid compatibility issues: ``` bun add @midnight-ntwrk/compact-runtime@0.16.0 ``` This gives you everything you need to: * Run your smart contracts * Manage your app's data * Work with zero-knowledge proofs * Get type definitions for TypeScript info Always refer to the [compatibility matrix](/relnotes/support-matrix.md) for the correct version of the runtime package to install. 4. Update the `tsconfig.json` file: tsconfig.json ``` { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "node", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "resolveJsonModule": true }, "include": ["src/**/*"] } ``` This configuration ensures: * Bun can resolve imports correctly. * TypeScript compiles cleanly. * Midnight’s runtime packages work without extra setup. ## Configure the project[​](#configure-the-project "Direct link to Configure the project") Update your `package.json` with the Bun-specific scripts below: package.json ``` "scripts": { "dev": "bun run --hot src/index.ts", "start": "bun run dist/index.js", "test": "bun test", "install:midnight": "bun install", "compile:contract": "compact compile contracts/message.compact contracts/managed", "build:contract": "bun run compile:contract && bun build src/index.ts --outdir dist" }, ``` Script explanations: * dev: Runs the app in development mode with hot reload on src/index.ts. * start: Runs the compiled production app from dist/index.js. * test: Runs all tests using Bun’s test runner. * install:midnight: Installs project dependencies with Bun. * compile:contract: Compiles the Compact smart contract `message.compact` into the contracts/managed output directory. * build:contract: First compiles the smart contract, then bundles the app entry file into the dist folder for production. ## Create smart contract with Compact[​](#create-smart-contract-with-compact "Direct link to Create smart contract with Compact") In this section, you will create a simple Compact smart contract that allows you to store and read a message on the Midnight blockchain. Then, you will compile it so it can be used in your TypeScript/Bun application. 1. Create the smart contract file. Create a file named `message.compact` in the contracts directory: ``` touch contracts/message.compact ``` 2. Add the code below to the file: message.compact ``` pragma language_version 0.23; import CompactStandardLibrary; // Public ledger state - visible on blockchain export ledger message: Opaque<"string">; // Circuit to store a message on the blockchain // The message will be publicly visible export circuit storeMessage(customMessage: Opaque<"string">): [] { message = disclose(customMessage); } ``` Explanation: * `pragma language_version 0.23;` Specifies the exact Compact compiler version required for this smart contract. Using version 0.23 ensures compatibility with the runtime version 0.16.0 you installed earlier. * `import CompactStandardLibrary;` Loads standard functions and types provided by Midnight for contracts. * `export ledger message: Opaque<"string">;` Declares a public state variable called `message` on the blockchain. Its value will be visible to everyone. * `export circuit storeMessage(customMessage: Opaque<"string">): [] { ... }` Defines a function (circuit) to store a message on the blockchain. `disclose()` makes the message publicly readable. 3. Compile with compact ``` compact compile contracts/message.compact contracts/managed ``` ![Image](https://github.com/user-attachments/assets/b53eb5ae-3f37-489d-8b54-968f84748e7a) What this does: * Converts the human-readable `.compact` contract into a compiled module that your application can interact with. * Saves the compiled contract in `contracts/managed`, making it ready for integration with your Bun/TypeScript app. ## Integrate compiled smart contracts with Bun[​](#integrate-compiled-smart-contracts-with-bun "Direct link to Integrate compiled smart contracts with Bun") Now that your Compact contracts are compiled, the next step is to interact with them from a Bun-powered TypeScript application. Here you’ll create a client that simulates storing and reading a message from your Midnight contract. 1. Create `src/message-client.ts` ``` touch src/message-client.ts ``` Add the following code: message-client.ts ``` import { Contract, ledger } from "../contracts/managed/contract/index.js"; export class MessageClient { private contract: Contract; constructor() { this.contract = new Contract({}); } async storeMessage(customMessage: string) { console.log(`📦 (Simulated) Storing message: "${customMessage}"`); // Real implementation needs proper Midnight context return { success: true, message: customMessage }; } async getMessage() { console.log("📥 (Simulated) Fetching message from ledger..."); return "Hello Midnight!"; } } ``` What this does: * Creates a `MessageClient` class. * Loads your compiled Compact contract. * Provides two methods: * `storeMessage()`: simulates writing data. * `getMessage()`: simulates reading data. * Keeps things simple while preserving the project structure required by real Midnight apps. 2. Create `src/index.ts` This file will serve as your application entry point. ``` touch src/index.ts ``` Add the following code: index.ts ``` import { MessageClient } from "./message-client"; async function main() { console.log("🚀 Starting Midnight Message App..."); const client = new MessageClient(); console.log("📝 Storing message..."); await client.storeMessage("Hello Midnight!"); console.log("📖 Reading message..."); const message = await client.getMessage(); console.log("✅ Message:", message); } main().catch(console.error); ``` ### What this file does:[​](#what-this-file-does "Direct link to What this file does:") * Boot your Midnight app * Creates an instance of `MessageClient` * Calls the store and retrieves functions * Prints the results nicely in your terminal 3. Run the app with Bun: ``` bun run --hot src/index.ts ``` ![Image](https://github.com/user-attachments/assets/845d6cbf-fcf8-42e9-bfe7-a63a6859175a) ## Known limitations and workarounds[​](#known-limitations-and-workarounds "Direct link to Known limitations and workarounds") While Bun offers significant performance improvements, there are some limitations you should be aware of when building Midnight applications. Here are the common issues and how to work around them. ### Native module compatibility[​](#native-module-compatibility "Direct link to Native module compatibility") Issue: some npm packages with native Node.js addons may not work correctly with Bun. Workaround: ``` # If a package fails, try running it with Node.js compatibility mode bun --bun run your-script.ts # Or fall back to Node.js for specific scripts node your-script.js ``` ### Package manager lock files[​](#package-manager-lock-files "Direct link to Package manager lock files") Issue: mixing Bun and npm in the same project can cause conflicts with lock files. Workaround: ``` # Pick one and stick with it. If using Bun, remove npm files rm package-lock.json # If using npm, remove Bun files rm bun.lock ``` tip Choose one package manager for your project and have your team use only that one. ### Environment variables[​](#environment-variables "Direct link to Environment variables") Issue: bun automatically handles `.env` files, which might cause unexpected behavior if you're using other environment variable tools. Workaround: ``` # Bun loads .env automatically, no library needed# If you need to disable this: bun --env-file= run your-script.ts # Or specify a different env file: bun --env-file=.env.production run your-script.ts ``` ## Migration guide (npm → Bun)[​](#migration-guide-npm--bun "Direct link to Migration guide (npm → Bun)") If your Midnight project was originally set up using Node.js + npm, you can migrate to Bun with just a few steps. This guide walks you through the process safely and cleanly. 1. Install Bun Make sure Bun is installed on your system. To check ``` bun --version ``` If not found, go to this step and [install Bun](#install-bun). 2. Remove npm Artifacts: ``` cd your-midnight-project rm -rf node_modules package-lock.json ``` warning Back up your `package-lock.json` first if you need to revert. 3. Install dependencies with Bun: ``` bun install ``` 4. Verify the Migration Test that your application works correctly with Bun: ``` bun run dev ``` ## Troubleshoot common issues[​](#troubleshoot-common-issues "Direct link to Troubleshoot common issues") 1. Module Not Found Errors Problem: ``` bun run --hot src/index.ts ``` Cannot find module `'@midnight-ntwrk/compact-runtime’` Solution: ``` bun add @midnight-ntwrk/compact-runtime@0.16.0 ``` 2. Version mismatch errors Problem: ``` CompactError: Version mismatch: compiled code expects 0.16.0, runtime is 0.9.0 ``` note The Compact compiler and runtime versions must match exactly. Always check [version compatibility](/relnotes/support-matrix.md) before compiling. Solution: Install the matching runtime version: ``` bun add @midnight-ntwrk/compact-runtime@0.16.0 ``` Then recompile your smart contracts: ``` compact compile contracts/message.compact contracts/managed ``` 3. Compact compiler language version errors Problem: ``` Exception: message.compact line 1 char 1: language version 0.22.0 mismatch ``` Solution: Update your smart contract to use the exact language version: ``` pragma language_version 0.23; ``` note Using an exact version number (such as 0.22) instead of a range prevents compatibility issues with different compiler versions. 4. Compact compiler installation issues Problem: The Compact compiler fails to install or doesn't work after installation. Solutions: * Verify the installer script ran successfully: ``` compact --version ``` * If the command isn't found, manually add it to your PATH: ``` export PATH="$HOME/.compact/bin:$PATH" ``` * Try reinstalling: ``` curl --proto '=https' --tlsv1.2 -LsSf \ https://github.com/midnightntwrk/compact/releases/latest/download/compact-installer.sh | sh ``` ## Next steps[​](#next-steps "Direct link to Next steps") Now that you have Bun installed and configured, you can start building DApps on Midnight. See the following guides for more information: * [DApp connector](/api-reference/dapp-connector.md) * [Deploy a contract](/guides/deploy-and-operate.md) * [Interact with a contract](/guides/interact-with-mn-app) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Decode 1010 transaction rejection errors Resolve `1010 Invalid Transaction` responses by decoding the inner `Custom error: N` value into a Midnight ledger error variant. ## Understand the cause of the error[​](#understand-the-cause-of-the-error "Direct link to Understand the cause of the error") When you submit a transaction to a Midnight node, the JSON-RPC layer may reject it with code `1010`: ``` { "code": 1010, "message": "Invalid Transaction", "data": "Custom error: 155" } ``` Code `1010` itself is a [Substrate](https://github.com/paritytech/polkadot-sdk/tree/master/substrate) envelope, not a Midnight-specific error. It signals that the node's transaction pool rejected the extrinsic. The actionable signal is the `N` in `Custom error: N`, which is a `u8` (0–255) corresponding to a `LedgerApiError` variant defined by the Midnight node. Two layers, one error The `1010` is inherited from Substrate. The inner `u8` is Midnight's. To diagnose the problem, you must decode the `u8`. ## Extract the inner u8[​](#extract-the-inner-u8 "Direct link to Extract the inner u8") The inner `u8` is embedded in the `data` field of the RPC error response. Use the steps below to extract it from common client environments. 1 ### Capture the full RPC response[​](#capture-the-full-rpc-response "Direct link to Capture the full RPC response") Capture the complete error response, not just the message string. Many wallet libraries and CLI wrappers truncate the `data` field by default. * JavaScript * cURL ``` try { await api.tx.someCall().signAndSend(account); } catch (err) { console.error(JSON.stringify(err, null, 2)); } ``` ``` curl -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"author_submitExtrinsic","params":["0x..."]}' \ http://localhost:9944 ``` 2 ### Read the trailing integer in the data field[​](#read-the-trailing-integer-in-the-data-field "Direct link to Read the trailing integer in the data field") The `data` field ends with `Custom error: N` where `N` is the variant code: ``` "data": "Custom error: 155" ``` In this example, `N` is `155`. 3 ### Look up the variant[​](#look-up-the-variant "Direct link to Look up the variant") Use the [variant tables](#look-up-the-variant) below to map the `u8` to its ledger error name and category. Variant codes change between releases Variant numbering is defined by the Midnight node and may change across releases. For example, `168 FeeCalculation` was retired and replaced by `155 FeeCalculationError`. Always cross-reference the variant against the [release notes](/relnotes/node.md) for the node version your network is running. ## Look up the variant[​](#look-up-the-variant-1 "Direct link to Look up the variant") The tables below list every `LedgerApiError` variant currently emitted by the Midnight node, grouped by category. Each row shows the `u8`, the variant name, and the meaning. Use the `Custom error: N` value extracted in the previous step to find the corresponding row. ### Deserialization errors (0–11)[​](#deserialization-errors-011 "Direct link to Deserialization errors (0–11)") The node could not decode an input from its serialized form. The transaction is rejected before any ledger logic runs. **Show full table** | Code | Variant | | ---- | ----------------------------- | | 0 | NetworkId | | 1 | Transaction | | 2 | LedgerState | | 3 | ContractAddress | | 4 | PublicKey | | 5 | VersionedArenaKey | | 6 | UserAddress | | 7 | TypedArenaKey | | 8 | SystemTransaction | | 9 | DustPublicKey | | 10 | CNightGeneratesDustActionType | | 11 | CNightGeneratesDustEvent | ### Serialization errors (50–63)[​](#serialization-errors-5063 "Direct link to Serialization errors (50–63)") The node could not encode a value to its serialized form. These typically indicate an internal inconsistency rather than a client error. **Show full table** | Code | Variant | | ---- | ------------------------ | | 50 | TransactionIdentifier | | 51 | LedgerState | | 52 | LedgerParameters | | 53 | ContractAddress | | 54 | ContractState | | 55 | ContractStateToJson | | 56 | ZswapState | | 57 | UnknownType | | 58 | MerkleTreeDigest | | 59 | VersionedArenaKey | | 60 | TypedArenaKey | | 61 | CNightGeneratesDustEvent | | 62 | SystemTransaction | | 63 | ArenaHash | ### Invalid transactions (100–109, 193–200, 239–250)[​](#invalid-transactions-100109-193200-239250 "Direct link to Invalid transactions (100–109, 193–200, 239–250)") The transaction is structurally valid but conflicts with current ledger state. These are the most common rejections in production traffic. **Show full table** | Code | Variant | | ------- | ------------------------------------------------- | | 100 | EffectsMismatch | | 101 | ContractAlreadyDeployed | | 102 | ContractNotPresent | | 103 | Zswap | | 104 | Transcript | | 105 | InsufficientClaimable | | 106 | VerifierKeyNotFound | | 107 | VerifierKeyAlreadyPresent | | 108 | ReplayCounterMismatch | | 109 | UnknownError | | ~~193~~ | ~~ReplayProtectionViolation~~ *(Retired)* | | 194 | BalanceCheckOutOfBounds | | 195 | InputNotInUtxos | | 196 | DustDoubleSpend | | 197 | DustDeregistrationNotRegistered | | 198 | GenerationInfoAlreadyPresent | | 199 | InvariantViolation | | 200 | RewardTooSmall | | 239 | Zswap.Invalid.NullifierAlreadyPresent | | 240 | Zswap.Invalid.CommitmentAlreadyPresent | | 241 | Zswap.Invalid.UnknownMerkleRoot | | 242 | ReplayProtectionViolation.IntentTtlExpired | | 243 | ReplayProtectionViolation.IntentTtlTooFarInFuture | | 244 | ReplayProtectionViolation.IntentAlreadyExists | | 248 | DivideByZero | | 249 | Invalid.MerkleTreeError | | 250 | Zswap.Invalid.MerkleTreeError | ### Malformed transactions (110–139, 166–192, 212–238)[​](#malformed-transactions-110139-166192-212238 "Direct link to Malformed transactions (110–139, 166–192, 212–238)") The transaction failed structural or cryptographic validation. The submitting client should treat these as bugs in transaction construction or signing. **Show full table** | Code | Variant | | ------- | ----------------------------------------------------- | | 110 | VerifierKeyNotSet | | 111 | TransactionTooLarge | | 112 | VerifierKeyTooLarge | | 113 | VerifierKeyNotPresent | | 114 | ContractNotPresent | | 115 | InvalidProof | | 116 | BindingCommitmentOpeningInvalid | | 117 | NotNormalized | | 118 | FallibleWithoutCheckpoint | | 119 | ClaimReceiveFailed | | 120 | ClaimSpendFailed | | 121 | ClaimNullifierFailed | | 122 | ClaimCallFailed | | 123 | InvalidSchnorrProof | | 124 | UnclaimedCoinCom | | 125 | UnclaimedNullifier | | 126 | Unbalanced | | 127 | Zswap | | 128 | BuiltinDecode | | 129 | GuaranteedLimit | | 130 | MergingContracts | | 131 | CantMergeTypes | | 132 | ClaimOverflow | | 133 | ClaimCoinMismatch | | 134 | KeyNotInCommittee | | 135 | InvalidCommitteeSignature | | 136 | ThresholdMissed | | 137 | TooManyZswapEntries | | 138 | BalanceCheckOverspend | | 139 | UnknownError | | 166 | InvalidNetworkId | | 167 | IllegallyDeclaredGuaranteed | | ~~168~~ | ~~FeeCalculation~~ *(Retired)* | | 169 | InvalidDustRegistrationSignature | | 170 | InvalidDustSpendProof | | 171 | OutOfDustValidityWindow | | 172 | MultipleDustRegistrationsForKey | | 173 | InsufficientDustForRegistrationFee | | 174 | MalformedContractDeploy | | 175 | IntentSignatureVerificationFailure | | 176 | IntentSignatureKeyMismatch | | 177 | IntentSegmentIdCollision | | 178 | IntentAtGuaranteedSegmentId | | 179 | UnsupportedProofVersion | | 180 | GuaranteedTranscriptVersion | | 181 | FallibleTranscriptVersion | | ~~182~~ | ~~TransactionApplicationError~~ *(Retired)* | | 183 | BalanceCheckOutOfBounds | | 184 | BalanceCheckConversionFailure | | 185 | PedersenCheckFailure | | ~~186~~ | ~~EffectsCheckFailure~~ *(Retired)* | | ~~187~~ | ~~DisjointCheckFailure~~ *(Retired)* | | ~~188~~ | ~~SequencingCheckFailure~~ *(Retired)* | | 189 | InputsNotSorted | | 190 | OutputsNotSorted | | 191 | DuplicateInputs | | 192 | InputsSignaturesLengthMismatch | | 212 | EffectsCheck.RealCallsSubsetCheckFailure | | 213 | EffectsCheck.AllCommitmentsSubsetCheckFailure | | 214 | EffectsCheck.RealUnshieldedSpendsSubsetCheckFailure | | 215 | EffectsCheck.ClaimedUnshieldedSpendsUniquenessFailure | | 216 | EffectsCheck.ClaimedCallsUniquenessFailure | | 217 | EffectsCheck.NullifiersNeqClaimedNullifiers | | 218 | EffectsCheck.CommitmentsNeqClaimedShieldedReceives | | 219 | SequencingCheck.CallSequencingViolation | | 220 | SequencingCheck.SequencingCorrelationViolation | | 221 | SequencingCheck.GuaranteedInFallibleContextViolation | | 222 | SequencingCheck.FallibleInGuaranteedContextViolation | | 223 | SequencingCheck.CausalityConstraintViolation | | 224 | SequencingCheck.CallHasEmptyTranscripts | | 225 | DisjointCheck.ShieldedInputsDisjointFailure | | 226 | DisjointCheck.ShieldedOutputsDisjointFailure | | 227 | DisjointCheck.UnshieldedInputsDisjointFailure | | 228 | TransactionApplication.IntentTtlExpired | | 229 | TransactionApplication.IntentTtlTooFarInFuture | | 230 | TransactionApplication.IntentAlreadyExists | | 231 | FeeCalculation.OutsideTimeToDismiss | | 232 | FeeCalculation.BlockLimitExceeded | | 233 | MalformedContractDeploy.NonZeroBalance | | 234 | MalformedContractDeploy.IncorrectChargedState | | 235 | Zswap.Malformed.InvalidProof | | 236 | Zswap.Malformed.ContractSentCiphertext | | 237 | Zswap.Malformed.NonDisjointCoinMerge | | 238 | Zswap.Malformed.NotNormalized | ### Infrastructure errors (150–157, 165)[​](#infrastructure-errors-150157-165 "Direct link to Infrastructure errors (150–157, 165)") The node could not complete an internal operation, such as a ledger lookup or fee calculation. These are not caused by the submitted transaction. **Show full table** | Code | Variant | | ---- | ----------------------------- | | 150 | LedgerCacheError | | 151 | NoLedgerState | | 152 | LedgerStateScaleDecodingError | | 153 | ContractCallCostError | | 154 | BlockLimitExceededError | | 155 | FeeCalculationError | | 156 | ContractNotPresent | | 157 | BeneficiaryNotFound | | 165 | GetTransactionContextError | ### System transactions (201–211, 245–247)[​](#system-transactions-201211-245247 "Direct link to System transactions (201–211, 245–247)") The node rejected a system-level transaction such as a payout or treasury operation. These are typically only seen by validators or block producers. **Show full table** | Code | Variant | | ------- | ----------------------------------------------------------------- | | 201 | IllegalPayout | | 202 | InsufficientTreasuryFunds | | 203 | CommitmentAlreadyPresent | | 204 | UnknownError | | ~~205~~ | ~~ReplayProtectionFailure~~ *(Retired)* | | 206 | IllegalReserveDistribution | | 207 | GenerationInfoAlreadyPresent | | 208 | InvalidBasisPoints | | 209 | InvariantViolation | | 210 | TreasuryDisabled | | 211 | MerkleTreeError | | 245 | SystemTransaction.ReplayProtectionFailure.IntentTtlExpired | | 246 | SystemTransaction.ReplayProtectionFailure.IntentTtlTooFarInFuture | | 247 | SystemTransaction.ReplayProtectionFailure.IntentAlreadyExists | ### Host API error (255)[​](#host-api-error-255 "Direct link to Host API error (255)") A reserved variant indicating that the node's host API surfaced an error not covered by the categories above. **Show full table** | Code | Variant | | ---- | ------------ | | 255 | HostApiError | ## Common causes and fixes[​](#common-causes-and-fixes "Direct link to Common causes and fixes") The following variants account for the majority of `1010` errors. **155 FeeCalculationError** — fee calculation failed for the submitted transaction Most often caused by stale fee estimates or an outdated runtime client. Refresh the client's view of network fees and resubmit. If the error persists, verify that your runtime packages match the values in the [release compatibility matrix](/relnotes/support-matrix.md). **154 BlockLimitExceededError** — the transaction would exceed the block resource limits Reduce the number of intents, calls, or similar in the transaction. For batched operations, split the work across multiple transactions. **108 ReplayCounterMismatch / 193 ReplayProtectionViolation** — replay protection rejected the transaction Either the replay counter is stale or the intent's TTL window has elapsed. Re-fetch the current counter and rebuild the transaction. Variants `242`–`244` and `228`–`230` give finer-grained reasons (TTL expired, TTL too far in the future, intent already exists). **115 InvalidProof / 235 Zswap.Malformed.InvalidProof** — a zero-knowledge proof failed verification Confirm that the proof server is running a version compatible with the node and SDK. See [run a proof server](/guides/run-proof-server.md) and the [release compatibility matrix](/relnotes/support-matrix.md). **166 InvalidNetworkId** — the transaction was constructed for a different network Verify that the SDK and wallet are configured for the same network ID as the node you are submitting to (for example, `Preprod` vs `TestNet02`). **126 Unbalanced / 138 BalanceCheckOverspend** — the transaction's inputs and outputs do not balance The wallet attempted to spend more than the available coin set permits, or change outputs were miscalculated. Re-sync the wallet and rebuild the transaction. ## When 1010 has no inner u8[​](#when-1010-has-no-inner-u8 "Direct link to When 1010 has no inner u8") If the response contains `code: 1010` but no `Custom error: N` substring, the rejection happened in upstream Substrate validation rather than Midnight ledger logic. The most common causes are: * **Bad signature**: the signing key does not match the sender, or the payload was altered after signing. * **Stale era**: the mortal era window has passed. Re-fetch the current block hash and rebuild the transaction. * **Wrong nonce**: the account nonce on the node does not match the value used when signing. Query the current nonce and resubmit. These rejections are not represented in the `LedgerApiError` tables because they never reach the ledger. ## Verify the fix[​](#verify-the-fix "Direct link to Verify the fix") After identifying and addressing the variant, resubmit the transaction and confirm it is accepted: ``` # Re-submit and observe the response curl -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"author_submitExtrinsic","params":["0x..."]}' \ http://localhost:9944 ``` A successful submission returns a transaction hash rather than an error envelope. ## Get help[​](#get-help "Direct link to Get help") If you cannot identify the variant or the rejection persists after applying the fixes above: * **Confirm the node version**: Variant numbering changes across releases. Check the [node release notes](/relnotes/node.md) for the version your network is running. * **Check the compatibility matrix**: Verify the proof server, runtime, and SDK match the supported set in the [release compatibility matrix](/relnotes/support-matrix.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Fix package repository access failures Resolve 403 Forbidden errors encountered when installing Midnight packages. ## Understand the cause of the error[​](#understand-the-cause-of-the-error "Direct link to Understand the cause of the error") When installing Midnight packages, you might encounter a 403 Forbidden error. This error typically appears when your npm configuration points to an incorrect registry or when network restrictions block access: ``` npm install @midnight-ntwrk/compact-runtime npm ERR! code E403 npm ERR! 403 Forbidden - GET https://registry.npmjs.org/@midnight-ntwrk/compact-runtime npm ERR! 403 In most cases, you or one of your dependencies are requesting npm ERR! 403 a package version that is forbidden by your security policy ``` The following solutions address the most common causes of this error, starting with the simplest fix. ## Solution 1: Reset npm registry[​](#solution-1-reset-npm-registry "Direct link to Solution 1: Reset npm registry") The most common cause is an npm configuration pointing to the wrong registry. Reset the npm registry to the default public npm registry to resolve this issue. 1 ### Check current registry[​](#check-current-registry "Direct link to Check current registry") Check which registry npm is currently configured to use: ``` npm config get registry ``` If the output differs from `https://registry.npmjs.org/`, then the registry configuration is incorrect and needs resetting. 2 ### Reset to default registry[​](#reset-to-default-registry "Direct link to Reset to default registry") Reset the npm registry configuration to the default public registry, remove any scoped registry settings, and clear the npm cache: ``` npm config set registry https://registry.npmjs.org/ npm config delete @midnight-ntwrk:registry npm cache clean --force ``` 3 ### Test installation[​](#test-installation "Direct link to Test installation") ``` npm install @midnight-ntwrk/compact-runtime ``` **Verification**: Package installs successfully without errors. ## Solution 2: Fix VPN and proxy issues[​](#solution-2-fix-vpn-and-proxy-issues "Direct link to Solution 2: Fix VPN and proxy issues") If resetting the registry does not resolve the issue, VPN connections or corporate proxy servers may be blocking npm access. Try these steps to configure npm to work with your network setup. 1 ### Disable VPN temporarily[​](#disable-vpn-temporarily "Direct link to Disable VPN temporarily") Corporate Networks On corporate networks, disabling a VPN connection may not be permitted. Disconnect from the VPN and test: ``` npm install @midnight-ntwrk/compact-runtime ``` If the installation succeeds, VPN restrictions are blocking npm access. Configure proxy settings instead. 2 ### Configure proxy (if VPN is required)[​](#configure-proxy-if-vpn-is-required "Direct link to Configure proxy (if VPN is required)") If you must remain connected to a VPN, configure npm to use your corporate proxy server. Replace `proxy.company.com:8080` with your actual proxy address: ``` # Set proxy settings npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 # With authentication (if required) npm config set proxy http://username:password@proxy.company.com:8080 npm config set https-proxy http://username:password@proxy.company.com:8080 ``` 3 ### Test installation[​](#test-installation-1 "Direct link to Test installation") ``` npm install @midnight-ntwrk/compact-runtime ``` **Verification**: Package installs successfully through proxy. ## Solution 3: Clear configuration and start fresh[​](#solution-3-clear-configuration-and-start-fresh "Direct link to Solution 3: Clear configuration and start fresh") If the previous solutions do not work, conflicting npm configurations may be causing the error. Clear all npm settings and restore default configurations to eliminate any misconfigurations. 1 ### Back up and clear configuration[​](#back-up-and-clear-configuration "Direct link to Back up and clear configuration") Important Back up the npm configuration before clearing it, as this process removes all custom settings. ``` # Back up existing config cp ~/.npmrc ~/.npmrc.backup # Remove all settings npm config delete registry npm config delete proxy npm config delete https-proxy npm config delete @midnight-ntwrk:registry ``` 2 ### Set defaults and clean project[​](#set-defaults-and-clean-project "Direct link to Set defaults and clean project") Data Loss Warning The following commands delete node\_modules and package-lock.json. Ensure the correct project directory is active before proceeding. ``` # Set registry npm config set registry https://registry.npmjs.org/ # Clean project rm -rf node_modules package-lock.json npm cache clean --force ``` 3 ### Test installation[​](#test-installation-2 "Direct link to Test installation") ``` npm install @midnight-ntwrk/compact-runtime ``` **Verification**: Package installs successfully. ## Solution 4: Authenticate to GitHub Package Registry[​](#solution-4-authenticate-to-github-package-registry "Direct link to Solution 4: Authenticate to GitHub Package Registry") If the previous solutions do not resolve the issue, the cause may be GitHub Package Registry authentication rather than an npm registry misconfiguration. Midnight publishes `@midnight-ntwrk/*` packages to `https://npm.pkg.github.com/`, which requires authentication even for public packages. This solution applies to Yarn Berry (v2+) projects that use a `.yarnrc.yml` file. Without a configured token, every install attempt fails with: ``` @midnight-ntwrk/ledger@npm:4.0.0::__archiveUrl=...: Invalid authentication (as an unknown user) ``` To resolve this, configure `npmAuthToken` in your `.yarnrc.yml`. You also need a GitHub personal access token with the `read:packages` scope, provided through the `GITHUB_TOKEN` environment variable. 1 ### Generate a GitHub personal access token[​](#generate-a-github-personal-access-token "Direct link to Generate a GitHub personal access token") Create a classic personal access token (PAT) at `https://github.com/settings/tokens/new` with the `read:packages` scope. A fine-grained token with the **Packages: Read** permission also works. Organization access For organization-owned packages, your token must also have access to the `midnightntwrk` organization. 2 ### Update `.yarnrc.yml`[​](#update-yarnrcyml "Direct link to update-yarnrcyml") Add the `npmAuthToken` field under the `midnight-ntwrk` scope, pointing at the `GITHUB_TOKEN` environment variable: ``` npmScopes: midnight-ntwrk: npmAlwaysAuth: true npmRegistryServer: "https://npm.pkg.github.com/" npmAuthToken: "${GITHUB_TOKEN}" ``` Token security Yarn interpolates `${GITHUB_TOKEN}` from the environment at install time, so the token never lives in `.yarnrc.yml`. 3 ### Export the token[​](#export-the-token "Direct link to Export the token") Export the `GITHUB_TOKEN` variable so yarn can interpolate it at install time: ``` export GITHUB_TOKEN= ``` If you prefer not to set the environment variable globally, prefix the install command on the same line: `GITHUB_TOKEN= yarn install`. 4 ### Test installation[​](#test-installation-3 "Direct link to Test installation") ``` yarn install @midnight-ntwrk/compact-runtime ``` **Verification**: Installation completes without `Invalid authentication` errors and `@midnight-ntwrk/*` packages resolve from `npm.pkg.github.com`. ## Platform-specific fixes[​](#platform-specific-fixes "Direct link to Platform-specific fixes") Some npm access issues are specific to particular operating systems or environments. Use these platform-specific solutions if the general fixes above do not resolve your issue. * Windows/WSL * Linux * macOS On Windows Subsystem for Linux (WSL), line ending issues and cache conflicts between Windows and WSL can cause npm errors. Use these commands to resolve WSL-specific issues: ``` # Configure git line endings git config --global core.autocrlf false # Use native WSL paths (not /mnt/c/...) cd /home/yourusername/project # Clear Windows npm cache rm -rf /mnt/c/Users/YourName/AppData/Roaming/npm-cache ``` Replace `yourusername` and `YourName` with your actual username. On Linux, permission errors can occur when npm tries to install packages globally. Configure npm to use a directory in your home folder instead of requiring sudo: ``` # Configure npm without sudo mkdir ~/.npm-global npm config set prefix '~/.npm-global' # Add to ~/.bashrc export PATH=~/.npm-global/bin:$PATH source ~/.bashrc ``` After running these commands, npm installs global packages to `~/.npm-global` without requiring elevated permissions. On macOS, cached credentials in the system keychain can cause authentication issues with npm. Clear these credentials to force npm to authenticate fresh: macOS security The system may prompt for your password when running this command. ``` # Clear keychain credentials security delete-generic-password -s 'npm' -a 'bearer' ``` If the command returns an error saying the password was not found, no credentials were stored and you can proceed with other solutions. ## Quick fix script[​](#quick-fix-script "Direct link to Quick fix script") For convenience, you can create an automated shell script that applies multiple fixes at once. This script resets npm configuration, clears caches, and tests the installation: fix-midnight-npm.sh ``` #!/bin/bash echo "🔧 Fixing Midnight npm installation..." # Clear configuration npm config delete registry npm config delete @midnight-ntwrk:registry npm config delete proxy npm config delete https-proxy # Set defaults npm config set registry https://registry.npmjs.org/ npm cache clean --force # Clean project (only if package.json exists) if [ -f "package.json" ]; then echo "📁 Cleaning project files..." rm -rf node_modules package-lock.json else echo "⚠️ No package.json found - skipping project cleanup" fi # Test installation echo "🧪 Testing package installation..." npm install @midnight-ntwrk/compact-runtime if [ $? -eq 0 ]; then echo "✅ Success! Midnight packages are accessible." else echo "❌ Installation failed. Try disconnecting from VPN or checking firewall settings." fi ``` Make the script executable and run it: ``` chmod +x fix-midnight-npm.sh ./fix-midnight-npm.sh ``` ## Verify the fix[​](#verify-the-fix "Direct link to Verify the fix") After applying the fixes, confirm that all configurations are correct and installations work properly: ``` # Check registry npm config get registry # Expected output: https://registry.npmjs.org/ # Test package access npm view @midnight-ntwrk/compact-runtime # Expected output: package information # Verify installation npm install @midnight-ntwrk/compact-runtime # Expected result: successful installation ``` ## Still not working?[​](#still-not-working "Direct link to Still not working?") If none of the solutions above resolve the issue, use these advanced debugging techniques to identify the root cause. **Enable verbose logging** Display detailed error information by running npm with the verbose flag: ``` npm install @midnight-ntwrk/compact-runtime --verbose ``` Common issues revealed by verbose logging include: * SSL certificate validation failures. * Proxy configuration errors or authentication issues. * DNS resolution failures when contacting the registry. **Test direct connection** Verify registry access: ``` curl https://registry.npmjs.org/@midnight-ntwrk/compact-runtime ``` A failed request indicates a network connectivity issue. ## Next steps[​](#next-steps "Direct link to Next steps") After successfully installing Midnight packages, verify that your development environment is properly configured and the packages are working correctly: ``` # Check installed packages npm list @midnight-ntwrk # Verify compiler compact --version # Test runtime import node -e "const runtime = require('@midnight-ntwrk/compact-runtime'); console.log('✅ Runtime loaded');" ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Fix version mismatch errors Learn how to resolve version compatibility issues between Midnight components that cause build failures and runtime errors. ## What causes version mismatches?[​](#what-causes-version-mismatches "Direct link to What causes version mismatches?") Midnight consists of multiple components that must work together in compatible versions: * **Compact toolchain**: Binaries, compiler, and formatter * **Runtime libraries**: `@midnight-ntwrk/compact-runtime`, `@midnight-ntwrk/ledger-v8`, `@midnight-ntwrk/onchain-runtime-v3`, and related packages * **JavaScript libraries**: `@midnight-ntwrk/midnight-js` (barrel package), `@midnight-ntwrk/dapp-connector-api`, `@midnight-ntwrk/wallet-sdk-facade`, and related packages * **Proof server**: Zero-knowledge proof generation service * **Indexer**: GraphQL API for querying blockchain data (optional) When these components are out of sync, you may encounter build errors, deployment failures, or runtime issues. Check the compatibility matrix Always refer to the official [release compatibility matrix](/relnotes/support-matrix.md) to verify which versions work together. ## Check your current versions[​](#check-your-current-versions "Direct link to Check your current versions") Before fixing version mismatches, identify which components are currently installed and compare them with the compatibility matrix. 1 ### Check the compiler version[​](#check-the-compiler-version "Direct link to Check the compiler version") ``` compact --version ``` Compare the output with the [compatibility matrix](/relnotes/support-matrix.md). 2 ### Check runtime package versions[​](#check-runtime-package-versions "Direct link to Check runtime package versions") Run these commands to check the installed versions of runtime packages: ``` npm list @midnight-ntwrk/compact-runtime npm list @midnight-ntwrk/ledger-v8 npm list @midnight-ntwrk/onchain-runtime-v3 ``` Verify that all runtime packages use compatible version numbers as specified in the compatibility matrix. 3 ### Check proof server version[​](#check-proof-server-version "Direct link to Check proof server version") If running the proof server using Docker: ``` docker ps | grep proof-server docker logs [proof-server-container-id] | head -20 ``` Look for version information in the startup logs. 4 ### Compare versions with the compatibility matrix[​](#compare-versions-with-the-compatibility-matrix "Direct link to Compare versions with the compatibility matrix") Review the [release compatibility matrix](/relnotes/support-matrix.md) and verify your versions are compatible. Note any components that do not match the recommended versions. ## Align component versions[​](#align-component-versions "Direct link to Align component versions") After identifying version mismatches, update all components to compatible versions. Always update related components together to maintain compatibility across your development environment. 1 ### Consult the compatibility matrix[​](#consult-the-compatibility-matrix "Direct link to Consult the compatibility matrix") Review the [release compatibility matrix](/relnotes/support-matrix.md) to identify the correct versions for your components: * Compact toolchain. * Runtime libraries. * JavaScript libraries. * Proof server. * Indexer (if used). 2 ### Update runtime packages[​](#update-runtime-packages "Direct link to Update runtime packages") Update your `package.json` with compatible versions from the matrix: package.json ``` { "dependencies": { "@midnight-ntwrk/compact-runtime": "x.x.x", "@midnight-ntwrk/ledger-v8": "x.x.x", "@midnight-ntwrk/onchain-runtime-v3": "x.x.x", "@midnight-ntwrk/wallet-sdk-facade": "x.x.x" } } ``` Install the updated packages: ``` npm install ``` 3 ### Update proof server[​](#update-proof-server "Direct link to Update proof server") If you use Docker, update your container image to a compatible version. Stop the current container, update your `docker-compose.yml` with the correct version, then restart: ``` # Stop current container docker-compose down # Update docker-compose.yml with compatible version, then restart docker-compose up -d ``` 4 ### Update the compiler[​](#update-the-compiler "Direct link to Update the compiler") Download and install the compatible compiler version from the [Compact releases](https://github.com/midnightntwrk/compact/releases). Verify installation: ``` compact --version ``` 5 ### Recompile contracts[​](#recompile-contracts "Direct link to Recompile contracts") After updating components, recompile your smart contracts: ``` # Clean old artifacts rm -rf contract/managed/ # Recompile using direct compact command compact compile src/contract.compact contract/managed ``` Keep components in sync Always check the compatibility matrix when updating components. Update all related components together to maintain compatibility across your development environment. ## Lock exact versions[​](#lock-exact-versions "Direct link to Lock exact versions") Prevent automatic version updates by specifying exact version numbers in your project configuration. This ensures your project remains stable and avoids unexpected compatibility issues. 1 ### Use exact version numbers[​](#use-exact-version-numbers "Direct link to Use exact version numbers") In your `package.json`, specify exact versions without range operators such as `^` or `~`: package.json ``` { "dependencies": { "@midnight-ntwrk/compact-runtime": "x.x.x", "@midnight-ntwrk/ledger-v8": "x.x.x" } } ``` Avoid version ranges Do not use version range operators such as `^x.x.x` or `~x.x.x`. Always specify exact versions like `x.x.x` to prevent unexpected updates. 2 ### Use npm ci for installations[​](#use-npm-ci-for-installations "Direct link to Use npm ci for installations") Use `npm ci` instead of `npm install` for reproducible builds: ``` # Clean install from lock file rm -rf node_modules npm ci ``` This installs exact versions from `package-lock.json`. 3 ### Document your versions[​](#document-your-versions "Direct link to Document your versions") Create a `VERSIONS.md` file in your project root to document the component versions you are using. This helps team members maintain consistency and troubleshoot version issues: VERSIONS.md ``` # Component Versions Last verified: 2025-10-17 ## Versions in Use - Compact compiler: x.x.x - Runtime packages: x.x.x - Proof server: x.x.x - Node.js: xx.x.x ## Compatibility Reference See: /relnotes/support-matrix ``` ## Platform-specific considerations[​](#platform-specific-considerations "Direct link to Platform-specific considerations") Different operating systems may require specific configuration or verification steps. Select your platform below for relevant guidance. * Linux * macOS * Windows/WSL Ensure all components are properly installed and accessible: ``` # Check compiler location which compact # Verify Node.js version node --version ``` On Apple Silicon (M1/M2/M3), verify that Docker images use the correct architecture: ``` # Check Docker architecture docker info | grep Architecture ``` When using Windows Subsystem for Linux (WSL), use native WSL paths rather than Windows mount paths for better performance and consistency: ``` # Use native WSL paths, not Windows mount paths like /mnt/c/ cd /home/username/project # Verify compiler access compact --version ``` ## Create a version check script[​](#create-a-version-check-script "Direct link to Create a version check script") Create a simple shell script to automate version checking across your development environment. This script helps you quickly verify that all components match the compatibility matrix. check-versions.sh ``` #!/bin/bash echo "=== Midnight Version Check ===" echo "" echo "Compiler:" compact --version || echo "❌ Compiler not found" echo "" echo "Runtime packages:" npm list --depth=0 | grep @midnight-ntwrk || echo "❌ No Midnight packages found" echo "" echo "Node.js:" node --version echo "" echo "⚠️ Compare these versions with:" echo "/relnotes/support-matrix" ``` Make the script executable and run it: ``` chmod +x check-versions.sh ./check-versions.sh ``` ## Back up before upgrading[​](#back-up-before-upgrading "Direct link to Back up before upgrading") Always back up your project files before upgrading components to prevent data loss if issues occur during the upgrade process: ``` # Back up package.json cp package.json package.json.backup # Back up contract artifacts cp -r contract contract-backup # Commit current state to git git add -A git commit -m "Backup before version upgrade" ``` ## Verify after updates[​](#verify-after-updates "Direct link to Verify after updates") After aligning component versions, test your setup to confirm everything works correctly: ``` # Test compilation compact compile src/contract.compact contract/ # Run tests npm test # Check for errors docker logs [proof-server-container-id] ``` ## Common mistakes to avoid[​](#common-mistakes-to-avoid "Direct link to Common mistakes to avoid") Avoid these common errors when managing component versions: caution * **Don't mix version ranges**: Use exact versions only. * **Don't update one component**: Update all related components together. * **Don't skip the compatibility matrix**: Always verify compatibility first. * **Don't forget to recompile**: Recompile contracts after compiler updates. ## Get help[​](#get-help "Direct link to Get help") If version issues persist after following these troubleshooting steps, use these resources: 1. **Check the compatibility matrix**: Review the [release compatibility matrix](/relnotes/support-matrix.md) for verified compatible versions. 2. **Review release notes**: Check component release notes for breaking changes and migration guidance. 3. **Ask for help**: Post in the #dev-chat channel on Discord with your version details and error messages. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Node overview The Midnight Node provides the foundational infrastructure for operating on the Midnight Network. It implements core protocol logic, manages peer-to-peer networking, and supports decentralized operations through integration with the Cardano network as a Partner Chain. ## Functions[​](#functions "Direct link to Functions") The Midnight node is responsible for: * Processing privacy-preserving smart contract transactions with zero-knowledge proofs * Enforcing protocol rules and maintaining blockchain state integrity * Enabling peer-to-peer (P2P) capabilities: node discovery, connection establishment, and block gossip * Supporting decentralization through both permissioned FNOs (Federated Node Operators) and registered SPOs (Stake Pool Operators) validators For how validators produce and finalize blocks, see [consensus](/concepts/network-architecture/consensus.md). ## Characteristics[​](#characteristics "Direct link to Characteristics") * Built on Polkadot SDK (Substrate framework) * Implements Partner Chain components for Cardano integration * Acts as a Partner Chain node with cross-chain communication * Requires persistent connection to Cardano via PostgreSQL database populated by Cardano-db-sync ## Architecture[​](#architecture "Direct link to Architecture") ``` ┌─────────────┐ ┌─────────────────┐ ┌──────────────┐ │ Cardano │ ───▶ │ Cardano Indexer │ ───▶ │ PostgreSQL │ │ Mainchain │ │ (db-sync) │ │ (cexplorer) │ └─────────────┘ └─────────────────┘ └──────────────┘ │ Observes mainchain state │ Queries Cardano data │ (cNIGHT, governance) ▼ ┌────────────────────────────────────────────────────────────────────┐ │ Midnight Node │ ├────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ Runtime │ │ │ │ │ │ │ │ ┌────────────────────────────────────────────────────────┐ │ │ │ │ │ Pallets │ │ │ │ │ │ │ │ │ │ │ │ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ │ │ │ │ Midnight │ │ Native │ │ Federated │ │ │ │ │ │ │ │ System │ │ Token │ │ Authority │ │ │ │ │ │ │ │ │ │ Observation │ │ │ │ │ │ │ │ │ └─────────────┘ └──────────────┘ └──────────────┘ │ │ │ │ │ │ │ │ │ │ │ │ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ │ │ │ │ Version │ │ Midnight │ │ Federated │ │ │ │ │ │ │ │ │ │ │ │ Authority │ │ │ │ │ │ │ │ │ │ │ │ Observation │ │ │ │ │ │ │ └─────────────┘ └──────────────┘ └──────────────┘ │ │ │ │ │ └────────────────────────────────────────────────────────┘ │ │ │ └──────────────────────────────────────────────────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────────────────────┐ │ │ │ Node Services │ │ │ │ │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ │ │ RPC │ │Consensus │ │ Keystore │ │ Network │ │ │ │ │ │ Server │ │ AURA │ │ │ │ P2P │◀───│──│────▶ Other Midnight Nodes │ │ │Port 9944 │ │ GRANDPA │ │ │ │Port 30333│ │ │ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ │ └──────────────────────────────────────────────────────────────┘ │ └────────────────────────────────────────────────────────────────────┘ │ │ WebSocket RPC │ Port: 9944 ▼ ┌─────────────────────────────────────────────────────────┐ │ External Clients: DApps, Indexers, Block Explorers │ └─────────────────────────────────────────────────────────┘ ``` ## Core parameters[​](#core-parameters "Direct link to Core parameters") | Parameter | Value | | -------------- | ------------------------- | | Block time | 6 seconds | | Session length | 1200 slots (2 hours) | | Epoch length | 300 blocks | | Hash function | `blake2_256` | | Account type | `sr25519` public key | | P2P port | 30333 (default) | | RPC port | 9944 (WebSocket, default) | ### Consensus[​](#consensus "Direct link to Consensus") * Initial validator set: Permissioned nodes operated by Federated Node Operators (FNOs). Stake Pool Operators (SPOs) supported at a later date. * The `D` parameter (`system_parameters`) controls the split between permissioned and registered validators. ## Runtime pallets[​](#runtime-pallets "Direct link to Runtime pallets") The Midnight Node includes eight custom pallets that implement core blockchain functionality: * **pallet-midnight**: Core ledger state and privacy-preserving transaction processing * **pallet-midnight-system**: System-level administrative operations * **pallet-cnight-observation**: Cardano bridge integration for cNIGHT token management and DUST generation * **pallet-federated-authority**: Multi-collective governance requiring consensus from multiple bodies * **pallet-federated-authority-observation**: Governance synchronization with Cardano Mainchain * **pallet-system-parameters**: Manages governance-controlled network parameters * **pallet-throttle**: Limits signed transaction throughput per governance member account * **pallet-version**: Runtime version tracking and upgrade monitoring ## Signature schemes[​](#signature-schemes "Direct link to Signature schemes") The Midnight Node uses different cryptographic schemes for various operations: * **ECDSA**: Partner Chain consensus message signing and BEEFY aggregated proofs * **Ed25519**: GRANDPA finality message signing * **Sr25519**: AURA block authorship signing (based on Schnorrkel / Ristretto / x25519) ## Node types[​](#node-types "Direct link to Node types") * **[Full node](/nodes/full-node.md)**: Validates transactions and maintains current blockchain state * **[Archive node](/nodes/full-node.md#full-node-vs-archive-node)**: Stores complete blockchain history with all historical states * **[Boot node](/nodes/boot-node.md)**: Provides initial connection points for nodes joining the network * **[RPC node](/nodes/rpc-node.md)**: Exposes HTTP/WebSocket APIs for external client interactions --- > For the complete documentation index, see [llms.txt](/llms.txt) # Set up boot node Boot nodes serve as initial connection points for nodes joining the Midnight Network. They help new nodes discover and connect to active peers in the network. While running a boot node is optional, doing so strengthens network decentralization and improves peer discovery. This guide provides step-by-step instructions for setting up a boot node for Midnight. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before setting up your Midnight boot node, ensure you have the following: * [Cardano-db-sync instance set up](/nodes/cardano-db-sync.md) with accessible PostgreSQL port. * [Midnight node set up](/nodes/full-node.md#install-midnight-node) with the environment variables set. ## Set up a boot node[​](#set-up-a-boot-node "Direct link to Set up a boot node") Use the following command to run Midnight node in boot node mode. Choose the configuration for your target network. * Preview * Preprod ``` midnight-node \ --chain /home/midnight/res/preview/chain-spec-raw.json \ --base-path /home/midnight/data \ --listen-addr /ip4/0.0.0.0/tcp/30333 \ --bootnodes /dns/bootnode-1.preview.midnight.network/tcp/30333/ws/p2p/12D3KooWK66i7dtGVNSwDh9tTeqov1q6LSdWsRLJvTyzTCaywYgK \ --no-private-ip ``` ``` midnight-node \ --chain /home/midnight/res/preprod/chain-spec-raw.json \ --base-path /home/midnight/data \ --listen-addr /ip4/0.0.0.0/tcp/30333 \ --bootnodes /dns/bootnode-1.preprod.midnight.network/tcp/30333/ws/p2p/12D3KooWQxxUgq7ndPfAaCFNbAxtcKYxrAzTxDfRGNktF75SxdX5 \ --no-private-ip ``` ## Known network boot nodes[​](#known-network-boot-nodes "Direct link to Known network boot nodes") Use the boot nodes corresponding to your target network environment. * Preview * Preprod ``` --bootnodes /dns/bootnode-1.preview.midnight.network/tcp/30333/ws/p2p/12D3KooWK66i7dtGVNSwDh9tTeqov1q6LSdWsRLJvTyzTCaywYgK \ --bootnodes /dns/bootnode-2.preview.midnight.network/tcp/30333/ws/p2p/12D3KooWHqFfXFwb7WW4jwR8pr4BEf562v5M6c8K3CXAJq4Wx6ym ``` ``` --bootnodes /dns/bootnode-1.preprod.midnight.network/tcp/30333/ws/p2p/12D3KooWQxxUgq7ndPfAaCFNbAxtcKYxrAzTxDfRGNktF75SxdX5 \ --bootnodes /dns/bootnode-2.preprod.midnight.network/tcp/30333/ws/p2p/12D3KooWNrUBs22FfmgjqFMa9ZqKED2jnxwsXWw5E4q2XVwN35TJ ``` ## Next steps[​](#next-steps "Direct link to Next steps") With the boot node set up, run the [RPC node](/nodes/rpc-node.md) to interact with the Midnight blockchain. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Set up Cardano-db-sync This guide provides step-by-step instructions for setting up Cardano-db-sync for Midnight. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before setting up Cardano-db-sync, ensure you have the following: * [Cardano node set up](/nodes/cardano-node.md) with a running node. * Sufficient resources (CPU, memory, and storage). ## Create PostgreSQL database[​](#create-postgresql-database "Direct link to Create PostgreSQL database") `Cardano-db-sync` requires a `PostgreSQL` backend to index blockchain data into a relational schema. ### Install PostgreSQL[​](#install-postgresql "Direct link to Install PostgreSQL") Run the following commands to install PostgreSQL: ``` sudo apt install curl ca-certificates -y sudo install -d /usr/share/postgresql-common/pgdg sudo curl -s -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc sudo sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' sudo apt update && sudo apt -y install postgresql-17 postgresql-server-dev-17 ``` ### Configure roles and database[​](#configure-roles-and-database "Direct link to Configure roles and database") Start the PostgreSQL shell: ``` sudo -i -u postgres psql ``` Create the user `midnight` and ensure the `midnight` user has a known password + full privileges: ``` CREATE USER midnight WITH PASSWORD 'your_actual_password'; ALTER ROLE midnight WITH SUPERUSER CREATEDB; CREATE DATABASE cexplorer; ``` These commands securely log into PostgreSQL as admin, create the user `midnight` and ensure the `midnight` user has a known password + full privileges, and create the empty `cexplorer` database. ### Configure authentication[​](#configure-authentication "Direct link to Configure authentication") Create a `.pgpass` file to allow Cardano-db-sync to connect without manual password entry: ``` # Set variable for postgres password export POSTGRES_PASSWORD='your_actual_password' # Set the variable to a hidden file in your home directory export PGPASSFILE="${HOME}/.pgpass" ``` important Ensure you replace `your_actual_password` with your actual secure password. Write the connection string to the `.pgpass` file: ``` echo "/var/run/postgresql:5432:cexplorer:midnight:$POSTGRES_PASSWORD" > "$PGPASSFILE" ``` Set strict permissions for the `.pgpass` file. PostgreSQL ignores the file if it's world-readable: ``` chmod 0600 "$PGPASSFILE" ``` Run a connection test: ``` psql -h /var/run/postgresql -U midnight -d cexplorer -c "SELECT current_user; SELECT now();" ``` How to interpret the results: * **Success**: If successful, then it returns a table showing `midnight` and the current timestamp without asking for a password. * **Password Prompt**: If it asks for a password, then the `.pgpass` file isn't being read correctly. Likely a mismatch in the host, port, or database name. * **Access Denied**: If you get `database "cexplorer" does not exist`, then you need to create the database first. Verify the `.pgpass` file exists including contents: ``` cat ~/.pgpass ``` Example output: ``` /var/run/postgresql:5432:cexplorer:midnight:YOUR_PASSWORD ``` The `~/.pgpass` file is a configuration file used by PostgreSQL client tools such as `psql` and `pg_dump` to automatically retrieve passwords without requiring manual entry or hard-coding them in scripts. ### PostgreSQL 17 configuration tuning[​](#postgresql-17-configuration-tuning "Direct link to PostgreSQL 17 configuration tuning") important PostgreSQL tuning is **required** when targeting Mainnet. Without it, Cardano-db-sync synchronization will take an extremely long time to complete. Modify your `/etc/postgresql/17/main/postgresql.conf` file: Find and update these specific lines. Remove the `#` to uncomment them: | Configuration | Description | | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `shared_buffers = 16GB` | This allows PostgreSQL to keep much more of the Cardano ledger in active memory. | | `maintenance_work_mem = 4GB` | This is the most important for your current "Building Index" phase. It gives the index sorter more elbow room to work. | | `max_parallel_maintenance_workers = 4` | This allows 4 CPU cores to collaborate on building that single index. | | `effective_cache_size = 48GB` | This helps the PostgreSQL planner understand how much total RAM it can rely on for caching. | ## Setup Cardano-db-sync[​](#setup-cardano-db-sync "Direct link to Setup Cardano-db-sync") This section covers downloading and installing Cardano-db-sync binaries and config files. important Use Cardano-db-sync [13.7.1.0](https://github.com/IntersectMBO/cardano-db-sync/releases/tag/13.7.1.0) together with Cardano-node [11.0.1](https://github.com/IntersectMBO/cardano-node/releases/tag/11.0.1). Because of the Van Rossem upgrade changes, the Cardano-db-sync database must be replayed against Cardano-node 11.0.1. Upgrading to this Cardano-db-sync version is not just a binary swap. The existing database needs to be replayed before it is usable. ### Download Cardano-db-sync binaries[​](#download-cardano-db-sync-binaries "Direct link to Download Cardano-db-sync binaries") Set the network to either, "preview", "mainnet", or "preprod": ``` NETWORK="preprod" ``` Download the Cardano-db-sync binaries and extract them into a temporary directory: ``` mkdir -p ~/tmp cd ~/tmp curl -L -O https://github.com/IntersectMBO/cardano-db-sync/releases/download/13.7.1.0/cardano-db-sync-13.7.1.0-linux.tar.gz tar -xzf cardano-db-sync-13.7.1.0-linux.tar.gz ``` Move Cardano-db-sync binaries to the local bin directory: ``` mkdir -p ~/.local/bin cp bin/* ~/.local/bin/ chmod +x ~/.local/bin/cardano-db-sync* ``` Verify Cardano-db-sync installation: ``` cardano-db-sync --version which cardano-db-sync ``` Move the downloaded `db-sync` schema into the `~/cardano-data` directory: ``` mkdir -p ~/cardano-data/ sudo mv ~/tmp/schema ~/cardano-data/ ``` Download the Cardano-db-sync `config.json` file: ``` cd ~/cardano-data curl -O https://book.world.dev.cardano.org/environments/$NETWORK/db-sync-config.json ``` Update the Cardano-db-sync `config.json` file with the Cardano node configuration file: ``` sed -i "s|\"NodeConfigFile\": \"config.json\"|\"NodeConfigFile\": \"/home/midnight/.local/share/$NETWORK/config.json\"|" ~/cardano-data/db-sync-config.json ``` Verify Cardano-db-sync installation: ``` cardano-db-sync --version which cardano-db-sync ``` ### Run Cardano-db-sync[​](#run-cardano-db-sync "Direct link to Run Cardano-db-sync") important Make sure your [Cardano node](/nodes/cardano-node.md) is running. Cardano-db-sync uses the Cardano database (provided by Cardano-node) to index chain. Set the environment variable for the PostgreSQL password: ``` export PGPASSFILE="${HOME}/.pgpass" ``` Start Cardano-db-sync interactively in shell: ``` cardano-db-sync \ --config /home/midnight/cardano-data/db-sync-config.json \ --socket-path /home/midnight/cardano-data/db/node.socket \ --schema-dir /home/midnight/cardano-data/schema \ --state-dir /home/midnight/cardano-data/db-sync-state ``` info Cardano-db-sync might delay for 5-20 minutes while it initializes. This is normal and expected. Check the latest block height of the `cardano-db-sync`: ``` psql -d cexplorer -c "SELECT block_no, slot_no, time FROM block ORDER BY id DESC LIMIT 1;" ``` Get `cardano-db-sync` sync percentage: ``` psql -d cexplorer -c " SELECT 100 * (EXTRACT(epoch FROM (MAX(time) AT TIME ZONE 'UTC')) - EXTRACT(epoch FROM (MIN(time) AT TIME ZONE 'UTC'))) / (EXTRACT(epoch FROM (NOW() AT TIME ZONE 'UTC')) - EXTRACT(epoch FROM (MIN(time) AT TIME ZONE 'UTC'))) AS sync_percent FROM block;" ``` Example output: ``` sync_percent ------------ 45.00 (1 row) ``` This means that the Cardano-db-sync is 45% synced. You need to wait for the sync percentage to reach at least 99% before running Cardano-db-sync. info Get more interesting SQL queries from the Cardano-db-sync repository: ### Setup Cardano-db-sync `systemd` service[​](#setup-cardano-db-sync-systemd-service "Direct link to setup-cardano-db-sync-systemd-service") Create the service file for the Cardano-db-sync: ``` sudo vim /etc/systemd/system/cardano-db-sync.service ``` Paste the following contents into the service file: ``` [Unit] Description=Cardano DB Sync # Ensures db-sync doesn't start until the node is ready After=cardano-node.service Requires=cardano-node.service [Service] User=midnight Type=simple # Crucial: Tells the tool where to find the Postgres password Environment="PGPASSFILE=/home/midnight/.pgpass" WorkingDirectory=/home/midnight/cardano-data ExecStart=/home/midnight/.local/bin/cardano-db-sync \ --config /home/midnight/cardano-data/db-sync-config.json \ --socket-path /home/midnight/cardano-data/db/node.socket \ --schema-dir /home/midnight/cardano-data/schema \ --state-dir /home/midnight/cardano-data/db-sync-state # SIGINT is the "clean" way to shut down to prevent database corruption KillSignal=SIGINT Restart=always RestartSec=10 # Increases the limit for open files (important for high-throughput DBs) LimitNOFILE=32768 [Install] WantedBy=multi-user.target ``` Enable and start the Cardano-db-sync service: ``` # Reload systemd to recognize new files sudo systemctl daemon-reload # Enable services to start on boot sudo systemctl enable cardano-db-sync # Start the services sudo systemctl start cardano-db-sync ``` View the status of the Cardano-db-sync service: ``` sudo systemctl status cardano-db-sync ``` View live logs: ``` # Follow Cardano-db-sync logs journalctl -u cardano-db-sync -f ``` ## Next steps[​](#next-steps "Direct link to Next steps") With Cardano-db-sync fully synchronized, you can start your Midnight node. To learn more, see the [Set up full node](/nodes/full-node.md) guide. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Set up Cardano node Midnight operates as a partner chain to Cardano, enabling interoperability and shared security. To maintain synchronization with the Cardano blockchain, the Midnight node requires a persistent connection to a PostgreSQL database populated by Cardano-db-sync. This database indexes Cardano's on-chain data and provides queryable access to it. This guide provides step-by-step instructions for setting up a Cardano relay node and a synchronized PostgreSQL database via cardano-db-sync. Supported platform These node setup guides target **Linux on x86-64 (amd64)**. The commands and binary download URLs assume this architecture. Builds for other platforms may exist, but multi-architecture instructions are out of scope. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") To run all nodes successfully, you need to aim for the following: System requirements Linux operating systems must be compatible with GLIBC version 2.39 or greater. Use one of the following: * Ubuntu 24.04 or later * Debian 13 or later Verify your GLIBC version with: `ldd --version` Hardware requirements | Requirement | Cardano Mainnet | Preview/Preprod Testnet | | -------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | **Operating system** | 64-bit Linux (Ubuntu 24.04 LTS recommended) | 64-bit Linux (Ubuntu 24.04 LTS recommended) | | **Memory** | 32 GB or more | 16 GB or more | | **CPU cores** | 4 or more | 4 or more | | **IOPS** | 60,000 IOPS or better. Lower ratings will lead to slower sync times and/or falling behind the chain tip. | 30,000 IOPS or better. Lower ratings will lead to slower sync times. | | **Disk storage** | 320 GB NVMe SSD | 40 GB NVMe SSD (minimum) | | **Network** | Stable 100 Mbps or better | Stable 100 Mbps or better | User segregation You can optionally create a non-privileged user to run the node service. Not running blockchain node as root is a security best practice. Create a non-privileged user named "midnight" to run the node service. ``` sudo adduser midnight ``` Grant sudo privileges to the user: ``` sudo usermod -aG sudo midnight ``` Switch to the "midnight" user: ``` su - midnight ``` Confirm profile: ``` whoami # should return "midnight" ``` ## Mithril setup[​](#mithril-setup "Direct link to Mithril setup") This guide uses [Mithril](https://mithril.network/) to download a verified snapshot of the Cardano blockchain, reducing sync time from days to roughly 20 minutes. ### Install Mithril tooling[​](#install-mithril-tooling "Direct link to Install Mithril tooling") Create a temporary directory and navigate to it: ``` mkdir -p $HOME/tmp/mithril && cd $HOME/tmp/mithril ``` Install Mithril signer, client, and aggregator (pre-release): ``` curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/input-output-hk/mithril/refs/heads/main/mithril-install.sh | sh -s -- -c mithril-signer -d unstable -p $(pwd) curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/input-output-hk/mithril/refs/heads/main/mithril-install.sh | sh -s -- -c mithril-client -d unstable -p $(pwd) curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/input-output-hk/mithril/refs/heads/main/mithril-install.sh | sh -s -- -c mithril-aggregator -d unstable -p $(pwd) ``` ### Configure Cardano environment variables (for Mithril)[​](#configure-cardano-environment-variables-for-mithril "Direct link to Configure Cardano environment variables (for Mithril)") info To get the latest Mithril network configurations, see . Set the following variables to point to the Cardano network you are using: * Preview * Preprod * Mainnet ``` export CARDANO_NETWORK=preview export AGGREGATOR_ENDPOINT=https://aggregator.pre-release-preview.api.mithril.network/aggregator export GENESIS_VERIFICATION_KEY=$(wget -q -O - https://raw.githubusercontent.com/input-output-hk/mithril/main/mithril-infra/configuration/pre-release-preview/genesis.vkey) export ANCILLARY_VERIFICATION_KEY=$(wget -q -O - https://raw.githubusercontent.com/input-output-hk/mithril/main/mithril-infra/configuration/pre-release-preview/ancillary.vkey) export SNAPSHOT_DIGEST=latest ``` ``` export CARDANO_NETWORK=preprod export AGGREGATOR_ENDPOINT=https://aggregator.release-preprod.api.mithril.network/aggregator export GENESIS_VERIFICATION_KEY=$(wget -q -O - https://raw.githubusercontent.com/input-output-hk/mithril/main/mithril-infra/configuration/release-preprod/genesis.vkey) export ANCILLARY_VERIFICATION_KEY=$(wget -q -O - https://raw.githubusercontent.com/input-output-hk/mithril/main/mithril-infra/configuration/release-preprod/ancillary.vkey) export SNAPSHOT_DIGEST=latest ``` ``` export CARDANO_NETWORK=mainnet export AGGREGATOR_ENDPOINT=https://aggregator.release-mainnet.api.mithril.network/aggregator export GENESIS_VERIFICATION_KEY=$(wget -q -O - https://raw.githubusercontent.com/input-output-hk/mithril/main/mithril-infra/configuration/release-mainnet/genesis.vkey) export ANCILLARY_VERIFICATION_KEY=$(wget -q -O - https://raw.githubusercontent.com/input-output-hk/mithril/main/mithril-infra/configuration/release-mainnet/ancillary.vkey) export SNAPSHOT_DIGEST=latest ``` warning The Cardano mainnet database is much larger than testnet databases. Therefore, downloading the mainnet snapshot takes longer. ### Download Cardano database snapshot[​](#download-cardano-database-snapshot "Direct link to Download Cardano database snapshot") List and verify the latest snapshot: ``` ./mithril-client cardano-db snapshot list ./mithril-client cardano-db snapshot show $SNAPSHOT_DIGEST ``` Download and verify the database: ``` ./mithril-client cardano-db download --include-ancillary $SNAPSHOT_DIGEST ``` The Mithril client downloads the snapshot to a `db/` directory in the working directory, which in this case is `/tmp/mithril/db`. This database will be used to bootstrap the Cardano node. ## Setup Cardano relay node[​](#setup-cardano-relay-node "Direct link to Setup Cardano relay node") Cardano node is the official Cardano client. There are many methods to install the node. This guide uses the official pre-compiled binary release. note If you want to build from source and explore additional methods, then use the [official Cardano documentation](https://developers.cardano.org/docs/operate-a-stake-pool/relay-configuration/relay-node-configuration/). ### Download Cardano node pre-compiled binary[​](#download-cardano-node-pre-compiled-binary "Direct link to Download Cardano node pre-compiled binary") Install Cardano node pre-compiled binary into `~/.local/bin` by running the following command: Always check for the latest release from the official [Cardano node release page](https://github.com/IntersectMBO/cardano-node/releases) on GitHub. ``` VERSION="11.0.1" ARCH="linux-amd64" URL="https://github.com/IntersectMBO/cardano-node/releases/download/${VERSION}/cardano-node-${VERSION}-${ARCH}.tar.gz" ``` Ensure the destination exists by running the following command: ``` mkdir -p ~/.local/bin mkdir -p ~/.local/share ``` Download and extract directly to the right spots by running the following command: ``` # --strip-components=1 removes the top-level 'bin/' or 'share/' wrapper curl -L "$URL" | tar -xz -C ~/.local/bin --strip-components=2 ./bin curl -L "$URL" | tar -xz -C ~/.local/share --strip-components=1 ./share ``` Make sure they are executable by running the following command: ``` chmod +x ~/.local/bin/cardano-* ``` This downloads and unpacks binary contents (`~/.local/bin`) and Cardano node configuration files for each Cardano network (`~/.local/share/`). Verify that the binaries and configuration files exist by running the following command: ``` ls ~/.local/bin ~/.local/share ``` Example output: ``` ~/.local/bin: bech32 cardano-node cardano-testnet db-analyser db-truncater tx-generator cardano-cli cardano-submit-api cardano-tracer db-synthesizer snapshot-converter ~/.local/share: mainnet preprod preview ``` Refresh the shell session and verify that you can invoke the Cardano node binary: ``` source ~/.bashrc # or ~/.zshrc which cardano-node # /$HOME/$USER/.local/bin/cardano-node cardano-node --version # cardano-node 11.0.1 - linux-x86_64 - ghc-9.6 # git rev 6c034ec038d8d276a3595e10e2d38643f09bd1f2 ``` ### Inject Mithril snapshot (optional)[​](#inject-mithril-snapshot-optional "Direct link to Inject Mithril snapshot (optional)") This is where you may consider your desired data storage options. For this guide, create a `~/cardano-data` directory for the Cardano node’s database and node socket path. ``` mkdir ~/cardano-data ``` Move the Cardano database snapshot: ``` mv ~/tmp/mithril/db/ ~/cardano-data/ ``` Verify that you moved the database: ``` ls ~/cardano-data/db ``` ### Run Cardano node[​](#run-cardano-node "Direct link to Run Cardano node") When you start `cardano-node`, provide the configuration file paths from `~/.local/bin/share/` and the database path. The Mithril client has already downloaded a snapshot of the *Cardano Preprod* database to `~/cardano-preprod/db`. Start the node interactively in shell: * Preview * Preprod * Mainnet ``` cardano-node run \ --topology ~/.local/share/preview/topology.json \ --database-path ~/cardano-data/db \ --socket-path ~/cardano-data/db/node.socket \ --host-addr 0.0.0.0 \ --port 3001 \ --config ~/.local/share/preview/config.json ``` ``` cardano-node run \ --topology ~/.local/share/preprod/topology.json \ --database-path ~/cardano-data/db \ --socket-path ~/cardano-data/db/node.socket \ --host-addr 0.0.0.0 \ --port 3001 \ --config ~/.local/share/preprod/config.json ``` ``` cardano-node run \ --topology ~/.local/share/mainnet/topology.json \ --database-path ~/cardano-data/db \ --socket-path ~/cardano-data/db/node.socket \ --host-addr 0.0.0.0 \ --port 3001 \ --config ~/.local/share/mainnet/config.json ``` If you took the snapshot of the Mainnet database, then the `node.socket` file is *not* created until the node has completed its internal initialization. The process includes validating the database and replaying any necessary blocks. Therefore, you will need to wait. The example log below shows the Cardano node has replayed only 1.76% of the chain. This may take around 20 minutes to complete. ``` Mar 10 21:36:58 mnf-mainnet-validator-1 cardano-node[7201]: [mnf-main:cardano.node.ChainDB:Info:5] [2026-03-10 21:36:58.11 UTC] Replayed block: slot 3196799 out of 181548256. Progress: 1.76% ``` Check latest block height of `cardano-node`: ``` export CARDANO_NODE_SOCKET_PATH="$HOME/cardano-data/db/node.socket" # You must use --testnet-magic 1 (preprod) or 2 (preview) with Cardano testnets cardano-cli query tip --testnet-magic 1 # To query mainnet simply pass --mainnet like so # cardano-cli query tip --mainnet ``` Example output: ``` { "block": 136111, "epoch": 10, "era": "Alonzo", "hash": "dc7767c3e2d116f3be63b33033a223fc5429a2ad65ade92578d1c40795a5f5b1", "slot": 2815017, "slotInEpoch": 136617, "slotsToEpochEnd": 295383, "syncProgress": "3.91" } ``` When you run `cardano-cli query tip`, you are asking your local node for its "current view" of the blockchain. Since your node is still syncing, this output represents where your node is currently positioned compared to the total history of the network. * **`"block"`**: This is the height of the last block your node has processed. In this case, it has reached block *136,111*. * **`"epoch"`**: The current epoch your node is looking at. An epoch is a specific time period, equivalent to 5 days on Mainnet, but varies on testnets. The node is currently in *Epoch 10*. * **`"era"`**: The protocol version (hard fork) the node is currently processing. Seeing *"Alonzo"* means your node is currently replaying history from the era that introduced smart contracts. As it syncs further, you will see this change to *"Babbage"* and eventually *"Conway"* (the current era). * **`"hash"`**: The unique digital fingerprint of the most recent block your node processed. * **`"slot"`**: The total number of seconds/slots that have passed since the network started (the "Genesis"). * **`"slotInEpoch"`** & **`"slotsToEpochEnd"`**: These tell you how far into the current epoch you are. The node has completed 136,617 slots in Epoch 10, with 295,383 slots remaining before Epoch 11 begins. * **`"syncProgress"`**: *This is the most important number.* It shows that the node has only downloaded and verified *3.91%* of the blockchain. ### Create Cardano node `systemd` service files[​](#create-cardano-node-systemd-service-files "Direct link to create-cardano-node-systemd-service-files") Create the service file for the relay node: ``` sudo vim /etc/systemd/system/cardano-node.service ``` Paste the following contents into the service file: * Preview * Preprod * Mainnet ``` [Unit] Description=Cardano Relay Node Wants=network-online.target After=network-online.target [Service] User=midnight Type=simple WorkingDirectory=/home/midnight/cardano-data ExecStart=/home/midnight/.local/bin/cardano-node run \ --topology /home/midnight/.local/share/preview/topology.json \ --database-path /home/midnight/cardano-data/db \ --socket-path /home/midnight/cardano-data/db/node.socket \ --host-addr 0.0.0.0 \ --port 3001 \ --config /home/midnight/.local/share/preview/config.json KillSignal=SIGINT Restart=always RestartSec=5 LimitNOFILE=32768 [Install] WantedBy=multi-user.target ``` ``` [Unit] Description=Cardano Relay Node Wants=network-online.target After=network-online.target [Service] User=midnight Type=simple WorkingDirectory=/home/midnight/cardano-data ExecStart=/home/midnight/.local/bin/cardano-node run \ --topology /home/midnight/.local/share/preprod/topology.json \ --database-path /home/midnight/cardano-data/db \ --socket-path /home/midnight/cardano-data/db/node.socket \ --host-addr 0.0.0.0 \ --port 3001 \ --config /home/midnight/.local/share/preprod/config.json KillSignal=SIGINT Restart=always RestartSec=5 LimitNOFILE=32768 [Install] WantedBy=multi-user.target ``` ``` [Unit] Description=Cardano Mainnet Node Wants=network-online.target After=network-online.target [Service] User=midnight Type=simple # Ensure this directory exists or update it to where you want the process to trigger from WorkingDirectory=/home/midnight/cardano-data ExecStart=/home/midnight/.local/bin/cardano-node run \ --topology /home/midnight/.local/share/mainnet/topology.json \ --database-path /home/midnight/cardano-data/db \ --socket-path /home/midnight/cardano-data/db/node.socket \ --host-addr 0.0.0.0 \ --port 3001 \ --config /home/midnight/.local/share/mainnet/config.json KillSignal=SIGINT Restart=always RestartSec=5 LimitNOFILE=32768 [Install] WantedBy=multi-user.target ``` Reload `systemd` to recognize new files: ``` sudo systemctl daemon-reload ``` Enable services to start on boot: ``` sudo systemctl enable cardano-node ``` Start the Cardano node service and check status: ``` sudo systemctl start cardano-node sudo systemctl status cardano-node ``` Follow the logs: ``` journalctl -fu cardano-node ``` ## Next steps[​](#next-steps "Direct link to Next steps") With the Cardano relay node running, proceed to [setup the PostgreSQL database and Cardano-db-sync](/nodes/cardano-db-sync.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight node error codes Midnight node errors are `LedgerApiError` codes mapped to `u8` (0–255). They surface via Substrate's `InvalidTransaction::Custom(u8)` when the node rejects a transaction at the ledger level. They often occur when the node rejects a submitted transaction with `Custom(N)` in the Substrate dispatch error. info A pallet-level `DispatchError::Module` surfaces with index 5 (`pallet_midnight`) or 6 (`pallet_midnight_system`) and you need to decode the inner error. To learn how to decode the inner error, see the [Decode 1010 transaction rejection errors](/how-to/decode-1010-transaction-rejection-errors.md) troubleshooting guide. ## Error tables by code range[​](#error-tables-by-code-range "Direct link to Error tables by code range") Below is a list of the Midnight node specific errors categorized by type and status code. The error tables group errors by code range to help you identify the error types. ### Deserialization errors (0–11)[​](#deserialization-errors-011 "Direct link to Deserialization errors (0–11)") Errors that occur when the node fails to deserialize data from the wire format. | Code | Name | Description | How to fix | | ---- | ------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------- | | 0 | `NetworkId` | Failed to deserialize the network ID | Check SDK version compatibility, verify network ID encoding | | 1 | `Transaction` | Failed to deserialize transaction payload | Verify transaction was built with a compatible SDK version | | 2 | `LedgerState` | Failed to deserialize ledger state | Internal node error | | 3 | `ContractAddress` | Failed to deserialize contract address | Verify the contract address format | | 4 | `PublicKey` | Failed to deserialize public key | Check key format and encoding | | 5 | `VersionedArenaKey` | Failed to deserialize versioned arena key | Internal | | 6 | `UserAddress` | Failed to deserialize user address | Verify address format | | 7 | `TypedArenaKey` | Failed to deserialize typed arena key | Internal | | 8 | `SystemTransaction` | Failed to deserialize system transaction | Governance/bridge transaction format error | | 9 | `DustPublicKey` | Failed to deserialize DUST public key | Check DUST key format | | 10 | `CNightGeneratesDustActionType` | Failed to deserialize cNIGHT-generates-DUST action type | Internal bridge/observation error | | 11 | `CNightGeneratesDustEvent` | Failed to deserialize cNIGHT-generates-DUST event | Internal bridge/observation error | Most deserialization errors occur due to version mismatch. Always refer to the [compatibility matrix](/relnotes/support-matrix.md) to ensure you are using compatible versions of Midnight blockchain components. ### Serialization errors (50–63)[​](#serialization-errors-5063 "Direct link to Serialization errors (50–63)") Errors that occur when the node fails to serialize data for storage or transmission. | Code | Name | Description | How to fix | | ---- | -------------------------- | ----------------------------------------------- | ---------------------------------------------------------- | | 50 | `TransactionIdentifier` | Failed to serialize transaction identifier | Internal | | 51 | `LedgerState` | Failed to serialize ledger state | Internal node error | | 52 | `LedgerParameters` | Failed to serialize ledger parameters | Internal node error | | 53 | `ContractAddress` | Failed to serialize contract address | Internal | | 54 | `ContractState` | Failed to serialize contract state | The contract state might be corrupt | | 55 | `ContractStateToJson` | Failed to serialize contract state to JSON | Contract state format incompatible with JSON serialization | | 56 | `ZswapState` | Failed to serialize Zswap state | Internal Zswap error | | 57 | `UnknownType` | Failed to serialize an unknown type | Internal | | 58 | `MerkleTreeDigest` | Failed to serialize Merkle tree digest | Internal Merkle tree error | | 59 | `VersionedArenaKey` | Failed to serialize versioned arena key | Internal | | 60 | `TypedArenaKey` | Failed to serialize typed arena key | Internal | | 61 | `CNightGeneratesDustEvent` | Failed to serialize cNIGHT-generates-DUST event | Internal bridge error | | 62 | `SystemTransaction` | Failed to serialize system transaction | Internal governance error | | 63 | `ArenaHash` | Failed to serialize arena hash | Internal | ### Transaction invalid (100–109, 193–200)[​](#transaction-invalid-100109-193200 "Direct link to Transaction invalid (100–109, 193–200)") Errors that occur when the node applies a transaction to the ledger state and then rejects it for violating a ledger invariant. | Code | Name | Description | How to fix | | ---- | --------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | 100 | `EffectsMismatch` | Declared transaction effects don't match the computed effects | Rebuild the transaction. The effects declaration is stale or the SDK computed it incorrectly | | 101 | `ContractAlreadyDeployed` | A contract already exists at the target address | Use a different contract address or find the existing deployment | | 102 | `ContractNotPresent` | Called a contract that doesn't exist at the given address | Verify the contract address; deploy the contract first | | 103 | `Zswap` | Zswap-level transaction error (e.g., double-spend, unknown Merkle root) | Check for nullifier reuse, verify coin tree root is current | | 104 | `Transcript` | The node rejected on-chain transcript execution | Check contract logic; the circuit's on-chain transcript failed | | 105 | `InsufficientClaimable` | Not enough NIGHT tokens to claim | Ensure sufficient NIGHT balance for the operation | | 106 | `VerifierKeyNotFound` | Verifier key missing for the circuit operation | Deploy the verifier key before calling the circuit | | 107 | `VerifierKeyAlreadyPresent` | Verifier key already exists for this operation | The key is already deployed; no action needed | | 108 | `ReplayCounterMismatch` | Signed counter doesn't match (replay attack prevention) | Rebuild the transaction with the current replay counter | | 109 | `UnknownError` | Unclassified transaction invalid error | Check node logs for details | | 193 | `ReplayProtectionViolation` | Transaction violates replay protection (duplicate intent) | This transaction or intent was already submitted | | 194 | `BalanceCheckOutOfBounds` | Token balance would overflow or underflow | Verify token amounts don't exceed representable range | | 195 | `InputNotInUtxos` | Input references a UTXO that doesn't exist in the set | The coin may already be spent; resync wallet state | | 196 | `DustDoubleSpend` | Attempt to spend the same DUST twice | DUST UTXO already consumed; resync DUST wallet | | 197 | `DustDeregistrationNotRegistered` | Attempting to deregister a DUST address that isn't registered | Verify the DUST address is currently registered | | 198 | `GenerationInfoAlreadyPresent` | DUST generation info already exists | Duplicate generation info submission | | 199 | `InvariantViolation` | Protocol-level invariant violated (e.g., NIGHT supply exceeded) | Transaction would break fundamental protocol rules | | 200 | `RewardTooSmall` | Claimed reward is below the minimum payout threshold | Accumulate more rewards before claiming | ### Transaction malformed (110–139, 166–192)[​](#transaction-malformed-110139-166192 "Direct link to Transaction malformed (110–139, 166–192)") Errors that occur when the node rejects a transaction that is structurally invalid. | Code | Name | Description | How to fix | | ---- | ------------------------------------ | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | 110 | `VerifierKeyNotSet` | Contract deployed without required verifier key | Include verifier keys when deploying the contract | | 111 | `TransactionTooLarge` | Transaction exceeds maximum allowed size | Reduce transaction payload; split into multiple transactions | | 112 | `VerifierKeyTooLarge` | Verifier key exceeds deserialization limit | Use a smaller circuit or contact Midnight support | | 113 | `VerifierKeyNotPresent` | Referenced verifier key not found | Deploy the contract with the verifier key before calling the circuit | | 114 | `ContractNotPresent` | Transaction references a non-existent contract | Verify contract address; deploy the contract first | | 115 | `InvalidProof` | Zero-knowledge proof verification failed | Regenerate the proof. Ensure the proof server is compatible | | 116 | `BindingCommitmentOpeningInvalid` | Binding commitment was incorrectly opened | Internal Zswap error — rebuild the transaction | | 117 | `NotNormalized` | Transaction is not in normal form | Rebuild with the SDK; normalize the transaction before submission | | 118 | `FallibleWithoutCheckpoint` | Fallible transcript missing initial checkpoint | Add kernel.checkpoint() at the start of fallible sections | | 119 | `ClaimReceiveFailed` | Failed to claim a coin commitment receive | Coin commitment format error; rebuild the transaction | | 120 | `ClaimSpendFailed` | Failed to claim a coin commitment spend | Coin commitment format error; rebuild the transaction | | 121 | `ClaimNullifierFailed` | Failed to claim a nullifier | Nullifier format error; rebuild the transaction | | 122 | `ClaimCallFailed` | Failed to claim a contract call | Contract call format error; rebuild the transaction | | 123 | `InvalidSchnorrProof` | Fiat-Shamir Schnorr proof verification failed | Signing error — regenerate the transaction signature | | 124 | `UnclaimedCoinCom` | Contract-owned output left unclaimed | Ensure you claim all contract outputs in the transaction before submitting the transaction | | 125 | `UnclaimedNullifier` | Contract-owned coin input left unauthorized | You must authorize all contract inputs | | 126 | `Unbalanced` | Negative balance in a token type | Transaction doesn't balance. Check token amounts | | 127 | `Zswap` | Zswap offer is structurally malformed | Rebuild the Zswap offer and check proof validity | | 128 | `BuiltinDecode` | FAB (field-aligned binary) decode error | Internal encoding error. Verify data formats | | 129 | `GuaranteedLimit` | Exceeded guaranteed section limits | Reduce the guaranteed section size | | 130 | `MergingContracts` | Error merging contract intents | These contracts cannot merge; check configuration | | 131 | `CantMergeTypes` | Attempted to merge incompatible transaction types | Transaction types must be compatible for merging | | 132 | `ClaimOverflow` | Claimed coin value overflows deltas | Token amounts exceed representable range | | 133 | `ClaimCoinMismatch` | ClaimRewards coin doesn't match the real coin | Rebuild the claim with correct coin data | | 134 | `KeyNotInCommittee` | Signing key is not a committee member | Only committee members can sign this operation | | 135 | `InvalidCommitteeSignature` | Committee signature verification failed | Verify the signing key and signature | | 136 | `ThresholdMissed` | Committee approval threshold not met | Gather more committee signatures | | 137 | `TooManyZswapEntries` | Too many Zswap entries (>=2^16) | Reduce the number of shielded operations | | 138 | `BalanceCheckOverspend` | Negative balance in a transaction segment | Segment spends more than available; check amounts | | 139 | `UnknownError` | Unclassified malformed transaction error | Check node logs for details | | 166 | `InvalidNetworkId` | Transaction's network ID doesn't match the node's network | Verify `networkId` matches the target (for example, `undeployed` for devnet); check `setNetworkId()` | | 167 | `IllegallyDeclaredGuaranteed` | Guaranteed segment (0) used where forbidden | Don't use `segment_id` 0 for intents | | 168 | `FeeCalculation` | Fee calculation error | Transaction size or timing parameters are invalid | | 169 | `InvalidDustRegistrationSignature` | DUST registration signature verification failed | Regenerate DUST registration with correct keys | | 170 | `InvalidDustSpendProof` | DUST spend proof verification failed | Regenerate DUST spend proof | | 171 | `OutOfDustValidityWindow` | DUST outside its validity time window | DUST creation time is outside the allowed window; use fresher DUST | | 172 | `MultipleDustRegistrationsForKey` | Multiple DUST registrations for same key in one intent | Only one DUST registration per key per intent | | 173 | `InsufficientDustForRegistrationFee` | Not enough DUST to pay registration fee | Acquire more DUST before registering | | 174 | `MalformedContractDeploy` | Contract deployment is structurally invalid | Check for non-zero balance or incorrect charged state in deploy | | 175 | `IntentSignatureVerificationFailure` | Intent signature verification failed | Regenerate intent signatures | | 176 | `IntentSignatureKeyMismatch` | Signing key doesn't match verifying key | Use the correct signing key for the intent | | 177 | `IntentSegmentIdCollision` | Duplicate `segment_id` in intent merge | Each intent must have a unique `segment_id` | | 178 | `IntentAtGuaranteedSegmentId` | Intent placed at `segment_id` 0 (reserved for guaranteed) | Use `segment_id` >= 1 for intents | | 179 | `UnsupportedProofVersion` | Proof version not supported | Update SDK/proof server to a compatible version | | 180 | `GuaranteedTranscriptVersion` | Guaranteed transcript version not supported | Update to a compatible ledger/SDK version | | 181 | `FallibleTranscriptVersion` | Fallible transcript version not supported | Update to a compatible ledger/SDK version | | 182 | `TransactionApplicationError` | Intent TTL expired, too far in future, or duplicate | Check intent timing; avoid resubmitting same intent | | 183 | `BalanceCheckOutOfBounds` | Balance overflow/underflow in a segment | Token amounts in a segment exceed representable range | | 184 | `BalanceCheckConversionFailure` | Failed to convert balance to i128 | Token amount too large for internal representation | | 185 | `PedersenCheckFailure` | Binding commitment mismatch | Internal cryptographic error — rebuild the transaction | | 186 | `EffectsCheckFailure` | Transaction effects validation failed | Declared effects don't match computed effects | | 187 | `DisjointCheckFailure` | Input/output sets are not disjoint | Shielded and transient inputs/outputs must not overlap | | 188 | `SequencingCheckFailure` | Call graph sequencing violated | Contract calls must respect ordering constraints | | 189 | `InputsNotSorted` | Unshielded inputs are not sorted | Sort unshielded inputs before submission | | 190 | `OutputsNotSorted` | Unshielded outputs are not sorted | Sort unshielded outputs before submission | | 191 | `DuplicateInputs` | Duplicate unshielded inputs | Remove duplicate inputs from the transaction | | 192 | `InputsSignaturesLengthMismatch` | Input count doesn't match signature count | Ensure each input has a corresponding signature | ### Infrastructure errors (150–155, 165)[​](#infrastructure-errors-150155-165 "Direct link to Infrastructure errors (150–155, 165)") Errors that occur when the node encounters infrastructure errors not directly related to transaction content. | Code | Name | Description | How to fix | | ---- | ------------------------------- | -------------------------------------- | ---------------------------------------------------------- | | 150 | `LedgerCacheError` | Ledger cache mutex/lock poisoned | Restart the node; this is an internal concurrency error | | 151 | `NoLedgerState` | No ledger state present in the node | Node may not be fully synced; wait for sync to complete | | 152 | `LedgerStateScaleDecodingError` | SCALE decoding of ledger state failed | The node state might be corrupt; try a resync | | 153 | `ContractCallCostError` | Failed to calculate contract call cost | Internal cost model error | | 154 | `BlockLimitExceededError` | Transaction exceeds block limits | Reduce transaction size or wait for a less congested block | | 155 | `FeeCalculationError` | Fee calculation failed | Internal fee model error | | 165 | `GetTransactionContextError` | Failed to retrieve transaction context | Internal node error | ### System transaction errors (201–210)[​](#system-transaction-errors-201210 "Direct link to System transaction errors (201–210)") Errors that occur when the node encounters errors from governance and bridge system transactions. These are special transactions submitted by the network's governance mechanisms. | Code | Name | Description | How to fix | | ---- | ------------------------------ | ---------------------------------------------- | -------------------------------------------------- | | 201 | `IllegalPayout` | Payout exceeds remaining supply or bridge pool | Payout amount is too large for available funds | | 202 | `InsufficientTreasuryFunds` | Treasury doesn't have enough funds | Requested amount exceeds treasury balance | | 203 | `CommitmentAlreadyPresent` | Faerie-gold double-commitment attempt | Commitment already exists in the tree | | 204 | `UnknownError` | Unclassified system transaction error | Check node logs | | 205 | `ReplayProtectionFailure` | System transaction replay protection violated | Duplicate system transaction | | 206 | `IllegalReserveDistribution` | Reserve distribution exceeds supply | Distribution amount exceeds available reserves | | 207 | `GenerationInfoAlreadyPresent` | DUST generation info already inserted | Duplicate generation info | | 208 | `InvalidBasisPoints` | Bridge fee basis points >= 10,000 | Basis points must be between 0 and 9,999 | | 209 | `InvariantViolation` | Protocol-level invariant violated | Transaction would break fundamental protocol rules | | 210 | `TreasuryDisabled` | Attempted to access disabled treasury | Treasury feature is not enabled | ### Host API error (255)[​](#host-api-error-255 "Direct link to Host API error (255)") Errors that occur when the node encounters errors from the host API. | Code | Name | Description | How to fix | | ---- | -------------- | ---------------------------- | --------------------------------------- | | 255 | `HostApiError` | Error in host API processing | Internal runtime error; check node logs | ## Pallet dispatch errors[​](#pallet-dispatch-errors "Direct link to Pallet dispatch errors") When a transaction fails inside a Substrate pallet, the error surfaces as `DispatchError::Module { index, error }`. The `index` identifies the pallet and `error` is the SCALE-encoded variant index within that pallet's error enum. Below is a list of the Midnight node specific pallet errors categorized by pallet and variant. ### Pallet index map[​](#pallet-index-map "Direct link to Pallet index map") Below is a list of the Midnight node specific pallet indices and their descriptions. | Index | Pallet | Description | | ----- | ---------------------------------------- | --------------------------- | | 5 | `pallet_midnight` | Core Midnight ledger pallet | | 6 | `pallet_midnight_system` | System transaction pallet | | 13 | `pallet_cnight_observation` | cNIGHT bridge observation | | 44 | `pallet_federated_authority` | Governance authority | | 45 | `pallet_federated_authority_observation` | Authority observation | | 50 | `pallet_system_parameters` | System parameters | | 51 | `pallet_throttle` | Transaction throttling | ### `pallet_midnight`[​](#pallet_midnight "Direct link to pallet_midnight") Errors from the core pallet managing the ledger state and transactions. | Variant | Name | Description | | ------- | ------------------------------- | ---------------------------------------------- | | 0 | `NewStateOutOfBounds` | New ledger state is out of acceptable bounds | | 1 | `Deserialization` | Wraps DeserializationError (codes 0–11) | | 2 | `Serialization` | Wraps SerializationError (codes 50–63) | | 3 | `Transaction` | Wraps TransactionError (codes 100–210) | | 4 | `LedgerCacheError` | Ledger cache poisoned (code 150) | | 5 | `NoLedgerState` | No ledger state (code 151) | | 6 | `LedgerStateScaleDecodingError` | SCALE decode failure (code 152) | | 7 | `ContractCallCostError` | Cost calculation failure (code 153) | | 8 | `BlockLimitExceededError` | Block limit exceeded (code 154) | | 9 | `FeeCalculationError` | Fee calculation failure (code 155) | | 10 | `HostApiError` | Host API error (code 255) | | 11 | `NetworkIdNotString` | Network ID not a valid string | | 12 | `GetTransactionContextError` | Transaction context retrieval error (code 165) | ### `pallet_midnight_system`[​](#pallet_midnight_system "Direct link to pallet_midnight_system") Errors from the system transaction pallet. | Variant | Name | Description | | ------- | ------------------------------------------ | ---------------------------------------- | | 0 | `LedgerApiError` | Wraps full LedgerApiError | | 1 | `SystemTransactionNotAllowedForGovernance` | Governance-disallowed system transaction | ### `pallet_federated_authority`[​](#pallet_federated_authority "Direct link to pallet_federated_authority") Errors from the multi-collective governance authority pallet. | Variant | Name | Description | | ------- | ----------------------------- | --------------------------------------- | | 0 | `MotionAlreadyApproved` | Authority already approved this motion | | 1 | `MotionApprovalMissing` | Approver not in the approval list | | 2 | `MotionApprovalExceedsBounds` | Exceeds maximum authority bodies | | 3 | `MotionNotFound` | Motion does not exist | | 4 | `MotionNotEnded` | Motion voting not yet complete | | 5 | `MotionHasEnded` | Motion ended; no more changes allowed | | 6 | `MotionTooEarlyToClose` | Approval period hasn't ended yet | | 7 | `MotionAlreadyExists` | Motion already exists | | 8 | `MotionExpired` | Motion expired without enough approvals | | 9 | `MotionWeightBoundTooLow` | Weight bound too low for the call | ### `pallet_cnight_observation`[​](#pallet_cnight_observation "Direct link to pallet_cnight_observation") Errors from the cNIGHT bridge integration pallet. | Variant | Name | Description | | ------- | ------------------------------ | ------------------------------------- | | 0 | `MaxCardanoAddrLengthExceeded` | Cardano wallet address too long | | 1 | `MaxRegistrationsExceeded` | Too many registrations | | 2 | `LedgerApiError` | Wraps LedgerApiError | | 3 | `InherentAlreadyExecuted` | Only one inherent call per block | | 4 | `CardanoPositionRegression` | Next Cardano position doesn't advance | | 5 | `TooManyUtxos` | UTXO count exceeds capacity | ### `pallet_federated_authority_observation`[​](#pallet_federated_authority_observation "Direct link to pallet_federated_authority_observation") Errors from the multi-collective governance synchronization pallet. | Variant | Name | Description | | ------- | ------------------------- | -------------------------------- | | 0 | `EmptyMembers` | Membership set is empty | | 1 | `DuplicatedMembers` | Duplicate members in the set | | 2 | `InherentAlreadyExecuted` | Only one inherent call per block | ### `pallet_system_parameters`[​](#pallet_system_parameters "Direct link to pallet_system_parameters") Errors from the system parameters pallet. | Variant | Name | Description | | ------- | ------------ | ---------------------------------- | | 0 | `UrlTooLong` | URL exceeds maximum allowed length | ## JSON-RPC error codes[​](#json-rpc-error-codes "Direct link to JSON-RPC error codes") The Midnight node uses standard JSON-RPC 2.0 error codes from the `jsonrpsee` crate. These are the most common error codes you might encounter when interacting with the node. | Code | Name | Used in | Description | | ------ | ---------------- | --------------------------------------- | -------------------------------------------------------------------------------------- | | -32602 | `INVALID_PARAMS` | State RPC, Block RPC, Events, Peer Info | Bad contract address, account address, block hash, peer ID, or other invalid parameter | | -32603 | `INTERNAL_ERROR` | Peer Info RPC, System Parameters RPC | Failed to send/receive internal requests, runtime API failures | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Set up full node This guide provides step-by-step instructions for setting up a full node for Midnight. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before setting up your Midnight full node, ensure you have the following: * [Cardano-db-sync instance set up](/nodes/cardano-db-sync.md) with accessible PostgreSQL port. * Sufficient resources (CPU, memory, and storage). ## Install Midnight node[​](#install-midnight-node "Direct link to Install Midnight node") The Midnight node is the core client for the Midnight protocol. Install the Midnight node by following the steps below. Create directories for the node: ``` mkdir -p ~/data ~/res ~/.local/bin ``` * `~/data`: For node database/base path. * `~/res`: For chain configuration files. * All owned by `midnight` user. Download and install the Midnight node binary: Create a temporary directory and navigate to it: ``` mkdir -p ~/tmp && cd ~/tmp ``` Download the Midnight node binary: ``` curl -L -O https://github.com/midnightntwrk/midnight-node/releases/download/node-0.22.5/midnight-node-0.22.5-linux-amd64.tar.gz ``` note Always verify the latest release version from the [compatibility matrix](/relnotes/support-matrix.md) before downloading the binary. Extract the binary: ``` tar -xvzf midnight-node-0.22.5-linux-amd64.tar.gz ``` Move the binary to the local bin directory: ``` mv ~/tmp/midnight-node ~/.local/bin/ ``` Move the chain config files to the res directory: ``` mv ~/tmp/res ~/res ``` Reload the shell environment: ``` source ~/.bashrc # or source ~/.zshrc ``` ### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables") Create an `.env` configuration file and set the environment variables for the PostgreSQL database: ``` # PostgreSQL connection export POSTGRES_HOST="localhost" export POSTGRES_DB="cexplorer" export POSTGRES_PORT="5432" export POSTGRES_USER="midnight" export POSTGRES_PASSWORD="YOUR_POSTGRES_PASSWORD" # Cardano database connection string export DB_SYNC_POSTGRES_CONNECTION_STRING="postgresql://midnight:YOUR_POSTGRES_PASSWORD@localhost:5432/cexplorer" export NODE_NAME="your_node_name" ``` Load the variables into the shell environment: ``` source ~/.env ``` Confirm that the variables are loaded successfully: ``` echo $DB_SYNC_POSTGRES_CONNECTION_STRING ``` ## Run a full node[​](#run-a-full-node "Direct link to Run a full node") Once the environment variables are set, run the Midnight node using the following command: * Preview * Preprod ``` midnight-node \ --chain /home/midnight/res/preview/chain-spec-raw.json \ --base-path /home/midnight/data \ --pool-limit 35 \ --name $NODE_NAME \ --no-private-ip ``` ``` midnight-node \ --chain /home/midnight/res/preprod/chain-spec-raw.json \ --base-path /home/midnight/data \ --pool-limit 35 \ --name $NODE_NAME \ --no-private-ip ``` ### Available networks[​](#available-networks "Direct link to Available networks") The `--chain` flag lets you specify the network to run the node on. The available networks are: * `local`: For local testing. This is the default network if you do not specify a network. * `preview`: For the Preview network. * `preprod`: For the Preprod network. * `mainnet`: For the Mainnet network. ## Verify the node[​](#verify-the-node "Direct link to Verify the node") Monitor the node's logs to ensure it syncs with the network. What to look for in the output: * **Cardano db connection**: If you see `Postgres connection established`, then your DB settings are correct. * **Peers**: Look for `IDLE (0 peers)`. If it stays at 0, then check your firewall (port 30333) or the `-bootnodes` address. * **Syncing**: You should see `Best: #0 ...` start to increment as it pulls blocks from the network. ## Full node vs. archive node[​](#full-node-vs-archive-node "Direct link to Full node vs. archive node") A full node syncs with the blockchain, validates transactions, and provides real-time state queries. It prunes historical states older than a configurable number (defaulting to 256 blocks). This makes it suitable for most DApp development and real-time interactions with the network. Its key advantage lies in its efficient use of disk space, requiring significantly less storage than an archive node. An archive node maintains the entire history of the blockchain, including all blocks and states. This comprehensive storage consumes substantial disk space. However, it is essential for use cases requiring access to historical data, such as building block explorers, conducting in-depth debugging, or querying past events. To run the Midnight node in archive mode, use the `--pruning archive` flag. ``` midnight-node \ --chain /home/midnight/res/preview/chain-spec-raw.json \ --base-path /home/midnight/data \ --pruning archive \ --no-private-ip \ --name $NODE_NAME ``` ## Next steps[​](#next-steps "Direct link to Next steps") With the full node set up, you can start using the [Node endpoints](/nodes/node-endpoints.md) to interact with the Midnight blockchain. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Node endpoints You can run your own node for interacting with the Midnight Network or connect to public endpoints provided by infrastructure service providers. This guide provides instructions on how to use the public network endpoints for the Midnight blockchain. ## Quickstart[​](#quickstart "Direct link to Quickstart") Run your first request against the Preview network: * cURL * TypeScript * Python * Rust ``` curl -X POST https://rpc.preview.midnight.network/ \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"system_chain","params":[],"id":1}' ``` ``` const res = await fetch("https://rpc.preview.midnight.network/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", method: "system_chain", params: [], id: 1 }) }); console.log(await res.json()); ``` ``` import requests response = requests.post( "https://rpc.preview.midnight.network/", json={ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ) print(response.json()) ``` ``` use reqwest::Client; use serde_json::json; #[tokio::main] async fn main() { let client = Client::new(); let res = client.post("https://rpc.preview.midnight.network/") .json(&json!({ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 })) .send() .await .unwrap(); let body = res.text().await.unwrap(); println!("{}", body); } ``` ## Public network endpoints[​](#public-network-endpoints "Direct link to Public network endpoints") Midnight maintains public endpoints for two test networks, Preview and Preprod, and for the Mainnet production network. For the full per-network reference, including indexer, faucet, and proof server endpoints, see [Networks and environments](/guides/networks-and-environments.md). * Preview * Preprod * Mainnet The primary development environment maintained by core engineering. | Service | URL | | ------------ | -------------------------------------------------------------------------------------- | | RPC endpoint | `https://rpc.preview.midnight.network/` | | WebSocket | `wss://rpc.preview.midnight.network/` | | Explorer | | Pre-production environment for final testing before Mainnet deployment. | Service | URL | | ------------ | -------------------------------------------------------------------------------------- | | RPC endpoint | `https://rpc.preprod.midnight.network/` | | WebSocket | `wss://rpc.preprod.midnight.network/` | | Explorer | | The production network. | Service | URL | | ------------ | -------------------------------------------------------------------------------------- | | RPC endpoint | `https://rpc.mainnet.midnight.network/` | | WebSocket | `wss://rpc.mainnet.midnight.network/` | | Explorer | | Network support Midnight provides public endpoints for development and testing purposes. For production DApps, consider running your own RPC node or using a dedicated infrastructure provider for better reliability and performance. ## Common RPC queries[​](#common-rpc-queries "Direct link to Common RPC queries") The following examples show how to query the chain information, list available RPC methods, and get the latest block for the Preview network. ### Query chain information[​](#query-chain-information "Direct link to Query chain information") Example query to get the chain name for the Preview network: ``` curl -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' \ https://rpc.preview.midnight.network/ ``` ### List available RPC methods[​](#list-available-rpc-methods "Direct link to List available RPC methods") Query all available RPC methods and save to a file for the Preview network: ``` curl -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' \ https://rpc.preview.midnight.network/ \ | jq '.' > rpc_methods.json ``` ### Get latest block[​](#get-latest-block "Direct link to Get latest block") Example query to get the latest block for the Preview network: ``` curl -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' \ https://rpc.preview.midnight.network/ ``` ## Insomnia API collection[​](#insomnia-api-collection "Direct link to Insomnia API collection") The Insomnia collection provides pre-configured requests for interacting with Midnight RPC endpoints. 1 ### Download[​](#download "Direct link to Download") Download the collection file: [Midnight Node Insomnia collection](/files/Insomnia_collection_2026-04-20.json) 2 ### Import the collection[​](#import-the-collection "Direct link to Import the collection") Open Insomnia and select **Import**. Choose the **File** tab and select the downloaded file. Click **Scan** to import the collection. info Download Insomnia from the [official website](https://insomnia.rest/download) if you haven't already. 3 ### Use the collection[​](#use-the-collection "Direct link to Use the collection") Locate the Midnight Node collection in your workspace. Update the RPC endpoint if needed. For example, if you are using the Preprod network, update the endpoint to `https://rpc.preprod.midnight.network/`. Run requests to explore available methods. ![Insomnia app screenshot](/assets/images/insomnia_app-19730707c1729dba1e7f67d3338793b5.gif) ## Troubleshoot[​](#troubleshoot "Direct link to Troubleshoot") These are some of the common issues that you might encounter and how to fix them. ### Request fails with 405[​](#request-fails-with-405 "Direct link to Request fails with 405") Ensure you are using `POST`, not `GET`. ### Invalid JSON response[​](#invalid-json-response "Direct link to Invalid JSON response") Check JSON formatting and the `Content-Type` header. The request body should be a valid JSON object. ### Empty result[​](#empty-result "Direct link to Empty result") Some RPC methods require parameters. To see the full list of available methods and required parameters, see the [Node OpenRPC specification](https://github.com/midnightntwrk/midnight-node/blob/main/docs/openrpc.json). ## Next steps[​](#next-steps "Direct link to Next steps") * Explore the [Node OpenRPC specification](https://github.com/midnightntwrk/midnight-node/blob/main/docs/openrpc.json) for full method documentation --- > For the complete documentation index, see [llms.txt](/llms.txt) # Set up RPC node for Midnight Remote Procedure Call (RPC) nodes serve as the primary interface for applications to interact with the Midnight blockchain programmatically. These nodes expose WebSocket and HTTP APIs that enable developers to submit transactions, query blockchain data, subscribe to events, and integrate DApps with the network. This guide provides step-by-step instructions for setting up an RPC node on the Midnight blockchain. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before setting up your Midnight RPC node, ensure you have the following: * [Cardano-db-sync instance set up](/nodes/cardano-db-sync.md) with accessible PostgreSQL port. * [Midnight node set up](/nodes/full-node.md#install-midnight-node) with the environment variables set. ## Run the Midnight node in RPC mode[​](#run-the-midnight-node-in-rpc-mode "Direct link to Run the Midnight node in RPC mode") Use the following command to run Midnight node in RPC mode. Choose the configuration for your target network. By default, the node binds its RPC interface to `127.0.0.1` (localhost) and exposes only the `Safe` method set. This is the recommended starting point: the endpoint is reachable from the local machine only, so it is not directly exposed to the internet. To make it available to external clients, place a hardened reverse proxy in front of it rather than binding the node itself to a public interface. See [Exposing the RPC endpoint](#exposing-the-rpc-endpoint). * Preview * Preprod ``` midnight-node \ --chain /home/midnight/res/preview/chain-spec-raw.json \ --base-path /home/midnight/data \ --rpc-port 9944 \ --rpc-methods Safe ``` ``` midnight-node \ --chain /home/midnight/res/preprod/chain-spec-raw.json \ --base-path /home/midnight/data \ --rpc-port 9944 \ --rpc-methods Safe ``` ### Configure RPC methods[​](#configure-rpc-methods "Direct link to Configure RPC methods") * `--rpc-port 9944`: The TCP port the RPC server listens on. * `--rpc-methods Safe`: Exposes only the safe RPC method set. Avoid `Unsafe`/`Auto` on any node that is reachable beyond localhost, as they expose methods that can control the node. ## Exposing the RPC endpoint[​](#exposing-the-rpc-endpoint "Direct link to Exposing the RPC endpoint") For a public RPC node, the recommended approach is to keep the node bound to localhost (the default above) and front it with a reverse proxy (for example, nginx or Caddy) that terminates TLS, restricts allowed origins, and applies rate limiting. Combine this with a firewall that only permits the P2P port and your proxy's port. The node can also expose RPC directly with the flags below. These bypass the localhost default, so only use them on a trusted, firewalled network and never point them at the open internet without a proxy in front. warning Binding the RPC interface to a public address with permissive CORS exposes your node to abuse, resource exhaustion, and data scraping. Treat the options below as advanced and secure them with a firewall, TLS, and scoped origins. * `--rpc-external`: Binds the RPC server to all interfaces so it is reachable from external networks. Without this flag, RPC stays on `127.0.0.1`. The unified RPC server handles both HTTP and WebSocket connections on this interface. * `--rpc-cors `: Sets the allowed CORS origins. Prefer an explicit comma-separated list of trusted domains (for example, `--rpc-cors https://app.example.com`) over `all`, which permits requests from any origin. * `--no-private-ip`: Disables the safety check that refuses external binding on private IP ranges. Only relevant when intentionally exposing the node. ### Test connectivity[​](#test-connectivity "Direct link to Test connectivity") Ensure the node's P2P port (default: `30333`) is open and reachable for network communication. Use tools like `telnet`, `netcat`, or `nmap` to verify the port status and ensure the node is properly connected to the network. Additionally, to preview the available RPC methods, run the following curl command, which lists all endpoints exposed by the node: ``` curl -H "Content-Type: application/json" \ -X POST \ -d '{ "jsonrpc":"2.0", "id":1, "method":"rpc_methods", "params":[] }' \ http://127.0.0.1:9944 ``` ## Next steps[​](#next-steps "Direct link to Next steps") With the RPC node set up, you can start using the [Node endpoints](/nodes/node-endpoints.md) to interact with the Midnight blockchain. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact toolchain Compact is Midnight's smart contract programming language, designed for building secure, efficient, and adaptable decentralized applications. The Compact toolchain includes the Compact compiler, formatter, and the Compact "fixup" tool. The compiler translates Compact smart contract code into JavaScript implementations and a representation of the zero-knowledge circuits. [Link to related documentation](/compact/compilation-and-tooling/compiler-usage.md) To install the toolchain, first install the [compact devtools](/relnotes/compact-tools.md) and then use `compact update` (for the latest version) or `compact update 0.28.0` (for a specific version, such as 0.28.0 in this case). *** Version0.34.0 StatusAll ### [Release 0.34.0](/relnotes/compact/toolchain-0.34.0)LATEST #### Compact language 0.26.0 25 August 2026 #### Summary --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact.js Compact.js provides a TypeScript-based execution environment for smart contracts compiled with the Compact compiler. When a Compact smart contract is compiled, the output includes a JavaScript file and a TypeScript declaration file. Compact.js uses these files at runtime to execute the circuits. The circuit execution results are then used by higher-level tools and frameworks (such as Midnight.js) to create and submit transactions to the Midnight blockchain. For more information, see the [Compact language documentation](/compact.md). *** Version2.5.3 StatusAll ### [Release 2.5.3](/relnotes/compact-js/compact-js-2-5-3)LATEST 9 July 2026 #### Artifacts * [NPM Package](https://www.npmjs.com/package/@midnight-ntwrk/compact-js/v/2.5.3) * [GitHub release](https://github.com/midnightntwrk/midnight-sdk/releases/tag/compact-js-v2.5.3) #### Summary * Fixed the CommonJS exports configuration of the package. * Security update: bumped the `tar` dependency to 7.5.16. * Updated development dependencies and release automation. * First version published to npm from the migrated `midnightntwrk/midnight-sdk` repository; supersedes the 2.5.1 and 2.5.2 alignment versions. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compact developer tools Compact is Midnight's dedicated smart contract programming language, designed for building secure, efficient, and adaptable decentralized applications. Compact developer tools are a command-line utility for installing, updating, managing, and running the Compact toolchain and compiler. [Link to related documentation](/compact.md) To download the component, click the appropriate link under **Artifacts**. *** Version0.5.2 StatusAll ### [Release 0.5.2](/relnotes/compact-tools/compact-tools-0-5-2)LATEST 18 August 2026 #### Artifacts * [Compact developer tools](https://github.com/midnightntwrk/compact/releases/tag/compact-v0.5.2) #### Summary * `compact compile --help` now forwards to the underlying `compactc`, so the help output lists every flag the selected compiler accepts, including `--feature-zkir-v3`. * Update an existing installation with `compact self update`. --- > For the complete documentation index, see [llms.txt](/llms.txt) # DApp Connector API DApp Connector API allows decentralized applications (DApps) to request wallet access, verify authorization, and retrieve service URIs for interacting with the Midnight network. [Link to related documentation](/api-reference/dapp-connector.md) To download the component, click the appropriate link under **Artifacts**. *** Version4.0.1 StatusAll ### [Release 4.0.1](/relnotes/dapp-connector-api/dapp-connector-api-4-0-1)LATEST 17 February 2026 #### Artifacts * [NPM package](https://www.npmjs.com/package/@midnight-ntwrk/dapp-connector-api) * [GitHub release](https://github.com/midnightntwrk/midnight-dapp-connector-api/releases/tag/v4.0.1) #### Summary * All transacting methods now accept the `payFees` option that was previously only available on `makeIntent`. * Disabling fee payment supports sponsored-fee flows where a separate wallet pays transaction fees. * Backwards-compatible: omitting the option keeps the existing fee payment behavior. * The motivation for the option is documented in the API specification. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Ledger The ledger in Midnight is a public record of contract states and token states, consisting of Zswap’s cryptographic commitments and a mapping of contract addresses to their respective states. [Link to related documentation](/concepts/how-midnight-works/semantics.md) To download the component, click the appropriate link under **Artifacts**. *** Version8.1.0 StatusAll ### [Release 8.1.0](/relnotes/ledger/ledger-8-1-0)LATEST 13 May 2026 #### Artifacts * [Ledger](https://www.npmjs.com/package/@midnight-ntwrk/ledger-v8) * [Onchain Runtime](https://www.npmjs.com/package/@midnight-ntwrk/onchain-runtime-v3) * [Proof Server](https://hub.docker.com/r/midnightntwrk/proof-server/) #### Summary * Added incremental garbage collector in `storage-core` with time-bounded execution * Allowed ParityDB to use existing instance and share backends through generic `Deref` * Fixed race condition in `force_as_arc` that could cause deadlocks * Fixed panic in `Sp` serialization with mixed promoted/unpromoted keys * Fixed memory leak from pending `Update` not removed before `cache_insert_new_key` * Corrected `Sp::into_tracked` behavior * Exposed finer-grained control and event contents for wallet in WASM bindings --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight Indexer The Midnight Indexer is a set of components designed to optimize the flow of blockchain data from a Midnight node to end-user applications. It retrieves history of blocks, processes them, stores indexed data efficiently, and provides a GraphQL API for queries and subscriptions. To download the component, click the appropriate link under **Artifacts**. *** Version4.3.3 StatusAll ### [Release 4.3.3](/relnotes/midnight-indexer/midnight-indexer-4-3-3)LATEST 4 June 2026 #### Artifacts * [Chain Indexer Docker image](https://hub.docker.com/r/midnightntwrk/chain-indexer) * [Indexer API Docker image](https://hub.docker.com/r/midnightntwrk/indexer-api) * [Wallet Indexer Docker image](https://hub.docker.com/r/midnightntwrk/wallet-indexer) * [Indexer Standalone Docker image](https://hub.docker.com/r/midnightntwrk/indexer-standalone) * [SPO Indexer Docker image](https://hub.docker.com/r/midnightntwrk/spo-indexer) #### Summary * Added per-connection and per-client subscription quotas to GraphQL WebSocket * Introduced `@beta` GraphQL directive for in-flight API fields * Added per-tree end indexes (`zswapEndIndex`, `dustCommitmentEndIndex`, `dustGenerationEndIndex`) to `Block` * Added lazy `transaction` reference on nullifier event types * Tightened shielded nullifier transactions input validation * Renamed dust nullifier byte fields with `LeBytes` suffix (breaking, `@beta` only) * Fixed `dustGenerations` subscription to deliver dtime updates on fresh subscriptions --- > For the complete documentation index, see [llms.txt](/llms.txt) # Midnight.js Midnight.js is a client library designed to facilitate the development of decentralized applications on the Midnight blockchain. [Link to related documentation](/api-reference/midnight-js/packages.md) To download the component, click the appropriate link under **Artifacts**. *** Version4.1.1 StatusAll ### [Release 4.1.1](/relnotes/midnight-js/midnight-js-4-1-1)LATEST 2 June 2026 #### Artifacts * [NPM Package](https://www.npmjs.com/search?q=midnight-ntwrk) #### Summary * Renamed `IndexerFormattedError.cause` to `.errors` for ES2022 compatibility (breaking) * Applied full password policy to signing key and private state export operations * Emitted contract state for `blockHeight`/`blockHash` configurations * Hardened error handling in `indexer-public-data-provider` * Added signing key validation on import * Warned on plain HTTP/WS for non-loopback provider URLs * Added qanet support via NIGHT/DUST faucet flow in `testkit-js` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Wallet API Deprecated The Wallet API is deprecated. Wallet functionality is now handled through the [Wallet SDK](/relnotes/wallet.md). Please migrate to the Wallet SDK for all wallet operations and integrations. *** Version5.0.0 StatusAll ### [Release 5.0.0](/relnotes/midnight-wallet-api/midnight-wallet-api-5-0-0)DEPRECATED 12 May 2025 #### Artifacts * [NPM Package](https://www.npmjs.com/package/@midnight-ntwrk/wallet-api/v/5.0.0) #### Summary * BLS Support. * Adds new sync progress API. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Environments and endpoints Midnight uses dedicated network services such as RPC nodes, indexer API, and proof server to power DApp development and interaction across the Preview, Preprod, and Mainnet environments. ## Preview[​](#preview "Direct link to Preview") The Preview environment is intended for early-stage development and experimentation. Use these endpoints to connect your DApp to Midnight Preview environment. | Service | URL | | ----------------- | --------------------------------------------------------- | | Node RPC | | | Indexer (GraphQL) | | | Faucet UI | | | Block explorers | | | | | | | | ## Preprod[​](#preprod "Direct link to Preprod") The Preprod environment is designed for final testing before mainnet deployment. Use these endpoints to connect your DApp to Midnight Preprod environment. | Service | URL | | ----------------- | --------------------------------------------------------- | | Node RPC | | | Indexer (GraphQL) | | | Faucet UI | | | Block explorers | | | | | | | | ## Mainnet[​](#mainnet "Direct link to Mainnet") The Mainnet environment is the production network. Use these endpoints to connect your DApp to Midnight Mainnet. | Service | URL | | ----------------- | --------------------------------------------------------- | | Node RPC | | | Indexer (GraphQL) | | | Block explorers | | | | | | | | | cNgD DApp | | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Node Node is a core component of the Midnight network, responsible for syncing, validating transactions, and maintaining the chain state. [Link to related documentation](/nodes.md) To download the component, click the appropriate link under **Artifacts**. *** Version1.0.1 StatusAll ### [Release 1.0.1](/relnotes/node/node-1-0-1)LATEST 14 July 2026 #### Artifacts * [Midnight node](https://hub.docker.com/r/midnightntwrk/midnight-node) * [GitHub release](https://github.com/midnightntwrk/midnight-node/releases/tag/node-1.0.1) #### Summary * `unsafe_allow_symlinks` now has a default value, so nodes without a TOML configuration file boot without the missing-field error from v1.0.0. * Regenerated the Preview network genesis and chain spec. * Removed the incorrect `NIGHT` asset name from the Preview reserve configuration. * Backported the ledger version bump and updated dependencies to fix the release build. * Ships with `toolkit-1.0.0` and `runtime-1.0.0`; no runtime upgrade is required. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Onchain Runtime Onchain Runtime releases are now part of Ledger Starting with Ledger 7.0.0, Onchain Runtime releases are included as part of the [Ledger release](/relnotes/ledger.md). For the most recent Onchain Runtime releases and updates, please refer to the [release notes overview](/relnotes/overview.md). Onchain Runtime is a component of the Midnight infrastructure that enables zero-knowledge proof generation, transaction verification, and privacy-preserving transaction processing. [Link to related documentation](/api-reference/onchain-runtime.md) To download the component, click the appropriate link under **Artifacts**. *** Version4.0.0 StatusAll ### [Release 4.0.0](/relnotes/onchain-runtime/onchain-runtime-4-0-0)UNSUPPORTED 12 May 2025 #### Artifacts * [Onchain Runtime](https://www.npmjs.com/package/@midnight-ntwrk/onchain-runtime) #### Summary * Integrated with the new storage model, making required objects `Storable` to allow storing MPT leafs as `Sp`s. * Added segment IDs to Zswap constructors. These should be set to `1` for fallible offers, and `0` for guaranteed offers. * Renamed `ZswapLocalStateNoKeys` to `ZswapLocalState`, removing the existing (with keys) state. * Switch from Pluto-Eris to BLS12-381. * Switched to using data providers instead of direct prover keys and parameters. * Add a data provider to fetch key material for Midnight. The source of this may be overridden with the `MIDNIGHT_PARAM_SOURCE` environment variable. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Latest stable release ## Compatibility[​](#compatibility "Direct link to Compatibility") This release delivers Midnight Ledger 8.0 on Preview, Preprod, and Mainnet, including updates to the runtime, SDKs and tooling. *** ## Environments[​](#environments "Direct link to Environments") Midnight uses dedicated network services such as RPC nodes, indexer API, and proof server to power DApp development and interaction across the Preview, Preprod, and Mainnet environments. To connect your application and configure these services correctly, see the [Environments and endpoints](/relnotes/network.md) reference. *** ## Compatible components[​](#compatible-components "Direct link to Compatible components") Building on Midnight requires a set of compatible components to work properly. When creating DApps, it’s important to use the latest stable version of each component. To view the full list of components and their compatible versions, see the [Compatibility matrix](/relnotes/support-matrix.md). *** ## Release notes and references[​](#release-notes-and-references "Direct link to Release notes and references") This list contains detailed release notes for each of the components that are required for DApp development. * Ledger
* Node
* Indexer
* Compact Compiler
* DApp Connector API
* Wallet SDK
* Midnight.js
* Compact JS *** --- > For the complete documentation index, see [llms.txt](/llms.txt) # Proof Server Proof Server releases are now part of Ledger Starting with Ledger 7.0.0, Proof Server releases are included as part of the [Ledger release](/relnotes/ledger.md). For the most recent Proof Server releases and updates, please refer to the [release notes overview](/relnotes/overview.md). Proof Server is a component of the Midnight infrastructure that enables zero-knowledge proof generation, transaction verification, and privacy-preserving transaction processing. [Link to related documentation](/guides/run-proof-server.md) To download the component, click the appropriate link under **Artifacts**. *** Version4.0.0 StatusAll ### [Release 4.0.0](/relnotes/proof-server/proof-server-4-0-0)UNSUPPORTED 12 May 2025 #### Artifacts * [Proof Server](https://hub.docker.com/r/midnightnetwork/proof-server/) #### Summary * Integrated with the new storage model, making required objects `Storable` to allow storing MPT leafs as `Sp`s. * Added segment IDs to Zswap constructors. These should be set to `1` for fallible offers, and `0` for guaranteed offers. * Renamed `ZswapLocalStateNoKeys` to `ZswapLocalState`, removing the existing (with keys) state. * Switch from Pluto-Eris to BLS12-381. * Switched to using data providers instead of direct prover keys and parameters. * Add a data provider to fetch key material for Midnight. The source of this may be overridden with the `MIDNIGHT_PARAM_SOURCE` environment variable. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Compatibility matrix *** note This matrix only reflects the latest tested versions. Earlier versions may still work, but we do not guarantee compatibility or provide support for them. * Preview * Preprod * Mainnet | Functional area | Component | Version | Notes | | ----------------------- | ------------------------------------- | ------- | ------------------------------------------------------- | | Network | Node (Midnight) | 1.0.1 | Preview network node | | Runtime and contracts | Compact devtools (`compact`) | 0.5.1 | Installs compilers, compiles contracts | | | Compact toolchain (`compact compile`) | 0.31.1 | Contract compiler for Midnight | | | Compact runtime | 0.16.0 | Runtime library for contracts | | | Compact JS | 2.5.1 | TypeScript execution environment for compiled contracts | | | Platform JS | 2.2.4 | Core abstractions and types | | | On-chain runtime | 3.0.0 | On-chain runtime support (v3) | | SDKs and APIs | Wallet SDK | 1.2.0 | SDK for building wallet integrations | | | Midnight.js | 4.1.1 | DApp framework: contracts, types, providers | | | testkit-js | 4.1.1 | E2E testing framework | | | DApp Connector API | 4.0.1 | Interface between DApps and wallets | | Indexing and data | Midnight Indexer | 4.3.5 | Preview indexer | | ZK and proving services | Proof server | 8.1.0 | Handles ZKP proof generation | | Functional area | Component | Version | Notes | | ----------------------- | ------------------------------------- | ------------ | ------------------------------------------------------- | | Network | Node (Midnight) | 1.0.2 | Preprod network node | | Runtime and contracts | Compact devtools (`compact`) | 0.5.1 | Installs compilers, compiles contracts | | | Compact toolchain (`compact compile`) | 0.31.1 | Contract compiler for Midnight | | | Compact runtime | 0.16.0 | Runtime library for contracts | | | Compact JS | 2.5.1 | TypeScript execution environment for compiled contracts | | | Platform JS | 2.2.4 | Core abstractions and types | | | On-chain runtime | 3.0.0 | On-chain runtime support (v3) | | SDKs and APIs | Wallet SDK | 1.2.0 | SDK for building wallet integrations | | | Midnight.js | 4.1.1 | DApp framework: contracts, types, providers | | | testkit-js | 4.1.1 | E2E testing framework | | | DApp Connector API | 4.0.1 | Interface between DApps and wallets | | Indexing and data | Midnight Indexer | 4.3.3-hotfix | Preprod indexer | | ZK and proving services | Proof server | 8.1.0 | Handles ZKP proof generation | | Functional area | Component | Version | Notes | | ----------------------- | ------------------------------------- | ------------ | ------------------------------------------------------- | | Network | Node (Midnight) | 1.0.2 | Mainnet network node | | Runtime and contracts | Compact devtools (`compact`) | 0.5.1 | Installs compilers, compiles contracts | | | Compact toolchain (`compact compile`) | 0.31.1 | Contract compiler for Midnight | | | Compact runtime | 0.16.0 | Runtime library for contracts | | | Compact JS | 2.5.1 | TypeScript execution environment for compiled contracts | | | Platform JS | 2.2.4 | Core abstractions and types | | | On-chain runtime | 3.0.0 | On-chain runtime support (v3) | | SDKs and APIs | Wallet SDK | 1.2.0 | SDK for building wallet integrations | | | Midnight.js | 4.1.1 | DApp framework: contracts, types, providers | | | testkit-js | 4.1.1 | E2E testing framework | | | DApp Connector API | 4.0.1 | Interface between DApps and wallets | | Indexing and data | Midnight Indexer | 4.3.3-hotfix | Mainnet indexer | | ZK and proving services | Proof server | 8.1.0 | Handles ZKP proof generation | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Wallet SDK Midnight Wallet SDK is the SDK of the digital wallet designed for the Midnight blockchain, enabling users to securely store private keys, manage assets, and interact with decentralized applications. [Link to related documentation](/sdks/official/wallet-developer-guide.md) To download the component, click the appropriate link under **Artifacts**. *** Version3.0.0 StatusAll ### [Release 3.0.0](/relnotes/wallet/wallet-3-0-0)LATEST 20 March 2026 #### Artifacts * [NPM Package](https://www.npmjs.com/package/@midnight-ntwrk/wallet-sdk-facade/v/3.0.0) #### Summary * Fee calculation split into `calculateFee` (transaction-only) and `estimateFee` (wallet-aware, includes balancing cost) * Updated to ledger v8 across the SDK * New `WalletFacade.fetchTermsAndConditions()` static method for retrieving network Terms and Conditions * New `QueryRunner.runPromise()` utility for executing GraphQL queries as plain Promises * `SecretKeysResource` in shielded and dust wallets now clears keys from memory after use * Shielded wallet now clears pending coins on transaction failure * Improved error messages for invalid transaction submission and balancing failures --- > For the complete documentation index, see [llms.txt](/llms.txt) # Tokens on Midnight Midnight has one native token, NIGHT, and one native resource, DUST. NIGHT is transferable, used for staking and governance, and generates DUST over time. DUST is a shielded, non-transferable resource that the network consumes to pay transaction fees. Both operate across a dual ledger that supports shielded (private) and unshielded (public) state. This section covers NIGHT, DUST, and the custom tokens you create in Compact. ## NIGHT and DUST[​](#night-and-dust "Direct link to NIGHT and DUST") * **NIGHT**: the native utility token. You hold NIGHT for staking, governance, and DUST generation. Unit: STAR (1 NIGHT = 10^6 STAR). * **DUST**: a shielded, non-transferable fee resource (not a token). Your NIGHT balance generates DUST over time up to a cap, and every transaction consumes it. Unit: SPECK (1 DUST = 10^15 SPECK). For the economic rationale behind this design, see [Dual-component tokenomics](/concepts/dual-component-tokenomics.md). For the technical architecture of DUST (generation, decay, registration), see [DUST architecture](/concepts/dust-architecture.md). ## Shielded and unshielded[​](#shielded-and-unshielded "Direct link to Shielded and unshielded") Midnight's dual ledger lets tokens exist in two forms: * **Shielded**: private state where wallet addresses and transaction details stay confidential. 1AM and urble default to shielded. * **Unshielded**: public state visible on the ledger, similar to transparent blockchains. Lace is opt-in for shielded. Both NIGHT and custom tokens can move between shielded and unshielded state. For code examples of shielded and unshielded token transfers in Compact, see [Token transfers](/examples/contracts/token-transfers.md). ## Custom tokens[​](#custom-tokens "Direct link to Custom tokens") You can create your own fungible and non-fungible tokens in Compact. The standard library provides `mintShieldedToken` (and its unshielded counterpart) to mint new tokens, and `sendShielded` / `receiveShielded` to transfer them. Token standards on Midnight will come through the MIP (Midnight Improvement Proposal) process. In the meantime, the [OpenZeppelin contracts for Compact](/sdks/community/openzeppelin-compact-contracts.md) library provides reusable access control and security primitives modeled on the Solidity originals. To build and move your own tokens end to end, follow the two-part tutorial: [Create and transfer an unshielded token](/tokens/unshielded-token.md) and [Create and transfer a shielded token](/tokens/shielded-token.md). ## Fees[​](#fees "Direct link to Fees") Every transaction on Midnight requires DUST. On a fresh wallet, DUST generation depends on how you register your NIGHT. Today, most NIGHT reaches Midnight through the cross-chain path (cNIGHT on Cardano), and the registration must finalize on Cardano and then reach a Midnight node, a process that takes about 12 hours. On a local network, DUST generates in about 5 minutes. This delay goes away once native mNIGHT launches. To get started: * [Fund a wallet](/guides/acquire-tokens.md) (faucet tNIGHT, Lace registration, and the wallet SDK path) ## Further reading[​](#further-reading "Direct link to Further reading") * [Dual-component tokenomics](/concepts/dual-component-tokenomics.md): the economic model behind NIGHT and DUST * [DUST architecture](/concepts/dust-architecture.md): generation, decay, registration, and protocol parameters * [Ledgers](/concepts/ledgers.md): the UTXO-based ledger and how it represents tokens * [Token transfers example](/examples/contracts/token-transfers.md): shielded and unshielded transfer code in Compact * [Compact standard library](/compact/standard-library.md): token management functions --- > For the complete documentation index, see [llms.txt](/llms.txt) # Create and transfer a shielded token In the [unshielded token tutorial](/tokens/unshielded-token.md) you built an **unshielded** token: balances live on-chain, the contract reads its own balance with a single call, and a transfer is a straight `sendUnshielded`. This tutorial builds the **shielded** version of the same token, and the privacy model changes the design in ways worth seeing directly. A shielded token has no public balance to read, its value lives in immutable *coins*, and the rule that governs everything is the difference between a *fresh* coin and a *committed* one. You build a small contract that mints a shielded coin and delivers it to the caller, privately, in a single transaction. This tutorial assumes you have completed the [unshielded token tutorial](/tokens/unshielded-token.md), or at least have its project set up. You reuse the same toolchain, the same local network, and most of the same support files. If you have not set those up, do its [project setup](/tokens/unshielded-token.md#set-up-your-project) first. ## What changes for a shielded token[​](#what-changes-for-a-shielded-token "Direct link to What changes for a shielded token") Three ideas carry the whole tutorial. None of them apply to the unshielded token, and all of them come straight from how shielded value works on Midnight. **There is no public balance.** The chain records commitments and nullifiers, not amounts. A contract cannot call anything like `unshieldedBalance(color)` for shielded value, because that number does not exist on-chain. To know what it holds, a contract has to track its own coins; to prove a transfer worked, you read the *wallet's* shielded balance, not the contract's. **Value lives in immutable coins.** A `ShieldedCoinInfo` describes a shielded coin: a nonce, a color, and a value. You cannot change a coin's value in place. To move part of it, you spend the coin and the standard library hands you back a new *change* coin for the remainder. A nonce keeps every coin unique, and you derive nonces deterministically with `evolveNonce` from a private seed. Fresh coins and committed coins are spent differently: | Coin state | Type | How you spend it | | -------------------------------------- | --------------------------------------------- | ----------------------- | | Fresh (just created, same transaction) | `ShieldedCoinInfo` | `sendImmediateShielded` | | Committed (already in the ledger) | `QualifiedShieldedCoinInfo` (adds `mt_index`) | `sendShielded` | A freshly minted coin has no Merkle tree position yet, so it cannot be spent with `sendShielded`. Once the ledger commits it on-chain, it gains an `mt_index` and becomes a `QualifiedShieldedCoinInfo`, which is what `sendShielded` requires. This tutorial mints and spends a coin in the *same* transaction, which keeps you on the fresh-coin path and avoids tracking Merkle positions across transactions. [Go further](#go-further-with-committed-transfers-and-burns) covers the committed path. One more constraint shapes what a contract-mediated shielded transfer can do today. The `sendShielded` primitive does not currently create coin ciphertexts, so sending shielded value to a user other than the current caller will not notify that user of the coin. In practice that means a contract can reliably deliver shielded value to the **caller** (the person signing the transaction). That is the transfer this tutorial demonstrates. ## Set up[​](#set-up "Direct link to Set up") You reuse the unshielded tutorial's environment. In particular: * The toolchain (compactc 0.31.1), the local network (midnight-local-dev), and the proof server. See the [project setup](/tokens/unshielded-token.md#set-up-your-project). * `src/config.ts` and `src/wallet.ts`, **identical to the unshielded tutorial**. Copy them over unchanged. The packages are the same as the unshielded tutorial, so if you completed it you already have everything installed. The shielded contract introduces something the unshielded one did not need: **witnesses**, off-chain functions that supply values to a circuit. You use them to hand the contract its nonce seed and its minter secret from private state. ## Build the shielded token contract[​](#build-the-shielded-token-contract "Direct link to Build the shielded token contract") As before, you build the contract one block at a time, in a single file: ``` touch contracts/shielded-token.compact ``` ### Set the language version, import the library, and declare the witnesses[​](#set-the-language-version-import-the-library-and-declare-the-witnesses "Direct link to Set the language version, import the library, and declare the witnesses") ``` pragma language_version 0.23; import CompactStandardLibrary; witness localNonceSeed(): Bytes<32>; witness minterSecretKey(): Bytes<32>; ``` The new line is the witnesses. A witness is a function that runs off-chain and feeds a value into the circuit. That value is often private data the circuit uses without publishing it, but it does not have to be. A witness is a hook for off-chain computation, and what it returns can be public or private. Privacy is not tied to witnesses either: a value passed as an ordinary circuit parameter also stays private unless the circuit explicitly discloses it. There are now two witnesses. `localNonceSeed()` supplies the nonce seed; `minterSecretKey()` supplies a second private 32-byte value, the secret that identifies who may mint. The contract never stores or publishes this secret; it stores only a public key *derived* from it (next), and at mint time checks the caller can reproduce that derivation. ### Declare the on-chain state[​](#declare-the-on-chain-state "Direct link to Declare the on-chain state") ``` export ledger token_color: Bytes<32>; export ledger initialized: Boolean; export ledger mints: Counter; export ledger minter: Bytes<32>; ``` `token_color` and `initialized` play the same role as in the unshielded tutorial. Note what is *not* here: there is no balance, and no map of who-holds-what. Recording shielded balances on-chain would publish the very amounts shielding is meant to hide, so the contract keeps none. `mints` is a counter, used only to show on-chain state changing. `minter` holds the public key of the wallet authorized to mint, derived from the secret above and set once at deployment. It's a hash, so storing it on-chain reveals nothing about the secret. ### Initialize at deployment[​](#initialize-at-deployment "Direct link to Initialize at deployment") ``` constructor() { // The deployer's derived key becomes the authorized minter. minter = disclose(deriveMinterKey(minterSecretKey())); initialized = false; } // Derive a public key from the secret with a domain-separated hash. A caller can // reproduce this value only if they hold the secret, so it is safe to gate on. export circuit deriveMinterKey(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "tutorial:shielded:minter:v1"), sk]); } ``` `deriveMinterKey` hashes a secret with a domain separator into a public key. The constructor runs once at deploy and records the *deployer's* derived key as the authorized minter, so only the wallet holding the deploy secret can mint later. (`ownPublicKey()` is deliberately not used for this. It returns a prover-claimed value with no binding to the signer, so anyone can bypass a check on it.) As in the unshielded tutorial, the constructor does not set `token_color` (that is set when you mint), and `initialized` starts false. ### Mint a shielded coin and send it to the caller[​](#mint-a-shielded-coin-and-send-it-to-the-caller "Direct link to Mint a shielded coin and send it to the caller") This is the core of the tutorial. It mints a fresh shielded coin to the contract and, in the same transaction, sends it to the caller: ``` export circuit mint_and_send(amount: Uint<64>, nonceIndex: Uint<128>): [] { // Only the authorized minter (holder of the deploy secret) may mint. assert(minter == deriveMinterKey(minterSecretKey()), "not authorized to mint"); assert(disclose(amount) > 0, "amount must be non-zero"); const domain = pad(32, "tutorial:shielded:token"); const nonce = disclose(evolveNonce(disclose(nonceIndex), localNonceSeed())); const coin = mintShieldedToken( domain, disclose(amount), nonce, right(kernel.self()) ); sendImmediateShielded( coin, left(ownPublicKey()), coin.value ); token_color = coin.color; initialized = true; mints.increment(1); } ``` In the code above: * The opening `assert` is the authorization gate. It recomputes the minter key from the caller's secret witness and requires it to equal the stored `minter`, so only the deployer can mint. The next `assert` rejects a zero amount. * `pad(32, "tutorial:shielded:token")` builds the domain separator, exactly as in the unshielded tutorial, but with a label of its own so the shielded token gets a distinct color. * `evolveNonce(nonceIndex, localNonceSeed())` derives a unique nonce. The seed is private (from the witness); `disclose(...)` wraps the *derived* nonce because the mint publishes it, while the seed stays secret. You pass a different `nonceIndex` each time you mint so the nonces never repeat. * `mintShieldedToken(...)` mints `amount` units and returns a `ShieldedCoinInfo`, a fresh coin. The recipient `right(kernel.self())` is the contract's own address, marked as the contract side of the recipient type, so the new coin belongs to the contract. * `sendImmediateShielded(coin, ..., coin.value)` spends that fresh coin in the same transaction, sending the whole value to `ownPublicKey()`, the caller. You wrap the recipient with `left(...)` because it is a user key, not a contract. Because you send the full value, there is no change coin to manage. Like `sendShielded`, `sendImmediateShielded` returns a `ShieldedSendResult`; this circuit ignores it, but a partial send (less than `coin.value`) would hand back a change coin you must handle, as shown in [Go further](#go-further-with-committed-transfers-and-burns). * The last three lines record the color, flip `initialized`, and bump the counter. The mint amount is a `Uint<64>` (the protocol caps a single mint at that width); coin values are `Uint<128>`, which is why `coin.value` is the wider type. As in the unshielded tutorial, minting requires authorization from the deployer; the difference is the mechanism. The unshielded contract takes the secret as an ordinary circuit parameter, while this one fetches it with a witness, so the caller never passes it as an argument at all. That completes the contract. Compile it the same way as before, into its own output directory: ``` compact compile contracts/shielded-token.compact src/shielded/managed/shielded-token ``` ## Wire the contract for deployment[​](#wire-the-contract-for-deployment "Direct link to Wire the contract for deployment") All of the shielded TypeScript goes in `src/shielded/`. Two of the support files differ from the unshielded tutorial. You reuse `config.ts` and `wallet.ts` from `src/` unchanged, which is why the imports below reach up a level with `../`. ### Implement the witnesses[​](#implement-the-witnesses "Direct link to Implement the witnesses") Create `src/shielded/witnesses.ts`: ``` mkdir src/shielded touch src/shielded/witnesses.ts ``` It defines the private state (the nonce seed and the minter secret) and the two witness implementations that hand the seed to the circuit: ``` import { randomBytes } from 'node:crypto'; export type ShieldedTokenPrivateState = { readonly nonceSeed: Uint8Array; readonly minterSecret: Uint8Array; }; export const createShieldedTokenPrivateState = ( nonceSeed: Uint8Array = randomBytes(32), minterSecret: Uint8Array = randomBytes(32), ): ShieldedTokenPrivateState => ({ nonceSeed, minterSecret }); // Each witness returns [updatedPrivateState, valueForTheCircuit]. The state // never changes here; the values handed back are the nonce seed and the // minter secret. export const witnesses = { localNonceSeed: ({ privateState, }: { privateState: ShieldedTokenPrivateState; }): [ShieldedTokenPrivateState, Uint8Array] => [privateState, privateState.nonceSeed], minterSecretKey: ({ privateState, }: { privateState: ShieldedTokenPrivateState; }): [ShieldedTokenPrivateState, Uint8Array] => [privateState, privateState.minterSecret], }; ``` `createShieldedTokenPrivateState` generates both secrets with `randomBytes(32)`, the same approach Midnight's official examples use. Never replace them with fixed, published values: the contract publishes the *hash* of the minter secret on-chain and gates minting on reproducing it, so anyone who could recompute a hardcoded secret could mint freely on your deployment, and a predictable nonce seed makes coin nonces predictable. Random per-run secrets work here because each run of the deploy script deploys a fresh contract, and the deploy and the mint share the same in-process private state. The flip side is that to mint again later on the *same* contract, you must persist the private state, because the constructor sets the minter key once. ### Wrap the compiled contract with the witnesses[​](#wrap-the-compiled-contract-with-the-witnesses "Direct link to Wrap the compiled contract with the witnesses") Create `src/shielded/contract.ts`: ``` touch src/shielded/contract.ts ``` It is the unshielded tutorial's wrapper with two changes: it points at the shielded output, and it supplies the witness instead of declaring the contract witness-free. Because the compiled output sits beside it under `src/shielded/managed/`, its internal paths look just like before: ``` import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import path from 'node:path'; import { witnesses } from './witnesses.js'; export { Contract, ledger, type Ledger } from './managed/shielded-token/contract/index.js'; import { Contract } from './managed/shielded-token/contract/index.js'; const currentDir = path.resolve(new URL(import.meta.url).pathname, '..'); export const zkConfigPath = path.resolve(currentDir, 'managed', 'shielded-token'); export const CompiledShieldedToken = CompiledContract.make( 'ShieldedToken', Contract, ).pipe( // The unshielded tutorial used withVacantWitnesses because it declares no // witness functions. This contract has two, so it supplies their // implementations instead, the same pattern Midnight's witness-backed // examples use. CompiledContract.withWitnesses(witnesses), CompiledContract.withCompiledFileAssets(zkConfigPath), ); ``` The only change from the unshielded wrapper is `withWitnesses(witnesses)` in place of `withVacantWitnesses`, plus the shielded output path. This is the pattern Midnight's own witness-backed examples use. ### Update the providers[​](#update-the-providers "Direct link to Update the providers") Create `src/shielded/providers.ts`: ``` touch src/shielded/providers.ts ``` It is identical to the unshielded tutorial except for the circuit name in the type, the private-state store name, and the `../` on the two shared imports: ``` import { type MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { type MidnightWalletProvider } from '../wallet.js'; import { type NetworkConfig } from '../config.js'; export type TokenCircuits = 'mint_and_send'; export type TokenProviders = MidnightProviders; export function buildProviders( wallet: MidnightWalletProvider, zkConfigPath: string, config: NetworkConfig, ): TokenProviders { const zkConfigProvider = new NodeZkConfigProvider(zkConfigPath); return { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: `shielded-token-${Date.now()}`, privateStoragePasswordProvider: () => 'Shielded-Token-Test-Password', accountId: wallet.getCoinPublicKey(), }), publicDataProvider: indexerPublicDataProvider( config.indexer, config.indexerWS, ), zkConfigProvider, proofProvider: httpClientProofProvider( config.proofServer, zkConfigProvider, ), walletProvider: wallet, midnightProvider: wallet, }; } ``` Unlike the unshielded tutorial, the private state is not empty. It carries the nonce seed and the minter secret. You pass the real values at deploy time in the next step. ## Deploy and test[​](#deploy-and-test "Direct link to Deploy and test") The deploy script follows the same shape as before (build the wallet, wait for funds and DUST, then deploy) and differs only in what it deploys and calls. The wallet, funding, and DUST steps match the unshielded tutorial, but this tutorial includes them in full so it runs on its own. Create `src/shielded/deploy.ts`: ``` touch src/shielded/deploy.ts ``` The imports change to bring in the shielded contract, the private-state factory, and `toHex`, and you reach the two shared modules with `../`: ``` import { WebSocket } from 'ws'; import { firstValueFrom } from 'rxjs'; import { filter, timeout as rxTimeout } from 'rxjs/operators'; import pino from 'pino'; import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import { deployContract, submitCallTx } from '@midnight-ntwrk/midnight-js-contracts'; import { type EnvironmentConfiguration } from '@midnight-ntwrk/testkit-js'; import { UnshieldedAddress } from '@midnight-ntwrk/wallet-sdk'; import { unshieldedToken } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { toHex } from '@midnight-ntwrk/midnight-js-utils'; import { getConfig } from '../config.js'; import { MidnightWalletProvider, syncWallet } from '../wallet.js'; import { buildProviders } from './providers.js'; import { CompiledShieldedToken, ledger, zkConfigPath, } from './contract.js'; import { createShieldedTokenPrivateState } from './witnesses.js'; (globalThis as any).WebSocket = WebSocket; const logger = pino({ level: 'info', transport: { target: 'pino-pretty' } }); ``` Next, build the wallet from the seed, print its address so you can fund it, wait for NIGHT to arrive, sync the unshielded channel, register that NIGHT for DUST, and poll until DUST is available. This is the same funding flow as the unshielded tutorial, included here in full: ``` const config = getConfig(); setNetworkId(config.networkId); const env: EnvironmentConfiguration = { walletNetworkId: config.networkId, networkId: config.networkId, indexer: config.indexer, indexerWS: config.indexerWS, node: config.node, nodeWS: config.nodeWS, faucet: config.faucet, proofServer: config.proofServer, }; const seed = process.env['MIDNIGHT_SEED']; if (!seed) { throw new Error('Set MIDNIGHT_SEED to your wallet seed (hex, no 0x prefix).'); } const wallet = await MidnightWalletProvider.build(logger, env, { kind: 'seed', value: seed, }); await wallet.start(); // Read the address from the wallet's first state update and print it, so you can fund it. const initialState = await firstValueFrom(wallet.wallet.state()); const address = UnshieldedAddress.codec .encode(config.networkId, initialState.unshielded.address) .asString(); logger.info(`Fund this address with tNIGHT, then this continues: ${address}`); const nightRaw = unshieldedToken().raw; // 1) Wait until NIGHT arrives. logger.info('Waiting for NIGHT to arrive...'); await firstValueFrom( wallet.wallet.state().pipe( filter((s: any) => (s.unshielded.balances[nightRaw] ?? 0n) > 0n), rxTimeout({ each: 30 * 60_000 }), ), ); logger.info('NIGHT received.'); // 2) Wait for the unshielded channel to finish syncing before registering, so // the wallet has an accurate view of its NIGHT UTXOs. logger.info('Waiting for the unshielded channel to sync...'); const syncedState = await firstValueFrom( wallet.wallet.state().pipe( filter((s: any) => s.unshielded.progress?.isStrictlyComplete() === true), rxTimeout({ each: 30 * 60_000 }), ), ); logger.info('Unshielded channel synced.'); // 3) Register NIGHT UTXOs for DUST generation. Fresh NIGHT is not registered // automatically, and without DUST the wallet cannot pay any transaction fee. const unregistered = syncedState.unshielded.availableCoins.filter( (coin: any) => coin.utxo.type === nightRaw && coin.meta.registeredForDustGeneration === false, ); if (unregistered.length > 0) { logger.info(`Registering ${unregistered.length} NIGHT UTXO(s) for DUST generation...`); const recipe = await wallet.wallet.registerNightUtxosForDustGeneration( unregistered, wallet.unshieldedKeystore.getPublicKey(), (payload: Uint8Array) => wallet.unshieldedKeystore.signData(payload), ); const finalized = await wallet.wallet.finalizeRecipe(recipe); const txId = await wallet.wallet.submitTransaction(finalized); logger.info(`DUST registration submitted: ${txId}`); } else { logger.info('NIGHT is already registered for DUST generation.'); } // 4) Wait until DUST is spendable. Poll the balance rather than holding a // subscription open, which keeps memory flat on a long wait. logger.info('Waiting for DUST to be generated from your NIGHT...'); const dustDeadline = Date.now() + 30 * 60_000; let dustBalance = 0n; while (Date.now() < dustDeadline) { const s = await firstValueFrom(wallet.wallet.state()); try { dustBalance = s.dust.balance(new Date()); } catch { dustBalance = 0n; } logger.info(` dust balance: ${dustBalance}`); if (dustBalance > 0n) break; await new Promise((r) => setTimeout(r, 15_000)); } if (dustBalance <= 0n) { throw new Error('Timed out waiting for DUST to be generated.'); } logger.info(`DUST available: ${dustBalance}`); ``` On the local network the genesis wallet is already funded and registered, so the NIGHT wait returns immediately, registration reports it is already done, and DUST appears within a few seconds. Now the shielded-specific part. Build the providers, deploy the contract with the private state, and read the initial state: ``` const providers = buildProviders(wallet, zkConfigPath, config); const deployed = await deployContract(providers, { compiledContract: CompiledShieldedToken, privateStateId: 'shielded-token', initialPrivateState: createShieldedTokenPrivateState(), }); const contractAddress = deployed.deployTxData.public.contractAddress; logger.info(`Deployed at ${contractAddress}`); async function readLedger() { const state = await providers.publicDataProvider.queryContractState(contractAddress); return ledger(state!.data); } logger.info(`initialized at deploy: ${(await readLedger()).initialized}`); // false ``` The one difference from the unshielded tutorial is the value of `initialPrivateState`: instead of an empty object you pass `createShieldedTokenPrivateState()`. This is the contract's initial *private state*, not the witnesses. `deployContract` runs the constructor against it and stores it in the private-state provider under `privateStateId`; on every later circuit call the framework loads the current private state and hands it to your witness implementations through `WitnessContext.privateState`, and each witness returns the updated private state alongside the value it feeds the circuit. The witnesses themselves are the off-chain functions you wrote earlier; the private state is the data they read. Mint and deliver the shielded token to your own wallet in a single call, then read the contract state back: ``` await submitCallTx(providers, { compiledContract: CompiledShieldedToken, contractAddress, privateStateId: 'shielded-token', circuitId: 'mint_and_send', args: [1000n, 0n], // amount, nonceIndex }); const afterMint = await readLedger(); logger.info(`initialized after mint: ${afterMint.initialized}`); // true logger.info(`token color: ${toHex(afterMint.token_color)}`); ``` `mint_and_send` mints 1,000 shielded units and sends them to the caller in the same transaction. `nonceIndex` is `0n` for this first call; a second call would use `1n`, and so on, to keep nonces unique. Finally, confirm the transfer by reading your **wallet's** shielded balance. There is no contract balance to read for a shielded token: ``` const after = await syncWallet(logger, wallet.wallet, 60 * 60_000); const color = toHex(afterMint.token_color); const shieldedBalance = after.shielded.balances[color] ?? 0n; logger.info(`wallet shielded balance of the token: ${shieldedBalance}`); // expect 1000 await wallet.stop(); ``` After syncing, the wallet should report 1,000 of the token's color in its shielded balance. This confirms the contract minted shielded value and delivered it to you privately. ### Run it[​](#run-it "Direct link to Run it") With the local network running in its own terminal, run the script against it with the genesis wallet seed, exactly as in the unshielded tutorial: ``` MIDNIGHT_NETWORK=local \ MIDNIGHT_SEED=0000000000000000000000000000000000000000000000000000000000000001 \ npx tsx src/shielded/deploy.ts ``` You should see the contract address, `initialized` flipping to true after the mint, and a wallet shielded balance of 1,000. To run against Preprod instead, use the same Preprod instructions as the [unshielded tutorial](/tokens/unshielded-token.md#run-against-preprod-instead). ## Go further with committed transfers and burns[​](#go-further-with-committed-transfers-and-burns "Direct link to Go further with committed transfers and burns") The flow above mints and spends a coin in one transaction, which keeps you on the fresh-coin path. Two common operations need the committed path or a special recipient. Their primitives are part of the same standard library; the signatures below are exact, but wiring them end-to-end on a live node involves managing Merkle positions across transactions, so treat them as the next thing to build rather than copy-paste-ready. 1. **Transferring a coin the contract already holds.** Once the ledger commits a minted coin on-chain, it becomes a `QualifiedShieldedCoinInfo` (it gains a Merkle tree index, `mt_index`), and you spend it with `sendShielded`: ``` circuit sendShielded( input: QualifiedShieldedCoinInfo, recipient: Either, value: Uint<128> ): ShieldedSendResult; ``` `sendShielded` returns a `ShieldedSendResult { change: Maybe; sent: ShieldedCoinInfo; }`. If you send less than the coin's value, `change` holds a new coin for the remainder. This is the consume-and-recreate pattern, and your application must persist that change coin, wait for it to commit, and spend it later as its own `QualifiedShieldedCoinInfo`. The hard part on a live network is obtaining the `mt_index` for the committed coin and supplying it to the circuit, typically from the indexer; that is the piece to work out and test carefully. Remember too that delivering shielded value to a user other than the caller will not notify them today. 2. **Burning shielded value.** Burning is a send to a special recipient that destroys the value, returned by `shieldedBurnAddress()`: ``` circuit shieldedBurnAddress(): Either; ``` To burn a committed coin, call `sendShielded(input, shieldedBurnAddress(), value)`. To burn a coin minted in the same transaction, use `sendImmediateShielded(coin, shieldedBurnAddress(), value)`. Either way, partial burns return change just like a transfer. ## What you built[​](#what-you-built "Direct link to What you built") You created a shielded token and moved it, end to end: * `mintShieldedToken` creates a fresh shielded coin owned by the contract. * `evolveNonce`, backed by a private witness seed, derives unique coin nonces. * `sendImmediateShielded` spends that fresh coin in the same transaction and delivers it to the caller. * Because shielded balances are not public, you confirmed the result by reading the wallet's shielded balance rather than the contract's. The thread connecting the two tutorials is that privacy is not a setting. It changes what the contract stores and how value moves. The [unshielded token](/tokens/unshielded-token.md) leaned on the chain to track balances; the shielded token holds value in coins and never publishes amounts at all. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Create and transfer an unshielded token On Midnight, the privacy model you choose for a token changes how you write its smart contract. This tutorial shows you how to create and transfer an **unshielded** (transparent) token in Compact: one whose balances live on-chain, where anyone can read them. This is the first of a two-part pair. Once you have built the transparent token here, the companion tutorial, [Create and transfer a shielded token](/tokens/shielded-token.md), builds the privacy-preserving version, where balances stay hidden and the design changes to match. Reading them in order is the fastest way to understand how privacy refines a token on Midnight. This tutorial is for developers who know the basics of Compact and have deployed a smart contract before. If you are new to Compact, read the [Compact language reference](/compact/reference/compact-reference.md) first or check out [Midnight Academy](https://academy.midnight.network). ## How tokens work on Midnight[​](#how-tokens-work-on-midnight "Direct link to How tokens work on Midnight") Midnight has one native token, NIGHT, issued by the protocol itself. On the test networks you get it as tNIGHT from a faucet, or pre-funded in the genesis wallet on a local network; on mainnet it reaches Midnight from Cardano over the one-way cNIGHT-to-mNIGHT bridge. See the [tokens overview](/tokens/overview.md) for the full picture. A smart contract creates every *other* token on Midnight, which is exactly what you do here. It helps to place your token in the wider map. Tokens fall into four types, along two axes: where the token comes from, and whether it is transparent or privacy-preserving. | | Unshielded (transparent) | Shielded (privacy-preserving) | | ------------ | --------------------------------------------- | ------------------------------------------- | | **Native** | Protocol-issued, for example NIGHT | Protocol-issued, amounts hidden | | **Contract** | Minted by a smart contract; balances on-chain | Minted by a smart contract; balances hidden | This pair of tutorials covers the two **contract** rows: this one the unshielded column, the [shielded tutorial](/tokens/shielded-token.md) the shielded column. Native tokens are protocol-issued, like the NIGHT you use for funding below. A third group, hybrid tokens, places a native coin under the control of a smart contract; that work depends on protocol changes still in design, so it is out of scope here. Token standards The token standards for Midnight are still taking shape. The smart contracts in this tutorial use the protocol primitives directly, which work today, rather than any draft standard. For the current direction, see the [token standards discussion](https://github.com/midnightntwrk/midnight-improvement-proposals/discussions/142). Those primitives share a starting point. Before you can mint, transfer, or check a balance, you need a way to identify the token you are working with. That identifier is its color. ## Token color[​](#token-color "Direct link to Token color") Every token has a *color*, a `Bytes<32>` value that identifies the token type. A contract token's color comes from the smart contract and a *domain separator*, a fixed label you choose. The minting primitive returns the color, and you use that color in every later operation on the token. Because the color depends on the smart contract, two smart contracts that use the same label still produce different tokens. Color settles which token you are working with, not who holds how much of it. How a contract keeps track of that (or whether it needs to at all) comes down to the privacy model. ## How privacy changes what you store[​](#how-privacy-changes-what-you-store "Direct link to How privacy changes what you store") This is the core idea of the tutorial. The privacy model is not a flag you toggle at the end; it changes what a smart contract has to store. On the **unshielded** side, the chain records the balance of each token color held by each address. A smart contract reads its own balance with `unshieldedBalance(color)`. Balances and supply are public, so the transparent equivalents of `balanceOf` and `totalSupply` make sense. On the **shielded** side, the chain hides balances. It records commitments and nullifiers, not amounts. There is no public balance to read. A smart contract that needs to know who holds what has to track that itself, and it has to guard the value as a shielded *coin*. That is why the shielded smart contract later mints a coin and delivers it to the caller in a single transaction, tracking no balances at all, while the unshielded one leans on the chain's public balances. | | Unshielded token | Shielded token | | ------------------------ | -------------------------- | ----------------------------------------- | | Balance storage | On-chain, per address | Hidden; tracked by the smart contract | | Read a balance | `unshieldedBalance(color)` | No public read; smart contract state only | | Value the contract holds | A balance | An immutable coin | A shielded coin is immutable. You cannot change its value in place. To change the amount it holds, a smart contract consumes the current coin and creates a new one at the new value. A nonce keeps each coin unique. The shielded tutorial's [Go further](/tokens/shielded-token.md#go-further-with-committed-transfers-and-burns) section shows this consume-and-recreate pattern. Whether a token sits as a balance or a coin, at some point it moves from one holder to another. That movement takes one of two forms. ## Two ways to transfer[​](#two-ways-to-transfer "Direct link to Two ways to transfer") Tokens move in one of two ways, and the difference matters most for shielded tokens. 1. **Wallet to wallet:** Once a holder has tokens in their wallet, the wallet transfers them directly. The smart contract is not involved. 2. **Contract-mediated:** A smart contract moves tokens it holds, with `sendUnshielded` for a transparent token or by sending a shielded coin for a shielded token. For shielded tokens this has a consequence worth stating plainly: a smart contract can enforce rules on shielded value only while it custodies the coin. Once a user holds the coin in their wallet, they spend it with their own key, outside the smart contract. This is why a smart contract that needs to govern a shielded token holds the coin itself, in a vault. ## Set up your project[​](#set-up-your-project "Direct link to Set up your project") This section installs the toolchain, starts a local Midnight network, and lays out the project you build on across both parts of this tutorial. If your environment is already configured, skip ahead to [Build an unshielded token](#build-an-unshielded-token). ### Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, make sure you have: * The **Compact toolchain** installed. Follow [Install the toolchain](/getting-started/installation.md). This tutorial targets compiler version 0.31.1. If you have an older toolchain, run `compact update`: version 0.31.0 could drop a range-check constraint from generated ZK circuits for certain casts, which 0.31.1 fixes. * Docker and Docker Compose v2 (for the local network and the proof server). * Node.js 22 or later. ### Start the local network[​](#start-the-local-network "Direct link to Start the local network") This tutorial runs against a local Midnight network. It gives you a genesis wallet that is already funded with NIGHT and registered for fees, so you can deploy in seconds without a faucet. The [midnight-local-dev](https://github.com/midnightntwrk/midnight-local-dev.git) tool starts the node, the indexer, and the proof server in Docker, and initializes that wallet for you. Clone it and start it in its **own terminal**: ``` git clone https://github.com/midnightntwrk/midnight-local-dev.git cd midnight-local-dev npm install npm start ``` When prompted, choose to pull the images and start the network. The tool brings up three containers and funds the genesis master wallet (seed `0x00...001`) with NIGHT and registered DUST. Leave this terminal running for the rest of the tutorial. The network exposes: * Node: `http://localhost:9944` * Indexer: `http://localhost:8088` * Proof server: `http://localhost:6300` Because midnight-local-dev already runs a proof server, you do not start one separately. Prefer Preprod? You can run the exact same code against the public **Preprod** network instead of local. In that case you do not run midnight-local-dev. Start a standalone proof server in its own terminal: ``` docker run -p 6300:6300 midnightntwrk/proof-server:8.1.0 midnight-proof-server -v ``` and fund your own wallet at the Preprod faucet (covered in [Run it](#run-it)). The flow is identical; it just takes a couple of minutes more than local. ### Create the project[​](#create-the-project "Direct link to Create the project") Create a project and install the Midnight dependencies. The versions below form a known-good set. Install them exactly as written rather than letting npm resolve the latest. ``` mkdir midnight-tokens && cd midnight-tokens npm init -y npm pkg set type=module ``` Install the contract runtime, the contract framework, and the providers: ``` npm install \ @midnight-ntwrk/midnight-js-contracts@4.1.1 \ @midnight-ntwrk/midnight-js-indexer-public-data-provider@4.1.1 \ @midnight-ntwrk/midnight-js-http-client-proof-provider@4.1.1 \ @midnight-ntwrk/midnight-js-node-zk-config-provider@4.1.1 \ @midnight-ntwrk/midnight-js-types@4.1.1 \ @midnight-ntwrk/midnight-js-utils@4.1.1 ``` The steps below use the **local** network by default. To run against **Preprod** instead, set `MIDNIGHT_NETWORK=preprod` when you run the script. Nothing else changes. ## Build an unshielded token[​](#build-an-unshielded-token "Direct link to Build an unshielded token") You build the contract one block at a time, in a single file. Create the directory and the empty file first: ``` mkdir -p contracts touch contracts/unshielded-token.compact ``` Open `contracts/unshielded-token.compact` in your editor and add each block below in order. With the last one, the file holds the whole contract. ### Set the language version and import the library[​](#set-the-language-version-and-import-the-library "Direct link to Set the language version and import the library") Start the file with the language version and the standard library: ``` pragma language_version 0.23; import CompactStandardLibrary; ``` `import CompactStandardLibrary` brings in the token primitives you use below, like `mintUnshieldedToken`, `sendUnshielded`, and `unshieldedBalanceGte`. ### Declare the on-chain state[​](#declare-the-on-chain-state "Direct link to Declare the on-chain state") Add the contract's public state: ``` export ledger token_color: Bytes<32>; export ledger initialized: Boolean; export ledger owner: Bytes<32>; ``` A ledger field lives on-chain. `token_color` holds the token's identity, which you set the first time you mint; `initialized` records whether that has happened yet, so the other circuits can check it before acting; `owner` holds a key hash derived from the deployer's secret, which the mint and transfer circuits gate on. On-chain ledger state is public and readable by anyone either way. What `export` adds is the generated JavaScript binding in the compiled artifacts, so your deploy script can read these fields back by name. ### Initialize at deployment[​](#initialize-at-deployment "Direct link to Initialize at deployment") Add a constructor to set the starting state: ``` constructor(ownerSecret: Bytes<32>) { // The deployer's derived key becomes the owner authorized to mint and transfer. owner = disclose(deriveOwnerKey(ownerSecret)); initialized = false; } // Derive a public key from the secret with a domain-separated hash. A caller can // reproduce this value only if they hold the secret, so it is safe to gate on. export circuit deriveOwnerKey(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "tutorial:unshielded:owner:v1"), sk]); } ``` A constructor can take arguments, and this one takes the owner's secret; the deploy script supplies it at deploy time. Constructor arguments and circuit parameters are *witness data* on Midnight: they stay off-chain, which is why writing anything derived from one into public ledger state requires `disclose()`. Here the constructor stores only the disclosed *hash* of the secret, so the secret itself never appears on-chain, and `initialized` starts false. (`ownPublicKey()` is deliberately not used for authorization: it returns a prover-claimed value with no binding to the signer, so anyone can bypass a check on it.) ### Create the token[​](#create-the-token "Direct link to Create the token") Add the mint circuit. This is where the token comes into existence: ``` export circuit mint(sk: Bytes<32>, amount: Uint<64>): [] { // Only the owner (holder of the deploy secret) may mint. assert(owner == deriveOwnerKey(sk), "not authorized to mint"); const domain = pad(32, "tutorial:unshielded:token"); const color = mintUnshieldedToken( domain, disclose(amount), left(kernel.self()) ); token_color = color; initialized = true; } ``` In the code snippet above: * The opening `assert` is the authorization gate: it recomputes the owner key from `sk` and requires it to match the stored `owner`, so only the deployer can mint. Because `sk` is an ordinary circuit parameter, it stays private; the comparison happens inside the proof, and this assert needs no `disclose()`. * `pad(32, "tutorial:unshielded:token")` builds the *domain separator* with a fixed `Bytes<32>` label that, with the contract's address, determines the token color. * `mintUnshieldedToken(...)` mints `amount` units and returns the token's color. The recipient is `kernel.self()`, the contract's own address, wrapped in `left(...)` to mark it as the contract side of the address type. So the new supply lands with the contract. * The last two lines record the color and set `initialized` to true. Two things are worth noting. The mint amount is a `Uint<64>` (the protocol caps a single mint at that width), while transfers use the wider `Uint<128>`. And `disclose(...)` marks a value as safe to reveal on-chain, and minting is a public action, so you disclose the amount. Minting to `kernel.self()` credits the contract directly, so the new supply is held by the contract until you transfer it out. Without the `sk` gate this mint would be permissionless: anyone could call it and inflate the supply. A real token needs the authorization check, so this tutorial treats it as part of the token rather than an extension. The [shielded tutorial](/tokens/shielded-token.md) implements the same gate with a different mechanism, supplying its secret through a witness function backed by private state, so the pair shows both ways to authorize a circuit. ### Transfer the token[​](#transfer-the-token "Direct link to Transfer the token") Add the transfer circuit to move tokens from the contract to a wallet: ``` export circuit transfer(sk: Bytes<32>, recipient: UserAddress, amount: Uint<128>): [] { // Only the owner may move tokens out of the contract. assert(owner == deriveOwnerKey(sk), "not authorized to transfer"); assert(initialized, "token not minted yet"); assert(unshieldedBalanceGte(token_color, disclose(amount)), "insufficient balance"); sendUnshielded( token_color, disclose(amount), right(disclose(recipient)) ); } ``` The three `assert` lines are guards. They run as part of the circuit, and if any condition is false the assertion fails and rejects the whole call, committing nothing on-chain. The first is the authorization gate, the same check as in `mint`: without it, anyone could call `transfer` and drain the contract's entire supply to any address they chose. The second fails the call if you haven't minted the token yet; the third fails if the contract doesn't hold enough, checked with `unshieldedBalanceGte`. `sendUnshielded(...)` then moves the amount to the recipient. This time you wrap the recipient in `right(...)`, the `UserAddress` side of the address type, because the tokens go to a wallet rather than back to the contract. ### Read the balance[​](#read-the-balance "Direct link to Read the balance") You don't need a circuit to read an unshielded balance. Because the token is transparent, its balances are public on-chain, and Midnight.js reads them straight from wallet state: `getUnshieldedBalances` returns the map of token color to amount (it's `unshielded.balances` under the hood). The deploy script uses exactly this in the next section to confirm the transfer, reading `after.unshielded.balances[color]` rather than calling the contract. This is precisely where a shielded token differs: there's no public balance to read, which is why the [shielded tutorial](/tokens/shielded-token.md)'s contract has to track value itself. That contrast is the point of the two parts. That completes the contract. Your `contracts/unshielded-token.compact` now holds the complete contract, in the order above. ### Compile the contract[​](#compile-the-contract "Direct link to Compile the contract") Compile the file, sending the output to `src/managed`: ``` compact compile contracts/unshielded-token.compact src/managed/unshielded-token ``` The compiler generates the contract's TypeScript interface, its prover and verifier keys, and the ZK artifacts the proof server uses, all under `src/managed/unshielded-token`. The deploy script in the next section imports the generated contract from `src/managed/unshielded-token/contract/index.js`, wraps it for deployment, and uses `ledger` to decode the contract's public state for this token: `token_color`, `initialized`, and `owner`. With the contract compiled, you are ready to deploy it and mint your first tokens. ## Deploy and test your token[​](#deploy-and-test-your-token "Direct link to Deploy and test your token") Now you run the contract on a live network. You add the wallet packages, create four small support files that connect your code to the network, then write a deploy script that creates the token, reads it back, and transfers it to a wallet. The steps below use the **local** network by default. To run against **Preprod** instead, set `MIDNIGHT_NETWORK=preprod` when you run the script. Nothing else changes. info Keep the local network (or, for Preprod, your standalone proof server) running while you do this. The deployment and every circuit call generate zero-knowledge proofs through the proof server. ### Install the wallet packages[​](#install-the-wallet-packages "Direct link to Install the wallet packages") Add the wallet SDK, the supporting libraries the harness imports, and tsx to run the script. As with the earlier install, pin these versions exactly: ``` npm install \ @midnight-ntwrk/wallet-sdk@1.2.0 \ @midnight-ntwrk/testkit-js@4.1.1 \ @midnight-ntwrk/midnight-js-protocol@4.1.1 \ @midnight-ntwrk/midnight-js-network-id@4.1.1 \ @midnight-ntwrk/midnight-js-level-private-state-provider@4.1.1 \ rxjs@7.8.2 pino@10.3.1 pino-pretty@13.1.3 ws@8.21.0 npm install --save-dev tsx@4.22.4 ``` The `wallet-sdk` version matters here. Pin it exactly to 1.2.0, the version listed in the [compatibility matrix](/relnotes/support-matrix.md). npm's `latest` dist-tag still points at 1.1.0, so installing without an exact version would silently resolve to an older release. For reference, your `package.json` dependencies should now read: ``` { "dependencies": { "@midnight-ntwrk/midnight-js-contracts": "4.1.1", "@midnight-ntwrk/midnight-js-http-client-proof-provider": "4.1.1", "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "4.1.1", "@midnight-ntwrk/midnight-js-level-private-state-provider": "4.1.1", "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-node-zk-config-provider": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-types": "4.1.1", "@midnight-ntwrk/midnight-js-utils": "4.1.1", "@midnight-ntwrk/testkit-js": "4.1.1", "@midnight-ntwrk/wallet-sdk": "1.2.0", "pino": "10.3.1", "pino-pretty": "13.1.3", "rxjs": "7.8.2", "ws": "8.21.0" }, "devDependencies": { "tsx": "4.22.4" } } ``` ### Configure the networks[​](#configure-the-networks "Direct link to Configure the networks") Create `src/config.ts`: ``` touch src/config.ts ``` It holds the endpoints for each network and reads `MIDNIGHT_NETWORK` to pick one: ``` export type NetworkConfig = { networkId: string; indexer: string; indexerWS: string; node: string; nodeWS: string; proofServer: string; faucet: string; }; export const LOCAL_CONFIG: NetworkConfig = { networkId: 'undeployed', indexer: 'http://127.0.0.1:8088/api/v4/graphql', indexerWS: 'ws://127.0.0.1:8088/api/v4/graphql/ws', node: 'http://127.0.0.1:9944', nodeWS: 'ws://127.0.0.1:9944', proofServer: 'http://127.0.0.1:6300', faucet: '', }; export const PREVIEW_CONFIG: NetworkConfig = { networkId: 'preview', indexer: 'https://indexer.preview.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preview.midnight.network', nodeWS: 'wss://rpc.preview.midnight.network', proofServer: process.env['MIDNIGHT_PROOF_SERVER'] ?? 'http://127.0.0.1:6300', // Fund wallets by hand at https://midnight-tmnight-preview.nethermind.dev/ — // this field is for a machine API endpoint, so leave it empty. faucet: '', }; export const PREPROD_CONFIG: NetworkConfig = { networkId: 'preprod', indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preprod.midnight.network', nodeWS: 'wss://rpc.preprod.midnight.network', proofServer: process.env['MIDNIGHT_PROOF_SERVER'] ?? 'http://127.0.0.1:6300', // Fund wallets by hand at https://midnight-tmnight-preprod.nethermind.dev/ — // this field is for a machine API endpoint, so leave it empty. faucet: '', }; export function getConfig(): NetworkConfig { const network = process.env['MIDNIGHT_NETWORK'] ?? 'local'; if (network === 'local') return LOCAL_CONFIG; if (network === 'preview') return PREVIEW_CONFIG; if (network === 'preprod') return PREPROD_CONFIG; throw new Error( `Unknown network: ${network}. Supported: 'local', 'preview', 'preprod'.`, ); } ``` ### Add the wallet[​](#add-the-wallet "Direct link to Add the wallet") Create `src/wallet.ts`: ``` touch src/wallet.ts ``` This is the most boilerplate of the support files: it builds a wallet on the wallet-sdk facade and adapts it to the `WalletProvider` and `MidnightProvider` interfaces the contract framework expects. Copy it as-is; you reuse it unchanged in the shielded tutorial. ``` import { type CoinPublicKey, DustSecretKey, type EncPublicKey, type FinalizedTransaction, LedgerParameters, ZswapSecretKeys, } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { type MidnightProvider, type UnboundTransaction, type WalletProvider, } from '@midnight-ntwrk/midnight-js-types'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import { type WalletFacade, type FacadeState, type UnshieldedKeystore, } from '@midnight-ntwrk/wallet-sdk'; import { type DustWalletOptions, type EnvironmentConfiguration, FluentWalletBuilder, } from '@midnight-ntwrk/testkit-js'; import * as Rx from 'rxjs'; import type { Logger } from 'pino'; export type WalletSecret = | { kind: 'seed'; value: string } | { kind: 'mnemonic'; value: string }; export class MidnightWalletProvider implements MidnightProvider, WalletProvider { readonly wallet: WalletFacade; readonly unshieldedKeystore: UnshieldedKeystore; private constructor( private readonly logger: Logger, wallet: WalletFacade, private readonly zswapSecretKeys: ZswapSecretKeys, private readonly dustSecretKey: DustSecretKey, unshieldedKeystore: UnshieldedKeystore, ) { this.wallet = wallet; this.unshieldedKeystore = unshieldedKeystore; } getCoinPublicKey(): CoinPublicKey { return this.zswapSecretKeys.coinPublicKey; } getEncryptionPublicKey(): EncPublicKey { return this.zswapSecretKeys.encryptionPublicKey; } async balanceTx( tx: UnboundTransaction, ttl: Date = ttlOneHour(), ): Promise { const recipe = await this.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: this.zswapSecretKeys, dustSecretKey: this.dustSecretKey, }, { ttl }, ); return await this.wallet.finalizeRecipe(recipe); } submitTx(tx: FinalizedTransaction): Promise { return this.wallet.submitTransaction(tx); } async start(): Promise { this.logger.info('Starting wallet...'); await this.wallet.start(this.zswapSecretKeys, this.dustSecretKey); } async stop(): Promise { return this.wallet.stop(); } static async build( logger: Logger, env: EnvironmentConfiguration, secret: WalletSecret, ): Promise { const dustOptions: DustWalletOptions = { ledgerParams: LedgerParameters.initialParameters(), additionalFeeOverhead: 1_000n, feeBlocksMargin: 5, }; const base = FluentWalletBuilder.forEnvironment(env) .withDustOptions(dustOptions); const builder = secret.kind === 'mnemonic' ? base.withMnemonic(secret.value) : base.withSeed(secret.value); const buildResult = await builder.buildWithoutStarting(); const { wallet, seeds, keystore } = buildResult as { wallet: WalletFacade; seeds: { masterSeed: string; shielded: Uint8Array; dust: Uint8Array; }; keystore: UnshieldedKeystore; }; logger.info( `Wallet built from ${secret.kind}; master seed: ${seeds.masterSeed.slice(0, 8)}...`, ); return new MidnightWalletProvider( logger, wallet, ZswapSecretKeys.fromSeed(seeds.shielded), DustSecretKey.fromSeed(seeds.dust), keystore, ); } } function isProgressStrictlyComplete(progress: unknown): boolean { if (!progress || typeof progress !== 'object') { return false; } const candidate = progress as { isStrictlyComplete?: unknown }; if (typeof candidate.isStrictlyComplete !== 'function') { return false; } return (candidate.isStrictlyComplete as () => boolean)(); } export async function syncWallet( logger: Logger, wallet: WalletFacade, timeout = 300_000, ): Promise { logger.info('Syncing wallet...'); let emissionCount = 0; return Rx.firstValueFrom( wallet.state().pipe( Rx.tap((state: FacadeState) => { emissionCount++; // Heartbeat every 200 updates so a long sync shows progress without flooding the console. if (emissionCount % 200 === 0) { const shielded = isProgressStrictlyComplete(state.shielded.state.progress); const unshielded = isProgressStrictlyComplete(state.unshielded.progress); const dust = isProgressStrictlyComplete(state.dust.state.progress); logger.info(`Still syncing: shielded=${shielded}, unshielded=${unshielded}, dust=${dust}`); } }), // Wait for the shielded and unshielded channels to catch up. We do not gate // on the dust channel here: on the public networks it may never report // "strictly complete", which would hang this wait forever. Rx.filter( (state: FacadeState) => isProgressStrictlyComplete(state.shielded.state.progress) && isProgressStrictlyComplete(state.unshielded.progress), ), Rx.tap(() => logger.info('Wallet synced.')), Rx.timeout({ each: timeout, with: () => Rx.throwError(() => new Error(`Wallet sync timed out after ${timeout}ms`)), }), ), ); } ``` The two functions you call from the deploy script are `MidnightWalletProvider.build(...)`, which creates the wallet from a seed, and `syncWallet(...)`, which waits until the wallet has caught up with the chain and returns its current state. ### Add the providers[​](#add-the-providers "Direct link to Add the providers") Create `src/providers.ts`: ``` touch src/providers.ts ``` This assembles the provider set the framework uses: public state from the indexer, proofs from the proof server, ZK config from the compiled output, and the wallet you just built: ``` import { type MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { type MidnightWalletProvider } from './wallet.js'; import { type NetworkConfig } from './config.js'; export type TokenCircuits = 'mint' | 'transfer'; export type TokenProviders = MidnightProviders; export function buildProviders( wallet: MidnightWalletProvider, zkConfigPath: string, config: NetworkConfig, ): TokenProviders { const zkConfigProvider = new NodeZkConfigProvider(zkConfigPath); return { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: `unshielded-token-${Date.now()}`, privateStoragePasswordProvider: () => 'Unshielded-Token-Test-Password', accountId: wallet.getCoinPublicKey(), }), publicDataProvider: indexerPublicDataProvider( config.indexer, config.indexerWS, ), zkConfigProvider, proofProvider: httpClientProofProvider( config.proofServer, zkConfigProvider, ), walletProvider: wallet, midnightProvider: wallet, }; } ``` This token keeps no private state, but the framework still expects a private-state provider, so you include one. It stays empty. ### Wrap the compiled contract[​](#wrap-the-compiled-contract "Direct link to Wrap the compiled contract") Create `src/contract.ts`: ``` touch src/contract.ts ``` It imports the generated contract and turns it into a deployable unit: ``` import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import path from 'node:path'; export { Contract, ledger, type Ledger } from './managed/unshielded-token/contract/index.js'; import { Contract } from './managed/unshielded-token/contract/index.js'; const currentDir = path.resolve(new URL(import.meta.url).pathname, '..'); export const zkConfigPath = path.resolve(currentDir, 'managed', 'unshielded-token'); export const CompiledUnshieldedToken = CompiledContract.make( 'UnshieldedToken', Contract, ).pipe( CompiledContract.withVacantWitnesses, CompiledContract.withCompiledFileAssets(zkConfigPath), ); ``` `withVacantWitnesses` applies because the contract declares no witness functions, so there are no off-chain implementations to supply; it attaches an empty witnesses object. Witnesses are hooks for off-chain code, which is a separate concept from state visibility: ledger state is public whether or not a contract has witnesses. `zkConfigPath` points the proof server at the keys the compiler generated under `src/managed/unshielded-token`. ### Write the deploy script[​](#write-the-deploy-script "Direct link to Write the deploy script") Now the part specific to your token. Create `src/deploy.ts` and build it up block by block: ``` touch src/deploy.ts ``` Start with the imports, the WebSocket global the indexer needs, and a logger: ``` import { randomBytes } from 'node:crypto'; import { WebSocket } from 'ws'; import { firstValueFrom } from 'rxjs'; import { filter, timeout as rxTimeout } from 'rxjs/operators'; import pino from 'pino'; import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import { deployContract, submitCallTx } from '@midnight-ntwrk/midnight-js-contracts'; import { type EnvironmentConfiguration } from '@midnight-ntwrk/testkit-js'; import { UnshieldedAddress } from '@midnight-ntwrk/wallet-sdk'; import { unshieldedToken } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils'; import { getConfig } from './config.js'; import { MidnightWalletProvider, syncWallet } from './wallet.js'; import { buildProviders } from './providers.js'; import { CompiledUnshieldedToken, ledger, zkConfigPath } from './contract.js'; // The indexer's GraphQL subscriptions need a WebSocket global under Node. (globalThis as any).WebSocket = WebSocket; const logger = pino({ level: 'info', transport: { target: 'pino-pretty' } }); ``` Build the wallet from your seed, start it, and print its address so you can fund it: ``` const config = getConfig(); setNetworkId(config.networkId); const env: EnvironmentConfiguration = { walletNetworkId: config.networkId, networkId: config.networkId, indexer: config.indexer, indexerWS: config.indexerWS, node: config.node, nodeWS: config.nodeWS, faucet: config.faucet, proofServer: config.proofServer, }; const seed = process.env['MIDNIGHT_SEED']; if (!seed) { throw new Error('Set MIDNIGHT_SEED to your wallet seed (hex, no 0x prefix).'); } const wallet = await MidnightWalletProvider.build(logger, env, { kind: 'seed', value: seed }); await wallet.start(); // Read the address from the wallet's first state update and print it, so you can fund it. const initialState = await firstValueFrom(wallet.wallet.state()); const address = UnshieldedAddress.codec .encode(config.networkId, initialState.unshielded.address) .asString(); logger.info(`Fund this address with tNIGHT, then this continues: ${address}`); ``` You pass your wallet seed in `MIDNIGHT_SEED`. The script builds the wallet, prints its unshielded address, and then waits for that address to hold NIGHT. On local, the genesis wallet is already funded, so the wait returns immediately. On Preprod, you fund the printed address at the faucet while the script waits. Wait for the NIGHT to arrive, sync the unshielded channel, then register that NIGHT to generate the tDUST that pays fees: ``` const nightRaw = unshieldedToken().raw; // 1) Wait until NIGHT arrives. logger.info('Waiting for NIGHT to arrive...'); await firstValueFrom( wallet.wallet.state().pipe( filter((s: any) => (s.unshielded.balances[nightRaw] ?? 0n) > 0n), rxTimeout({ each: 30 * 60_000 }), ), ); logger.info('NIGHT received.'); // 2) Wait for the unshielded channel to finish syncing before registering, so // the wallet has an accurate view of its NIGHT UTXOs. logger.info('Waiting for the unshielded channel to sync...'); const syncedState = await firstValueFrom( wallet.wallet.state().pipe( filter((s: any) => s.unshielded.progress?.isStrictlyComplete() === true), rxTimeout({ each: 30 * 60_000 }), ), ); logger.info('Unshielded channel synced.'); // 3) Register NIGHT UTXOs for DUST generation. Fresh NIGHT is not registered // automatically, and without DUST the wallet cannot pay any transaction fee. const unregistered = syncedState.unshielded.availableCoins.filter( (coin: any) => coin.utxo.type === nightRaw && coin.meta.registeredForDustGeneration === false, ); if (unregistered.length > 0) { logger.info(`Registering ${unregistered.length} NIGHT UTXO(s) for DUST generation...`); const recipe = await wallet.wallet.registerNightUtxosForDustGeneration( unregistered, wallet.unshieldedKeystore.getPublicKey(), (payload: Uint8Array) => wallet.unshieldedKeystore.signData(payload), ); const finalized = await wallet.wallet.finalizeRecipe(recipe); const txId = await wallet.wallet.submitTransaction(finalized); logger.info(`DUST registration submitted: ${txId}`); } else { logger.info('NIGHT is already registered for DUST generation.'); } ``` Fees on Midnight are paid in DUST, and registering NIGHT generates DUST. Freshly funded NIGHT is not registered, so the script registers it after the unshielded channel has synced. On local, the genesis wallet is already registered, so this step reports that and skips. The filter checks the token type as well as the registration flag. You can register only NIGHT for DUST generation, and the wallet SDK rejects the whole call if any other token type slips in. The type check matters on a re-run: once your wallet holds the token you mint below, those UTXOs also report `registeredForDustGeneration === false`, and without the `nightRaw` check the script would pass them to the registration call and crash it. Poll until DUST appears, so the wallet can pay for the transactions that follow: ``` // 4) Wait until DUST is spendable. Poll the balance rather than holding a // subscription open, which keeps memory flat on a long wait. logger.info('Waiting for DUST to be generated from your NIGHT...'); const dustDeadline = Date.now() + 30 * 60_000; let dustBalance = 0n; while (Date.now() < dustDeadline) { const s = await firstValueFrom(wallet.wallet.state()); try { dustBalance = s.dust.balance(new Date()); } catch { dustBalance = 0n; } logger.info(` dust balance: ${dustBalance}`); if (dustBalance > 0n) break; await new Promise((r) => setTimeout(r, 15_000)); } if (dustBalance <= 0n) { throw new Error('Timed out waiting for DUST to be generated.'); } logger.info(`DUST available: ${dustBalance}`); ``` DUST generates from registered NIGHT over a short period, so the balance starts at 0 and climbs. The script polls every 15 seconds until it goes positive. On local this takes a few seconds; on Preprod expect about 1 to 2 minutes, which is mostly block confirmation plus wallet sync, because DUST itself accrues every second once the registration transaction is on-chain. With the faucet's standard 1,000 tNIGHT that accrual is roughly 0.5 tDUST per minute, capping at 5 tDUST per tNIGHT after about a week, so by the time the balance goes positive you already hold far more than the deployment and calls below cost. Build the providers, deploy the contract, and read its initial state: ``` const providers = buildProviders(wallet, zkConfigPath, config); // The owner secret gates mint and transfer. It is random per run; a real // deployment would persist it, because without it this contract can never // mint or transfer again. const ownerSecret = randomBytes(32); const deployed = await deployContract(providers, { compiledContract: CompiledUnshieldedToken, privateStateId: 'unshielded-token', initialPrivateState: {}, args: [ownerSecret], }); const contractAddress = deployed.deployTxData.public.contractAddress; logger.info(`Deployed at ${contractAddress}`); async function readLedger() { const state = await providers.publicDataProvider.queryContractState(contractAddress); return ledger(state!.data); } logger.info(`initialized at deploy: ${(await readLedger()).initialized}`); // false ``` `deployContract` returns the on-chain address, and `args` carries the constructor arguments, here the owner secret. The constructor stores only the secret's hash; the secret itself never leaves the script. `queryContractState` fetches the contract's public state, and `ledger(...)` decodes it into the fields you declared. Right after deployment, `initialized` is false. Mint the supply, then read the state back to confirm the token exists: ``` await submitCallTx(providers, { compiledContract: CompiledUnshieldedToken, contractAddress, privateStateId: 'unshielded-token', circuitId: 'mint', args: [ownerSecret, 1000n], }); const afterMint = await readLedger(); logger.info(`initialized after mint: ${afterMint.initialized}`); // true logger.info(`token color: ${toHex(afterMint.token_color)}`); ``` `submitCallTx` runs the mint circuit on-chain. The `args` mirror the Compact signature: the owner secret first, then the amount. The secret is witness data, so it feeds the proof without appearing in the transaction. After it, `initialized` is true and `token_color` holds the color the mint produced. The token now exists, and the contract holds all 1,000 units. Transfer some units to your own wallet, then read the wallet's balance to confirm they arrived: ``` // A UserAddress circuit argument is { bytes: Uint8Array }, the recipient's raw // address bytes, so pull those bytes out of the wallet's address object. function toUserAddressBytes(unshielded: any): Uint8Array { const pk = unshielded?.state?.publicKey ?? unshielded?.publicKey; if (pk?.address instanceof Uint8Array) return pk.address; if (typeof pk?.addressHex === 'string') return fromHex(pk.addressHex); const addr = unshielded?.address; if (addr?.bytes instanceof Uint8Array) return addr.bytes; if (addr?.data instanceof Uint8Array) return addr.data; if (typeof addr?.addressHex === 'string') return fromHex(addr.addressHex); throw new Error('Could not find raw unshielded address bytes.'); } const recipient = { bytes: toUserAddressBytes(syncedState.unshielded) }; await submitCallTx(providers, { compiledContract: CompiledUnshieldedToken, contractAddress, privateStateId: 'unshielded-token', circuitId: 'transfer', args: [ownerSecret, recipient, 100n], }); const after = await syncWallet(logger, wallet.wallet, 60 * 60_000); const color = toHex(afterMint.token_color); logger.info(`wallet balance of the token: ${after.unshielded.balances[color] ?? 0n}`); // 100 await wallet.stop(); ``` A UserAddress circuit argument is an object of the form `{ bytes: Uint8Array }`, the recipient's raw address bytes, so `toUserAddressBytes` pulls those bytes out of the wallet's address. The transfer call then moves 100 units from the contract to your wallet address. After syncing again, the wallet reports a balance of 100 for the token's color, which proves the transfer landed on-chain. ### Run it[​](#run-it "Direct link to Run it") With the local network running in its own terminal, run the deploy script against it using the genesis wallet seed: ``` MIDNIGHT_NETWORK=local \ MIDNIGHT_SEED=0000000000000000000000000000000000000000000000000000000000000001 \ npx tsx src/deploy.ts ``` That seed is the local network's genesis wallet, which midnight-local-dev already funded with NIGHT and registered for DUST. The script syncs, sees the funds, waits a few seconds for DUST, then deploys, mints, and transfers. You should see the contract address, `initialized` flipping to true after the mint, and a wallet balance of 100 after the transfer. You have now created an unshielded token and moved it, end to end. #### Run against Preprod instead[​](#run-against-preprod-instead "Direct link to Run against Preprod instead") The same script runs against Preprod with two differences: you provide your own funded wallet, and you keep a standalone proof server running (see [Start the local network](#start-the-local-network)). First, generate a throwaway wallet seed, a 32-byte value written as a hex string: ``` openssl rand -hex 32 ``` Treat it as a throwaway test wallet: it only ever holds test funds, and you should not reuse it anywhere real. Then run the script with that seed, giving Node extra memory headroom for the longer remote sync: ``` NODE_OPTIONS="--max-old-space-size=8192" \ MIDNIGHT_NETWORK=preprod \ MIDNIGHT_SEED= \ npx tsx src/deploy.ts ``` The script prints your wallet's address and waits. Copy that address, open the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/), paste it in, and request tNIGHT. Once the funds land the script registers them for DUST, waits for the DUST to generate, then deploys, mints, and transfers exactly as it does on local. Expect it to take a couple of minutes more than the local run. ## What's next[​](#whats-next "Direct link to What's next") Next, you build the [shielded version of this token](/tokens/shielded-token.md). Because a shielded balance is hidden, the chain can't track it for you, so the contract mints a shielded coin and delivers it to the caller in a single transaction, and you confirm the result by reading the wallet's shielded balance. You reuse the same wallet and provider setup from this part and connect to the same networks. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Troubleshoot compiler errors This guide covers common Compact compiler errors, their causes, and how to fix them. ## Exit codes[​](#exit-codes "Direct link to Exit codes") The Compact compiler returns the following exit codes: | Code | Meaning | Fix | | ---- | -------------------------- | ------------------------------------------------ | | 0 | Compilation succeeded | No action required | | 1 | Bad command-line arguments | Check `compact compile --help` for correct flags | | 255 | Compilation failed | Fix the reported source errors and recompile | ## Error severity levels[​](#error-severity-levels "Direct link to Error severity levels") The Compact compiler uses the following error severity levels: | Mechanism | Severity | Description | | ----------------- | -------- | ------------------------------------------------------ | | `source-errorf` | Fatal | User-visible error with source location | | `source-warningf` | Warning | Continuable warning with source location | | `pending-errorf` | Deferred | Collected and shown together after the pass | | `internal-errorf` | Fatal | Compiler internal bug; report this to the Compact team | | `external-errorf` | Fatal | External tool or file system error | ## Lexer errors[​](#lexer-errors "Direct link to Lexer errors") These errors occur during tokenization, before any parsing takes place. ### Unexpected end of file[​](#unexpected-end-of-file "Direct link to Unexpected end of file") **Message**: `"unexpected end of file"` **Triggers**: The compiler reaches the end of the file while inside an unclosed string literal or block comment. **Fix**: Check for unclosed strings (`"…`) and unclosed block comments (`/* …`) in the source file. ### Unexpected newline[​](#unexpected-newline "Direct link to Unexpected newline") **Message**: `"unexpected newline"` **Triggers**: The compiler encounters a line break inside a context where a newline is not valid, such as inside a single-line string literal. **Fix**: Ensure string literals do not span multiple lines. Use concatenation or a supported multi-line construct instead. ### Unexpected character[​](#unexpected-character "Direct link to Unexpected character") **Message**: `"unexpected character ''"` **Triggers**: The compiler encounters a character that is not valid in Compact source code. **Fix**: Remove or replace the invalid character. Check for non-ASCII characters, stray punctuation, or invisible Unicode characters copied from external sources. ### Nested block comment[​](#nested-block-comment "Direct link to Nested block comment") **Message**: `"attempt to nest block comment"` **Triggers**: Using `/*` inside an already-open `/* */` block comment. **Fix**: Compact does not support nested block comments. Use line comments (`//`) for inner comments, or restructure to avoid nesting. ### Numeric literal out of Field range[​](#numeric-literal-out-of-field-range "Direct link to Numeric literal out of Field range") **Message**: `" is out of Field range"` **Triggers**: A numeric literal exceeds the maximum representable Field value. **Fix**: Use a smaller number. Field values are bounded by the prime used in the ZK proof system. ### Invalid digit in binary literal[​](#invalid-digit-in-binary-literal "Direct link to Invalid digit in binary literal") **Message**: `"unexpected digit (expected 0 or 1)"` **Triggers**: A digit other than `0` or `1` appears in a `0b…` literal. **Fix**: Binary literals may only contain the digits `0` and `1`. ### Invalid digit in octal literal[​](#invalid-digit-in-octal-literal "Direct link to Invalid digit in octal literal") **Message**: `"unexpected digit (expected 0 through 7)"` **Triggers**: A digit `8` or `9` appears in a `0o…` literal. **Fix**: Octal literals may only contain digits `0` through `7`. ## Parser errors[​](#parser-errors "Direct link to Parser errors") These errors occur after tokenization, while the compiler builds the AST. ### Parse error[​](#parse-error "Direct link to Parse error") **Message**: `"parse error: found looking for "` **Triggers**: Any syntax that does not match the Compact grammar at the current parse position. **Fix**: Read the location carefully. Common causes include: * Missing semicolons at the end of statements * Mismatched braces `{` / `}` * Wrong or misspelled keyword * Extra or missing commas in argument lists ### Unrecognized pragma setting[​](#unrecognized-pragma-setting "Direct link to Unrecognized pragma setting") **Message**: `"unrecognized pragma setting "` **Triggers**: A `pragma` directive uses a value the compiler does not recognize. **Fix**: Check supported pragma directives. Example of a valid pragma: ``` pragma language_version >= 0.23; ``` ### File I/O errors[​](#file-io-errors "Direct link to File I/O errors") The compiler returns the following messages: * `"error opening source file"` * `"error reading source file"` * `" is a directory"` **Triggers**: The compiler encounters an error opening or reading the specified source file, or the path points to a directory. **Fix**: Verify the file path is correct, the file exists, and it has a `.compact` extension. Do not pass a directory path where the compiler expects a file. ## Witness and disclosure errors[​](#witness-and-disclosure-errors "Direct link to Witness and disclosure errors") These errors enforce Compact's privacy model around witness values. ### Undeclared witness disclosure[​](#undeclared-witness-disclosure "Direct link to Undeclared witness disclosure") **Message**: `"potential witness-value disclosure must be declared but is not"` **Triggers**: A witness value flows to the ledger or a public output without a `disclose()` wrapper. **Fix**: Wrap the witness value in `disclose()` before it reaches any ledger state or public output: ``` disclose(witnessValue) ``` The `disclose()` wrapper declares private data as safe to write to the public ledger state. ### Witness returns contract-typed value[​](#witness-returns-contract-typed-value "Direct link to Witness returns contract-typed value") **Message**: `"invalid type for witness return value: witness return values cannot include contract values"` **Triggers**: A witness function declares a return type that includes a contract-typed value. **Fix**: Remove any contract-typed values from the witness return type. Witnesses can return structs, enums, and other regular types, but not contract values. Pass any contract-related information as individual fields instead. ## ZKIR generation errors[​](#zkir-generation-errors "Direct link to ZKIR generation errors") These errors occur when the compiler generates the ZK Intermediate Representation (ZKIR) from the type-checked AST. ### Cross-contract calls not yet supported[​](#cross-contract-calls-not-yet-supported "Direct link to Cross-contract calls not yet supported") **Message**: `"cross-contract calls are not yet supported"` **Triggers**: The contract attempts a cross-contract call, which the ZKIR output stage does not yet support. **Fix**: This is a current compiler limitation. Restructure to avoid cross-contract calls until the feature is available. ### ZKIR non-zero exit status[​](#zkir-non-zero-exit-status "Direct link to ZKIR non-zero exit status") **Message**: `"zkir returned a non-zero exit status "` **Triggers**: The external ZKIR compilation tool exited with an error. **Fix**: Review the output for details on the unsupported operation. Check for operations in circuits that the ZKIR backend does not yet support. ## Runtime errors[​](#runtime-errors "Direct link to Runtime errors") These errors originate from compiled contracts executing in the Midnight runtime, not from the compiler itself. ### Base error class[​](#base-error-class "Direct link to Base error class") **Class**: `CompactError` **Description**: `CompactError` is the base class for all contract runtime errors. Catch this type to handle any Compact contract error generically. ### Failed assertion[​](#failed-assertion "Direct link to Failed assertion") **Message**: `"failed assert: "` **Triggers**: A Compact `assert` expression evaluated to `false` at runtime. **Fix**: Investigate the assertion condition. The `` text is the string you provided to `assert`. Use it to locate the assertion in your contract source and determine why the condition was not satisfied. ### Runtime type error[​](#runtime-type-error "Direct link to Runtime type error") **Message**: `"type error: at ; expected value of type but received "` **Triggers**: A runtime type mismatch in the generated code, typically caused by a mismatch between declared witness return types and the actual values produced at runtime. **Fix**: Check witness return types. Ensure that the TypeScript witness implementation returns values that conform to the types declared in the Compact contract. ### Version mismatch[​](#version-mismatch "Direct link to Version mismatch") **Message**: `"version mismatch: compiled code expects X.Y.Z, runtime is A.B.C"` **Triggers**: You compiled the smart contract with one version of the Compact compiler but run it against a different version of `@midnight-ntwrk/compact-runtime`. **Fix**: Update `@midnight-ntwrk/compact-runtime` in your project to match the compiler version used to build the contract. Alternatively, recompile the contract with the compiler version that matches your runtime. Version compatibility Always refer to the [compatibility matrix](/relnotes/support-matrix.md) to verify which versions work together. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Frequently asked questions Find answers to common questions about the Midnight Network, development tools, and troubleshooting. If you cannot find the answer you need, see the [getting help](/troubleshoot/getting-help.md) page for additional support resources. ## General questions[​](#general-questions "Direct link to General questions") This section answers some of the most common questions about Midnight Network. ### Is there a Midnight white paper?[​](#is-there-a-midnight-white-paper "Direct link to Is there a Midnight white paper?") Yes. Midnight provides technical white papers covering the network architecture and economic model: * **Nightpaper**: Technical overview of the Midnight Network architecture and privacy-preserving smart contract system. * **Tokenomics incentives**: Detailed explanation of the NIGHT token economics and network incentive mechanisms. For more information, see [midnight.network/whitepaper](https://midnight.network/whitepaper). ### What tokens are available for use on Testnet? Are there gas fees?[​](#what-tokens-are-available-for-use-on-testnet-are-there-gas-fees "Direct link to What tokens are available for use on Testnet? Are there gas fees?") Testnet uses only one token: test DUST (**tDUST**), which is a test token used for Midnight Testnet testing purposes only. Visit the [token acquisition page](/guides/acquire-tokens.md) to find out more. This may change in future versions of Midnight, and may include the calibration of the gas fees against the amount work performed by a computation. ## Developer questions[​](#developer-questions "Direct link to Developer questions") This section answers some of the most common questions about developing on Midnight Network. ### Where do I go if I need help troubleshooting my code?[​](#where-do-i-go-if-i-need-help-troubleshooting-my-code "Direct link to Where do I go if I need help troubleshooting my code?") The [Getting help](/troubleshoot/getting-help.md) section of this site describes multiple ways to communicate with the Midnight team and your fellow developers. Your questions, including those about troubleshooting your code, are welcome. ### What types of DApps can I build on the Midnight Testnet?[​](#what-types-of-dapps-can-i-build-on-the-midnight-testnet "Direct link to What types of DApps can I build on the Midnight Testnet?") Theoretically, any DApp that does not require one contract to call another from within its circuits. This includes private payment DApps, private auction DApps, and DApps that enable shielded identity verification. ### What types of DApps can *not* yet be built on Testnet?[​](#what-types-of-dapps-can-not-yet-be-built-on-testnet "Direct link to what-types-of-dapps-can-not-yet-be-built-on-testnet") DApps that require an oracle (for pricing data info or other external data), such as a DeFi lending DApp requiring Bitcoin pricing data. ### Can I reuse Solidity code on Midnight?[​](#can-i-reuse-solidity-code-on-midnight "Direct link to Can I reuse Solidity code on Midnight?") No, Midnight DApps are created in TypeScript and Compact, a custom programming language, to build zero-knowledge circuits that generate privacy proofs. ### What are the key unique concepts or coding patterns I need to know to create DApps on Midnight?[​](#what-are-the-key-unique-concepts-or-coding-patterns-i-need-to-know-to-create-dapps-on-midnight "Direct link to What are the key unique concepts or coding patterns I need to know to create DApps on Midnight?") One of the key ideas in Midnight is the distinction between information that you want to place in the public record and information that you want to keep private. For example, the assertion that someone is over 25 might be useful to place in the public space of a contract, while the details of the person's birthday and precise age might be kept private. This kind of thinking about what is truly needed in the public sphere is a core aspect of Midnight programming. After writing the contract in Midnight’s contract language, the DApp is written in standard TypeScript. This implies that the coding experience of existing JavaScript and TypeScript programmers can be applied to creating Midnight DApps. ### How does Midnight work at a high level?[​](#how-does-midnight-work-at-a-high-level "Direct link to How does Midnight work at a high level?") See [Midnight's architecture](/concepts/how-midnight-works/midnight-combined-model.md) and the section of this site about [How Midnight works](/concepts.md). ### What is the current Testnet block time (time to finality)?[​](#what-is-the-current-testnet-block-time-time-to-finality "Direct link to What is the current Testnet block time (time to finality)?") Testnet block time is 6 seconds. This time is governed by network parameters that are subject to adjustment. Finality will occur typically one or two blocks after block creation (so within 18 seconds). ### I'm getting `ERR_UNSUPPORTED_DIR_IMPORT`. What should I do?[​](#im-getting-err_unsupported_dir_import-what-should-i-do "Direct link to im-getting-err_unsupported_dir_import-what-should-i-do") This error typically occurs when Node.js tries to import a directory instead of a specific file, which can happen if your terminal environment is stale after updating `~/.zshrc`, changing Node versions, or setting environment variables. To fix this: * Open a new terminal window (don’t just run `source ~/.zshrc`) after changing your shell config or switching Node versions. * Ensure you're using the correct Node version (Midnight requires Node 22+). Run: ``` nvm use ``` * Clear any module cache: ``` rm -rf node_modules/.cache ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Support As a participant in the Midnight Testnet, you have the opportunity to shape the future of Midnight by reporting issues, suggesting enhancements, and directly influencing the development process. ## Connectivity failures, bugs, general problems, and suggestions[​](#connectivity-failures-bugs-general-problems-and-suggestions "Direct link to Connectivity failures, bugs, general problems, and suggestions") There are two ways to report problems, make suggestions, give feedback, or just ask for help: 1. Participate in a discussion on the [Midnight Discord server](https://discord.gg/midnightnetwork). The Midnight team will be monitoring the `#support` channel regularly. **Important:** when you first join the Midnight Discord server, you must accept the rules in the `#rules` before you can access other content on the server. 2. Send email to [Midnight support](mailto:support@midnight.network). ## Security vulnerabilities[​](#security-vulnerabilities "Direct link to Security vulnerabilities") If you discover any security vulnerabilities in the Midnight libraries or infrastructure, please report them using the following protocol: 1. Do *not* post security vulnerabilities on the support channel on Discord. 2. Instead, please send a report of what you have found to the Midnight support email address: . If you have a fix or workaround for the vulnerability, please describe that, too. 3. The Midnight team will evaluate your report and may release a fix or publish instructions for mitigating the vulnerability. The team will inform you of the outcome directly. 4. Unless you request otherwise, the Midnight team will credit you for finding the problem in any publication of a fix or mitigation. 5. After the Midnight team has either published a fix or informed you that the vulnerability will not be addressed, you are free to disclose it publicly. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Troubleshoot Compact toolchain installation issue on NixOS Compact is Midnight’s dedicated smart contract programming language designed for building secure, efficient and adaptable decentralized applications. Compact tools are command-line utility for installing, updating, managing, and running the compact toolchain and compiler. This guide walks you through installing Midnight compact tools on NixOS. ### Compiler version scope[​](#compiler-version-scope "Direct link to Compiler version scope") note Installation problems only concern versions of the compact compiler **0.26**. A fix has already been made and the guide will become obsolete upon official release of version 0.27. By the end of the guide, you will: * Understand why standard installations fail on NixOS. * Install and run compact for Midnight development. * Fix “No such file or directory” errors for `compactc`. ### Prerequisites[​](#prerequisites "Direct link to Prerequisites") * NixOS version 23.11 * 24.05 * 25.11 **(recommended stable release)** Familiarity with command-line interfaces. *** ## Why standard installations fail on NixOS[​](#why-standard-installations-fail-on-nixos "Direct link to Why standard installations fail on NixOS") Standard installations fail on NixOS because unlike traditional Linux distributions it is not configured to follow the Filesystem Hierarchy Standard (FHS) which defines the directory structure and directory content in Linux operating systems. The main reason for this deviation is because it does not provide isolation, it instead uses the filesystem as a database and to store packages in isolation in a special directory called the Nix store. This causes issues when applications download binaries that expect a traditional FHS structure. ## Install the Compact compiler (FHS Environment)[​](#install-the-compact-compiler-fhs-environment "Direct link to Install the Compact compiler (FHS Environment)") To install the compiler, use `buildFHSEnv` a tool that creates a lightweight sandbox environment that simulates a traditional FHS system. It creates an isolated root filesystem with the host’s `/nix/store`, so its footprint in terms of disk space is quite small. This allows you to run software which is hard or unfeasible to patch for NixOS. ### Create shell.nix[​](#create-shellnix "Direct link to Create shell.nix") Create a file called `shell.nix` with the code snippet below: ``` { pkgs ? import {} }: pkgs.buildFHSEnv { name = "x-11"; targetPkgs = pkgs: [ pkgs.bash pkgs.glibc pkgs.curl]; runScript = "exec ${pkgs.bash}/bin/bash"; } ``` Alternative for macOS (mkShell) If you are on macOS, use this version of the file instead: ``` { pkgs ? import {} }: pkgs.mkShell { name = "x-11"; buildInputs = with pkgs; [ bash glibc curl ]; } ``` ### Run nix-shell[​](#run-nix-shell "Direct link to Run nix-shell") Run this command to enter the environment: ``` nix-shell ``` ### Download the Compact compiler[​](#download-the-compact-compiler "Direct link to Download the Compact compiler") Inside the shell, run the installer: ``` curl --proto '=https' --tlsv1.2 -LsSf https://github.com/midnightntwrk/compact/releases/latest/download/compact-installer.sh | sh ``` ### Update Compact[​](#update-compact "Direct link to Update Compact") Once installed, update to the latest version: ``` compact update ``` ## Fix “No such file or directory (os error 2)” error[​](#fix-no-such-file-or-directory-os-error-2-error "Direct link to Fix “No such file or directory (os error 2)” error") Even within the FHS environment, the installed Compact wrapper script `compactc` often fails when `compact compile -help` is run because it contains a hardcoded shebang (`#!`) line pointing to `bin/bash`, which the installer does not correctly resolve at the exact path resulting to a `No such file or directory(os error 2)`error. **To fix this**: Modify the installed Compact wrapper script to correctly point to the `bash` binary that is accessible inside the FHS sandbox. Create a file called `compact_util.sh` in the root directory. This file serves as the utility script: ``` #!/usr/bin/env bash cd ./.compact/versions/0.26.0/x86_64-unknown-linux-musl sed -i '1 i #!/usr/bin/env bash' compactc ``` Make script executable, run this command to change permissions: ``` chmod +x compact_util.sh ``` Run the utility script: ``` ./compact_util.sh ``` Verify installation,check that the compiler is now accessible: ``` compact compile --help ``` ## Next steps[​](#next-steps "Direct link to Next steps") Midnight is a blockchain platform for building privacy-preserving DApps. It enables developers to define how data is isolated, verified, and shared through zero-knowledge (ZK) proofs and programmable confidentiality controls. [To get started with Midnight](/getting-started.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Tutorials Step-by-step tutorials for building DApps on Midnight Network. Start with the entry-level tutorials and work up to end-to-end deployments. [✦](/tutorials/bboard.md) ### [Bulletin board](/tutorials/bboard.md) [Build a bulletin board DApp that uses ZK proofs for access control, so users can post and remove messages without revealing their identity on-chain.](/tutorials/bboard.md) [Build bulletin board→](/tutorials/bboard.md) [✦](/tutorials/private-party/smart-contract.md) ### [Private party](/tutorials/private-party/smart-contract.md) [Build a privacy application that demonstrates the privacy boundary in Midnight DApps.](/tutorials/private-party/smart-contract.md) [Write the contract→](/tutorials/private-party/smart-contract.md) [✦](/tutorials/bship.md) ### [Battleship](/tutorials/bship.md) [Write a contract that mixes public and private state as a state machine, then verify it with MidnightJS tests on a local devnet.](/tutorials/bship.md) [Build Battleship→](/tutorials/bship.md) [✦](/tutorials/leaderboard.md) ### [Leaderboard](/tutorials/leaderboard.md) [Build a full-stack DApp with structured on-chain data, privacy controls via disclose(), Lace wallet integration, and production deployment.](/tutorials/leaderboard.md) [Build leaderboard→](/tutorials/leaderboard.md) [✦](/tutorials/zk-loan.md) ### [ZK Loan](/tutorials/zk-loan.md) [Build a loan DApp that privately evaluates credit data with ZK proofs, covering Compact contract logic, a Schnorr-signed attestation API, and a CLI.](/tutorials/zk-loan.md) [Build ZK Loan→](/tutorials/zk-loan.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Bulletin board tutorial Build a privacy-preserving bulletin board DApp. Users post and remove messages while ZK proofs protect poster identity on-chain. [✦](/tutorials/bboard/smart-contract.md) ### [Bulletin board contract](/tutorials/bboard/smart-contract.md) [Write a Compact contract with private state, ZK identity proofs, and cryptographic access control for message management.](/tutorials/bboard/smart-contract.md) [Write the contract→](/tutorials/bboard/smart-contract.md) [✦](/tutorials/bboard/bboard-cli.md) ### [Bulletin board CLI](/tutorials/bboard/bboard-cli.md) [Build a CLI that deploys the contract, manages wallets, and lets users post and remove messages interactively.](/tutorials/bboard/bboard-cli.md) [Build the CLI→](/tutorials/bboard/bboard-cli.md) [✦](/tutorials/bboard/bboard-api-implementation.md) ### [API implementation](/tutorials/bboard/bboard-api-implementation.md) [Create a reusable API layer for contract deployment, state management, and transaction submission.](/tutorials/bboard/bboard-api-implementation.md) [Build the API→](/tutorials/bboard/bboard-api-implementation.md) [✦](/tutorials/bboard/bboard-cli-implementation.md) ### [CLI implementation](/tutorials/bboard/bboard-cli-implementation.md) [Implement wallet management, DUST generation, and the interactive command-line interface.](/tutorials/bboard/bboard-cli-implementation.md) [Implement the CLI→](/tutorials/bboard/bboard-cli-implementation.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Bulletin board API implementation This tutorial shows how to implement the API package that provides a reusable abstraction layer for bulletin board contract interactions. This package can be shared between the CLI and browser-based UI. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, ensure that you have completed the [bulletin board CLI setup](/tutorials/bboard/bboard-cli.md) and installed root dependencies. ## Create the API directory[​](#create-the-api-directory "Direct link to Create the API directory") From the root, create the API structure: ``` mkdir -p api/src/utils cd api ``` ## Configure the API package[​](#configure-the-api-package "Direct link to Configure the API package") Create `api/package.json`: ``` { "name": "@midnight-ntwrk/bboard-api", "version": "0.1.0", "author": "IOG", "license": "MIT", "private": true, "type": "module", "module": "./dist/index.js", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "rm -rf dist && tsc --project tsconfig.build.json", "ci": "npm run typecheck && npm run lint && npm run build", "lint": "eslint src", "typecheck": "tsc -p tsconfig.json --noEmit" } } ``` ## Configure TypeScript[​](#configure-typescript "Direct link to Configure TypeScript") Create `api/tsconfig.json`: ``` { "include": ["src/**/*.ts", "src/test/jest.setup.ts"], "compilerOptions": { "outDir": "dist", "declaration": true, "lib": ["ESNext", "DOM"], "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "types": [], "allowJs": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "strict": true, "isolatedModules": true, "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true } } ``` Create `api/tsconfig.build.json` to exclude test files from production builds: ``` { "extends": "./tsconfig.json", "exclude": ["src/test/**/*.ts"], "compilerOptions": {} } ``` ## Implement utility functions[​](#implement-utility-functions "Direct link to Implement utility functions") Create `api/src/utils/index.ts`: api/src/utils/index.ts ``` /** * Provides utility functions. * * @module */ /** * Generates a buffer containing a series of randomly generated bytes. * * @param length The number of bytes to generate. * @returns A `Uint8Array` representing `length` randomly generated bytes. */ export const randomBytes = (length: number): Uint8Array => { const bytes = new Uint8Array(length); crypto.getRandomValues(bytes); return bytes; }; ``` This utility function generates cryptographically secure random bytes using the Web Crypto API. The bulletin board uses this to generate secret keys for users. ## Define common types[​](#define-common-types "Direct link to Define common types") Create `api/src/common-types.ts`: api/src/common-types.ts ``` import { type MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; import { type FoundContract } from '@midnight-ntwrk/midnight-js-contracts'; import type { State, BBoardPrivateState, Contract, Witnesses } from '../../contract/src/index'; export const bboardPrivateStateKey = 'bboardPrivateState'; export type PrivateStateId = typeof bboardPrivateStateKey; export type PrivateStates = { readonly bboardPrivateState: BBoardPrivateState; }; export type BBoardContract = Contract>; export type BBoardCircuitKeys = Exclude; export type BBoardProviders = MidnightProviders; export type DeployedBBoardContract = FoundContract; export type BBoardDerivedState = { readonly state: State; readonly sequence: bigint; readonly message: string | undefined; readonly isOwner: boolean; }; ``` These type definitions create aliases for complex generic types. The `BBoardDerivedState` combines public ledger state with computed ownership information. The `isOwner` field determines whether the current user posted the message by comparing the ledger's owner commitment with the user's secret key. ## Implement the BBoardAPI class[​](#implement-the-bboardapi-class "Direct link to Implement the BBoardAPI class") The `BBoardAPI` class provides a high-level interface for interacting with the bulletin board smart contract. It handles contract deployment, state management, and transaction submission while exposing a reactive state observable for real-time updates. Create `api/src/index.ts` and add the following sections. ### Import required packages[​](#import-required-packages "Direct link to Import required packages") api/src/index.ts ``` import * as BBoard from '../../contract/src/managed/bboard/contract/index.js'; import { type ContractAddress, convertFieldToBytes } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { type Logger } from 'pino'; import { type BBoardDerivedState, type BBoardContract, type BBoardProviders, type DeployedBBoardContract, bboardPrivateStateKey, } from './common-types.js'; import { CompiledBBoardContractContract } from '../../contract/src/index'; import * as utils from './utils/index.js'; import { deployContract, findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; import { combineLatest, map, tap, from, type Observable } from 'rxjs'; import { toHex } from '@midnight-ntwrk/midnight-js-utils'; import { BBoardPrivateState, createBBoardPrivateState } from '../../contract/src/witnesses.js'; ``` ### Define the API interface[​](#define-the-api-interface "Direct link to Define the API interface") api/src/index.ts ``` export interface DeployedBBoardAPI { readonly deployedContractAddress: ContractAddress; readonly state$: Observable; post: (message: string) => Promise; takeDown: () => Promise; } ``` This interface exposes the contract address, a reactive state observable, and methods for posting and removing messages. ### Implement the constructor and state observable[​](#implement-the-constructor-and-state-observable "Direct link to Implement the constructor and state observable") The `BBoardAPI` class constructor is private, ensuring instances are only created through the static `deploy` or `join` methods. api/src/index.ts ``` export class BBoardAPI implements DeployedBBoardAPI { private constructor( public readonly deployedContract: DeployedBBoardContract, providers: BBoardProviders, private readonly logger?: Logger, ) { this.deployedContractAddress = deployedContract.deployTxData.public.contractAddress; providers.privateStateProvider.setContractAddress(this.deployedContractAddress); this.state$ = combineLatest( [ providers.publicDataProvider.contractStateObservable(this.deployedContractAddress, { type: 'latest' }).pipe( map((contractState) => BBoard.ledger(contractState.data)), tap((ledgerState) => logger?.trace({ ledgerStateChanged: { ledgerState: { ...ledgerState, state: ledgerState.state === BBoard.State.OCCUPIED ? 'occupied' : 'vacant', owner: toHex(ledgerState.owner), }, }, }), ), ), from(providers.privateStateProvider.get(bboardPrivateStateKey) as Promise), ], (ledgerState, privateState) => { const hashedSecretKey = BBoard.pureCircuits.publicKey( privateState.secretKey, convertFieldToBytes(32, ledgerState.sequence, 'api/src/index.ts'), ); return { state: ledgerState.state, message: ledgerState.message.value, sequence: ledgerState.sequence, isOwner: toHex(ledgerState.owner) === toHex(hashedSecretKey), }; }, ); } readonly deployedContractAddress: ContractAddress; readonly state$: Observable; ``` The reactive state observable uses RxJS `combineLatest` to merge two data streams: public ledger state from the indexer and private state from local storage. It computes the `isOwner` flag by hashing the private secret key and comparing it with the on-chain owner field, which determines whether the user can call `takeDown()` to remove their message. ### Implement the post method[​](#implement-the-post-method "Direct link to Implement the post method") api/src/index.ts ``` async post(message: string): Promise { this.logger?.info(`postingMessage: ${message}`); const txData = await this.deployedContract.callTx.post(message); this.logger?.trace({ transactionAdded: { circuit: 'post', txHash: txData.public.txHash, blockHeight: txData.public.blockHeight, }, }); } ``` The `post` method invokes the smart contract's `post` circuit, waits for the zero-knowledge (ZK) proof to be generated and the transaction to be confirmed, then logs the transaction details. ### Implement the takeDown method[​](#implement-the-takedown-method "Direct link to Implement the takeDown method") api/src/index.ts ``` async takeDown(): Promise { this.logger?.info('takingDownMessage'); const txData = await this.deployedContract.callTx.takeDown(); this.logger?.trace({ transactionAdded: { circuit: 'takeDown', txHash: txData.public.txHash, blockHeight: txData.public.blockHeight, }, }); } ``` The `takeDown` method invokes the smart contract's `takeDown` circuit, which requires proof of ownership. It can only succeed if the caller's hashed secret key matches the on-chain owner field. ### Implement the deploy method[​](#implement-the-deploy-method "Direct link to Implement the deploy method") api/src/index.ts ``` static async deploy(providers: BBoardProviders, logger?: Logger): Promise { logger?.info('deployContract'); const deployedBBoardContract = await deployContract(providers, { compiledContract: CompiledBBoardContractContract, privateStateId: bboardPrivateStateKey, initialPrivateState: createBBoardPrivateState(utils.randomBytes(32)), }); logger?.trace({ contractDeployed: { finalizedDeployTxData: deployedBBoardContract.deployTxData.public, }, }); return new BBoardAPI(deployedBBoardContract, providers, logger); } ``` The `deploy` method creates a new bulletin board contract instance on the blockchain by generating a fresh 32-byte secret key for the deployer's private state. Each deployed contract gets a unique on-chain address that other users can use to join and interact with the bulletin board. ### Implement the join method[​](#implement-the-join-method "Direct link to Implement the join method") api/src/index.ts ``` static async join(providers: BBoardProviders, contractAddress: ContractAddress, logger?: Logger): Promise { logger?.info({ joinContract: { contractAddress, }, }); const deployedBBoardContract = await findDeployedContract(providers, { contractAddress, compiledContract: CompiledBBoardContractContract, privateStateId: bboardPrivateStateKey, initialPrivateState: await BBoardAPI.getPrivateState(providers, contractAddress), }); logger?.trace({ contractJoined: { finalizedDeployTxData: deployedBBoardContract.deployTxData.public, }, }); return new BBoardAPI(deployedBBoardContract, providers, logger); } ``` The `join` method connects to an existing deployed bulletin board contract, allowing users to read the public state and, if they deployed the current message, remove it using their secret key. ### Implement private state helper[​](#implement-private-state-helper "Direct link to Implement private state helper") api/src/index.ts ``` private static async getPrivateState( providers: BBoardProviders, contractAddress: ContractAddress, ): Promise { providers.privateStateProvider.setContractAddress(contractAddress); const existingPrivateState = await providers.privateStateProvider.get(bboardPrivateStateKey); return existingPrivateState ?? createBBoardPrivateState(utils.randomBytes(32)); } } ``` The Midnight.js 4.x private state provider scopes stored state per contract address, so the helper first calls `setContractAddress()` before reading. If no private state exists for the given address, the helper generates a new random 32-byte secret key. The private state persists across application restarts, allowing users to prove ownership of their posted messages in future sessions. ### Export utilities and types[​](#export-utilities-and-types "Direct link to Export utilities and types") api/src/index.ts ``` export * as utils from './utils/index.js'; export * from './common-types.js'; ``` These exports make the API's utility functions and TypeScript types available to the CLI application and other consumers of the API module. ## Build the API package[​](#build-the-api-package "Direct link to Build the API package") Build the API package: ``` npm run build ``` This compiles the TypeScript to JavaScript and generates type definitions in the `dist` directory. ## Next steps[​](#next-steps "Direct link to Next steps") Continue to the [CLI implementation](/tutorials/bboard/bboard-cli-implementation.md) tutorial to build the command-line interface that uses this API. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Bulletin board CLI This tutorial explains how to build a command-line interface that interacts with the bulletin board smart contract created in the [bulletin board contract](/tutorials/bboard/smart-contract.md) tutorial. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, ensure that you have: * Completed the [bulletin board contract](/tutorials/bboard/smart-contract.md) tutorial with the contract compiled in `contract/src/managed/bboard/` * Docker Desktop installed and running * Node.js version 24+ ## Architecture overview[​](#architecture-overview "Direct link to Architecture overview") The bulletin board CLI uses a monorepo structure with three packages: * **contract**: The Compact smart contract (from the previous tutorial) * **api**: A reusable abstraction layer for contract interactions * **bboard-cli**: The command-line application The API package provides a high-level interface (`BBoardAPI`) that handles contract deployment, state management, and transaction submission while exposing a reactive state observable for real-time updates. The CLI package implements wallet management, user interaction, and the main application logic. ## Set up the root package[​](#set-up-the-root-package "Direct link to Set up the root package") From the `example-bboard` root directory, create or update `package.json`: ``` { "name": "@midnight-ntwrk/example-bboard", "version": "0.1.0", "author": "IOG", "license": "MIT", "private": true, "type": "module", "engines": { "node": ">=24.11.1" }, "workspaces": { "packages": [ "bboard-cli", "api", "contract" ] }, "dependencies": { "@midnight-ntwrk/dapp-connector-api": "4.0.1", "@midnight-ntwrk/midnight-js-contracts": "4.1.1", "@midnight-ntwrk/midnight-js-fetch-zk-config-provider": "4.1.1", "@midnight-ntwrk/midnight-js-http-client-proof-provider": "4.1.1", "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "4.1.1", "@midnight-ntwrk/midnight-js-level-private-state-provider": "4.1.1", "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-node-zk-config-provider": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-types": "4.1.1", "@midnight-ntwrk/midnight-js-utils": "4.1.1", "@midnight-ntwrk/testkit-js": "4.1.1", "@midnight-ntwrk/wallet-sdk": "1.0.0", "axios": "^1.17.0", "buffer": "^6.0.3", "fp-ts": "^2.16.11", "pino": "^10.3.1", "pino-pretty": "^13.1.3", "rxjs": "^7.8.2", "semver": "^7.8.4", "testcontainers": "^12.0.1", "ws": "^8.21.0" }, "devDependencies": { "@eslint/js": "^9.39.2", "@originjs/vite-plugin-commonjs": "^1.0.3", "@types/babel__core": "^7.20.5", "@types/semver": "^7.7.1", "@types/ws": "^8.18.1", "@typescript-eslint/eslint-plugin": "^8.61.0", "@typescript-eslint/parser": "^8.61.0", "eslint": "^9.39.2", "eslint-config-prettier": "^10.1.8", "eslint-plugin-prettier": "^5.5.6", "eslint-plugin-react": "^7.37.5", "http-server": "^14.1.1", "prettier": "^3.8.4", "ts-node": "^10.9.2", "typescript": "^5.9.3", "typescript-eslint": "^8.61.0", "vite": "^8.0.14", "vite-plugin-top-level-await": "^1.6.0", "vite-plugin-wasm": "^3.6.0" } } ``` The workspaces configuration tells npm to manage the contract, API, and bboard-cli as linked packages. Dependencies defined at the root level are shared across all workspaces, reducing duplication and ensuring version consistency. Wallet SDK consolidation Midnight.js 4.1.x consumes the wallet stack through the bundled `@midnight-ntwrk/wallet-sdk` package and the new `@midnight-ntwrk/midnight-js-protocol` umbrella, which provides subpath imports such as `@midnight-ntwrk/midnight-js-protocol/ledger` and `@midnight-ntwrk/midnight-js-protocol/compact-runtime`. Earlier examples used the standalone `@midnight-ntwrk/wallet-sdk-*` and `@midnight-ntwrk/ledger-v8` packages directly. Version compatibility Always refer to the [release compatibility matrix](/relnotes/support-matrix.md) to ensure you are using compatible versions. Install all dependencies from the root: ``` npm install ``` This command installs dependencies for the root package and all workspace packages, creating symlinks between them for local development. ## Implementation guides[​](#implementation-guides "Direct link to Implementation guides") To build the bulletin board CLI, follow these implementation guides in order: 1. **[API implementation](/tutorials/bboard/bboard-api-implementation.md)**: Set up the API package with the `BBoardAPI` class that handles contract deployment, state management, and transaction submission. 2. **[CLI implementation](/tutorials/bboard/bboard-cli-implementation.md)**: Set up the CLI package with wallet management, DUST generation, and the interactive command-line interface. ## Project structure[​](#project-structure "Direct link to Project structure") The complete example-bboard project uses a monorepo structure with npm workspaces: ``` example-bboard/ ├── package.json # Root package with workspaces ├── contract/ # Compact contract │ ├── src/ │ │ ├── bboard.compact │ │ ├── managed/ │ │ ├── witnesses.ts │ │ └── index.ts │ └── package.json ├── api/ # Shared API layer │ ├── src/ │ │ ├── index.ts # BBoardAPI implementation │ │ ├── common-types.ts # Type definitions │ │ └── utils/ │ │ └── index.ts # Utility functions │ └── package.json └── bboard-cli/ # Bulletin board CLI ├── src/ │ ├── config.ts # Network configuration │ ├── index.ts # Main CLI logic │ ├── logger-utils.ts # Logging setup │ ├── wallet-utils.ts # Wallet synchronization │ ├── generate-dust.ts # DUST generation │ ├── midnight-wallet-provider.ts # Wallet provider │ └── launcher/ │ ├── preprod.ts # Preprod entry point │ ├── preview.ts # Preview entry point │ └── standalone.ts # Standalone entry point ├── proof-server-local.yml # Docker compose for local proof server ├── proof-server.yml # Docker compose for testcontainers └── package.json ``` The monorepo structure enables code sharing between packages through workspace references. ## Run the CLI[​](#run-the-cli "Direct link to Run the CLI") After completing both implementation guides, start a local proof server and then run the CLI from the `bboard-cli` directory: ``` docker compose -f proof-server-local.yml up -d ``` * preprod * preview * standalone ``` npm run preprod-remote ``` ``` npm run preview-remote ``` ``` npm run standalone ``` The `preprod-remote` and `preview-remote` commands start the CLI and connect to the corresponding Midnight remote testnet, while the `standalone` command runs against a local Midnight network using the genesis-mint wallet seed. You should see the following output: ``` You can do one of the following: 1. Build a fresh wallet 2. Build wallet from a seed 3. Exit Which would you like to do? ``` From here, you can choose to build a fresh wallet or build a wallet from a seed. You can also exit the CLI by entering `3`. For more information on running the CLI, see the [Bulletin board DApp](/examples/dapps/bboard.md) example. ## Next steps[​](#next-steps "Direct link to Next steps") Now that you have built a complete bulletin board CLI with privacy-preserving message posting: * **Build the UI**: Create a browser-based interface for the bulletin board using the [DApp connector API](/api-reference/dapp-connector.md). * **Extend functionality**: Add features like message history, multiple boards, or time-limited posts. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Bulletin board CLI implementation This tutorial shows how to implement the CLI package that provides wallet management, DUST generation, and the interactive command-line interface. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, ensure that you have completed the [Bulletin board API implementation](/tutorials/bboard/bboard-api-implementation.md) tutorial. ## Create the CLI directory[​](#create-the-cli-directory "Direct link to Create the CLI directory") From the root, create the bboard-cli structure: ``` cd .. mkdir -p bboard-cli/src/launcher cd bboard-cli ``` ## Configure the CLI package[​](#configure-the-cli-package "Direct link to Configure the CLI package") Create `bboard-cli/package.json`: ``` { "name": "@midnight-ntwrk/bboard-cli", "version": "0.1.0", "author": "IOG", "license": "MIT", "private": true, "type": "module", "scripts": { "build": "rm -rf dist && tsc --project tsconfig.build.json && cp -R ../contract/src/managed dist/contract/src/managed", "ci": "npm run typecheck && npm run lint && npm run build", "lint": "eslint src", "prepack": "npm run build", "standalone": "node --experimental-specifier-resolution=node --loader ts-node/esm src/launcher/standalone.ts", "preview-remote": "node --experimental-specifier-resolution=node --loader ts-node/esm src/launcher/preview.ts", "preprod-remote": "node --experimental-specifier-resolution=node --loader ts-node/esm src/launcher/preprod.ts", "typecheck": "tsc -p tsconfig.json --noEmit" }, "devDependencies": { "@types/json-schema": "^7.0.15", "@types/node": "^25.3.0" } } ``` Each launcher script targets a different network: * `preprod-remote`: Connects to the hosted **Preprod** testnet * `preview-remote`: Connects to the hosted **Preview** testnet * `standalone`: Connects to a local Midnight network running on your machine using the genesis-mint wallet seed info For more information on setting up a local Midnight network, see [Running a local network](/guides/networks-and-environments.md#running-a-local-network). ## Configure TypeScript[​](#configure-typescript "Direct link to Configure TypeScript") Create `bboard-cli/tsconfig.json`: ``` { "include": ["src/**/*.ts"], "compilerOptions": { "outDir": "dist", "declaration": true, "lib": ["ESNext"], "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "allowJs": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "strict": true, "isolatedModules": true, "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true } } ``` Create `bboard-cli/tsconfig.build.json` to exclude tests from production builds: ``` { "extends": "./tsconfig.json", "exclude": ["src/**/*.test.ts"], "compilerOptions": {} } ``` ## Network configuration[​](#network-configuration "Direct link to Network configuration") The configuration module defines network-specific settings for connecting to different Midnight environments. It provides a common `Config` interface that standardizes how the CLI accesses network endpoints, manages private state storage, and configures DUST generation settings. Create `bboard-cli/src/config.ts` and start with the shared configuration interface: bboard-cli/src/config.ts ``` import path from 'node:path'; import { EnvironmentConfiguration, getTestEnvironment, RemoteTestEnvironment, TestEnvironment, } from '@midnight-ntwrk/testkit-js'; import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import { Logger } from 'pino'; export interface Config { readonly privateStateStoreName: string; readonly logDir: string; readonly zkConfigPath: string; getEnvironment(logger: Logger): TestEnvironment; readonly generateDust: boolean; } export const currentDir = path.resolve(new URL(import.meta.url).pathname, '..'); ``` The CLI supports three network environments: * **Standalone**: Connects to a local Midnight network running on your machine and uses the genesis-mint wallet seed; DUST generation is disabled because the genesis wallet already holds tDUST. * **Preview**: Connects to the hosted Preview testnet. * **Preprod**: Connects to the hosted Preprod testnet. bboard-cli/src/config.ts ``` export class StandaloneConfig implements Config { getEnvironment(logger: Logger): TestEnvironment { return getTestEnvironment(logger) as TestEnvironment; } privateStateStoreName = 'bboard-private-state'; logDir = path.resolve(currentDir, '..', 'logs', 'standalone', `${new Date().toISOString()}.log`); zkConfigPath = path.resolve(currentDir, '..', '..', 'contract', 'src', 'managed', 'bboard'); generateDust = false; } export class PreviewRemoteConfig implements Config { getEnvironment(logger: Logger): TestEnvironment { setNetworkId('preview'); return new PreviewTestEnvironment(logger); } privateStateStoreName = 'bboard-private-state'; logDir = path.resolve(currentDir, '..', 'logs', 'preview-remote', `${new Date().toISOString()}.log`); zkConfigPath = path.resolve(currentDir, '..', '..', 'contract', 'src', 'managed', 'bboard'); generateDust = true; } export class PreprodRemoteConfig implements Config { getEnvironment(logger: Logger): TestEnvironment { setNetworkId('preprod'); return new PreprodTestEnvironment(logger); } privateStateStoreName = 'bboard-private-state'; logDir = path.resolve(currentDir, '..', 'logs', 'preprod-remote', `${new Date().toISOString()}.log`); zkConfigPath = path.resolve(currentDir, '..', '..', 'contract', 'src', 'managed', 'bboard'); generateDust = true; } export class PreviewTestEnvironment extends RemoteTestEnvironment { constructor(logger: Logger) { super(logger); } private getProofServerUrl(): string { const container = this.proofServerContainer as { getUrl(): string } | undefined; if (!container) { throw new Error('Proof server container is not available.'); } return container.getUrl(); } getEnvironmentConfiguration(): EnvironmentConfiguration { return { walletNetworkId: 'preview', networkId: 'preview', indexer: 'https://indexer.preview.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preview.midnight.network', nodeWS: 'wss://rpc.preview.midnight.network', faucet: 'https://midnight-tmnight-preview.nethermind.dev/', proofServer: this.getProofServerUrl(), }; } } export class PreprodTestEnvironment extends RemoteTestEnvironment { constructor(logger: Logger) { super(logger); } private getProofServerUrl(): string { const container = this.proofServerContainer as { getUrl(): string } | undefined; if (!container) { throw new Error('Proof server container is not available.'); } return container.getUrl(); } getEnvironmentConfiguration(): EnvironmentConfiguration { return { walletNetworkId: 'preprod', networkId: 'preprod', indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql', indexerWS: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws', node: 'https://rpc.preprod.midnight.network', nodeWS: 'wss://rpc.preprod.midnight.network', faucet: 'https://midnight-tmnight-preprod.nethermind.dev/', proofServer: this.getProofServerUrl(), }; } } ``` All three configurations rely on the local Docker proof server for generating zero-knowledge (ZK) proofs. The local proof server provides better performance and doesn't require external network access for proof generation. ## Implement logging utilities[​](#implement-logging-utilities "Direct link to Implement logging utilities") Create `bboard-cli/src/logger-utils.ts`: bboard-cli/src/logger-utils.ts ``` import * as path from 'node:path'; import * as fs from 'node:fs/promises'; import pinoPretty from 'pino-pretty'; import pino from 'pino'; import { createWriteStream } from 'node:fs'; export const createLogger = async (logPath: string): Promise => { await fs.mkdir(path.dirname(logPath), { recursive: true }); const pretty: pinoPretty.PrettyStream = pinoPretty({ colorize: true, sync: true, }); const level = process.env.DEBUG_LEVEL !== undefined && process.env.DEBUG_LEVEL !== null && process.env.DEBUG_LEVEL !== '' ? process.env.DEBUG_LEVEL : 'info'; return pino( { level, depthLimit: 20, }, pino.multistream([ { stream: pretty, level }, { stream: createWriteStream(logPath), level }, ]), ); }; ``` The logger creates two output streams: a pretty-printed console stream for development and a file stream for persistent logs. The log level can be controlled through the `DEBUG_LEVEL` environment variable. ## Implement wallet utilities[​](#implement-wallet-utilities "Direct link to Implement wallet utilities") Wallet utilities manage wallet state synchronization and funding operations. These functions ensure the wallet is properly synced with the blockchain and has sufficient funds before attempting contract interactions. Create `bboard-cli/src/wallet-utils.ts`: bboard-cli/src/wallet-utils.ts ``` import { UnshieldedTokenType } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { type FacadeState, type WalletFacade } from '@midnight-ntwrk/wallet-sdk-facade'; import { type ShieldedWalletAPI, type ShieldedWalletState } from '@midnight-ntwrk/wallet-sdk-shielded'; import { type UnshieldedWalletAPI, type UnshieldedWalletState } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet'; import * as Rx from 'rxjs'; import { FaucetClient, type EnvironmentConfiguration } from '@midnight-ntwrk/testkit-js'; import { Logger } from 'pino'; import { UnshieldedAddress } from '@midnight-ntwrk/wallet-sdk-address-format'; import { getNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; ``` ### Get initial wallet state[​](#get-initial-wallet-state "Direct link to Get initial wallet state") Before starting wallet synchronization, you need to access the current state to retrieve addresses and check balances. These helper functions use RxJS `firstValueFrom()` to convert the wallet's state observable into a Promise that resolves with the first emitted value. Add the initial state functions: bboard-cli/src/wallet-utils.ts ``` export const getInitialShieldedState = async ( logger: Logger, wallet: ShieldedWalletAPI, ): Promise => { logger.info('Getting initial state of wallet...'); return Rx.firstValueFrom(wallet.state); }; export const getInitialUnshieldedState = async ( logger: Logger, wallet: UnshieldedWalletAPI, ): Promise => { logger.info('Getting initial state of wallet...'); return Rx.firstValueFrom(wallet.state); }; ``` These functions provide type-safe access to wallet state: * `getInitialShieldedState()`: Retrieves shielded wallet state from a `ShieldedWalletAPI` and logs the operation * `getInitialUnshieldedState()`: Retrieves unshielded wallet state from an `UnshieldedWalletAPI` and logs the operation ### Sync wallet[​](#sync-wallet "Direct link to Sync wallet") The `syncWallet` function monitors the wallet's synchronization progress across all three components (shielded, unshielded, and DUST) and waits until they are fully synced with the blockchain. This is essential before performing any wallet operations. Add the sync wallet function: bboard-cli/src/wallet-utils.ts ``` const isProgressStrictlyComplete = (progress: unknown): boolean => { if (!progress || typeof progress !== 'object') { return false; } const candidate = progress as { isStrictlyComplete?: unknown }; if (typeof candidate.isStrictlyComplete !== 'function') { return false; } return (candidate.isStrictlyComplete as () => boolean)(); }; const isFacadeStateSynced = (state: FacadeState): boolean => isProgressStrictlyComplete(state.shielded.state.progress) && isProgressStrictlyComplete(state.dust.state.progress) && isProgressStrictlyComplete(state.unshielded.progress); export const syncWallet = (logger: Logger, wallet: WalletFacade, throttleTime = 2_000) => { logger.info('Syncing wallet...'); return Rx.firstValueFrom( wallet.state().pipe( Rx.tap((state: FacadeState) => { const shieldedSynced = isProgressStrictlyComplete(state.shielded.state.progress); const unshieldedSynced = isProgressStrictlyComplete(state.unshielded.progress); const dustSynced = isProgressStrictlyComplete(state.dust.state.progress); logger.debug( `Wallet synced state emission: { shielded=${shieldedSynced}, unshielded=${unshieldedSynced}, dust=${dustSynced} }`, ); }), Rx.throttleTime(throttleTime), Rx.tap((state: FacadeState) => { const shieldedSynced = isProgressStrictlyComplete(state.shielded.state.progress); const unshieldedSynced = isProgressStrictlyComplete(state.unshielded.progress); const dustSynced = isProgressStrictlyComplete(state.dust.state.progress); const isSynced = shieldedSynced && dustSynced && unshieldedSynced; logger.debug( `Wallet synced state emission (synced=${isSynced}): { shielded=${shieldedSynced}, unshielded=${unshieldedSynced}, dust=${dustSynced} }`, ); }), Rx.filter((state: FacadeState) => isFacadeStateSynced(state)), Rx.tap(() => logger.info('Sync complete')), Rx.tap((state: FacadeState) => { const shieldedBalances = state.shielded.balances || {}; const unshieldedBalances = state.unshielded.balances || {}; const dustBalances = state.dust.balance(new Date(Date.now())) || 0n; logger.info( `Wallet balances after sync - Shielded: ${JSON.stringify(shieldedBalances)}, Unshielded: ${JSON.stringify(unshieldedBalances)}, Dust: ${dustBalances}`, ); }), ), ); }; ``` The `isFacadeStateSynced` helper centralizes the three-way progress check (shielded, unshielded, dust) so is reusable by `waitForUnshieldedFunds`. The DUST balance is read via `state.dust.balance(...)` — the older `walletBalance(...)` API is removed in `@midnight-ntwrk/wallet-sdk` 1.0. ### Wait for unshielded funds[​](#wait-for-unshielded-funds "Direct link to Wait for unshielded funds") Before deploying contracts or submitting transactions, the wallet needs unshielded tNIGHT tokens to generate DUST for paying network fees. This function ensures sufficient funds are available, optionally requesting tokens from the faucet for testing. Add the funding function: bboard-cli/src/wallet-utils.ts ``` export const waitForUnshieldedFunds = async ( logger: Logger, wallet: WalletFacade, env: EnvironmentConfiguration, tokenType: UnshieldedTokenType, fundFromFaucet = false, throttleTime = 2_000, ): Promise => { const initialState = await getInitialUnshieldedState(logger, wallet.unshielded); const unshieldedAddress = UnshieldedAddress.codec.encode(getNetworkId(), initialState.address); logger.info(`Using unshielded address: ${unshieldedAddress.toString()} waiting for funds...`); if (fundFromFaucet && env.faucet) { logger.info('Requesting tokens from faucet...'); await new FaucetClient(env.faucet, logger).requestTokens(unshieldedAddress.toString()); } const initialBalance = initialState.balances[tokenType.raw]; if (initialBalance === undefined || initialBalance === 0n) { logger.info(`Your wallet initial balance is: 0 (not yet initialized)`); logger.info(`Waiting to receive tokens...`); return Rx.firstValueFrom( wallet.state().pipe( Rx.tap((state: FacadeState) => { const balance = state.unshielded.balances[tokenType.raw] ?? 0n; logger.debug( `Wallet funds state emission: { synced=${isFacadeStateSynced(state)}, balance=${balance.toString()} }`, ); }), Rx.throttleTime(throttleTime), Rx.filter( (state: FacadeState) => isFacadeStateSynced(state) && (state.unshielded.balances[tokenType.raw] ?? 0n) > 0n, ), Rx.tap(() => logger.info('Sync complete')), Rx.tap((state: FacadeState) => { const shieldedBalances = state.shielded.balances || {}; const unshieldedBalances = state.unshielded.balances || {}; const dustBalances = state.dust.balance(new Date(Date.now())) || 0n; logger.info( `Wallet balances after sync - Shielded: ${JSON.stringify(shieldedBalances)}, Unshielded: ${JSON.stringify(unshieldedBalances)}, Dust: ${dustBalances}`, ); }), Rx.map((state: FacadeState) => state.unshielded), ), ); } return initialState; }; ``` `waitForUnshieldedFunds` waits until the wallet is fully synced **and** the unshielded balance for the requested token type is greater than zero — this avoids races where the wallet finishes its initial sync before the faucet credit is observed. ## Implement DUST generation[​](#implement-dust-generation "Direct link to Implement DUST generation") Create `bboard-cli/src/generate-dust.ts`: bboard-cli/src/generate-dust.ts ``` import { type WalletFacade } from '@midnight-ntwrk/wallet-sdk-facade'; import { createKeystore, UnshieldedWalletState } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet'; import { Logger } from 'pino'; import { HDWallet, Roles } from '@midnight-ntwrk/wallet-sdk-hd'; import { getNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import * as rx from 'rxjs'; export const getUnshieldedSeed = (seed: string): Uint8Array => { const seedBuffer = Buffer.from(seed, 'hex'); const hdWalletResult = HDWallet.fromSeed(seedBuffer); const { hdWallet } = hdWalletResult as { type: 'seedOk'; hdWallet: HDWallet; }; const derivationResult = hdWallet.selectAccount(0).selectRole(Roles.NightExternal).deriveKeyAt(0); if (derivationResult.type === 'keyOutOfBounds') { throw new Error('Key derivation out of bounds'); } return derivationResult.key; }; export const generateDust = async ( logger: Logger, walletSeed: string, unshieldedState: UnshieldedWalletState, walletFacade: WalletFacade, ) => { const dustState = await walletFacade.dust.waitForSyncedState(); const networkId = getNetworkId(); const unshieldedKeystore = createKeystore(getUnshieldedSeed(walletSeed), networkId); const utxos = unshieldedState.availableCoins.filter((coin) => !coin.meta.registeredForDustGeneration); if (utxos.length === 0) { logger.info('No unregistered UTXOs found for dust generation.'); return; } logger.info(`Generating dust with ${utxos.length} UTXOs...`); const recipe = await walletFacade.registerNightUtxosForDustGeneration( utxos, unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signData(payload), dustState.address, ); const transaction = await walletFacade.finalizeRecipe(recipe); const txId = await walletFacade.submitTransaction(transaction); const dustBalance = await rx.firstValueFrom( walletFacade.state().pipe( rx.filter((s) => s.dust.balance(new Date()) > 0n), rx.map((s) => s.dust.balance(new Date())), ), ); logger.info(`Dust generation transaction submitted with txId: ${txId}`); logger.info(`Receiver dust balance after generation: ${dustBalance}`); return txId; }; ``` DUST generation designates tNIGHT tokens to automatically produce DUST for transaction fees. The `getUnshieldedSeed` function derives an unshielded wallet key from the HD wallet seed using the `NightExternal` role. The `generateDust` function: 1. Filters out UTXOs that are already registered for DUST generation 2. Builds a registration recipe via `walletFacade.registerNightUtxosForDustGeneration()`, passing a callback that signs each intent with the unshielded keystore 3. Finalizes the recipe and submits the transaction to the network 4. Waits for the DUST balance observable to emit a non-zero value The wallet SDK 1.0 facade hides the intent construction and signature wiring that earlier wallet packages required, so the CLI just supplies a signing callback and the wallet does the rest. ## Implement wallet provider[​](#implement-wallet-provider "Direct link to Implement wallet provider") The wallet provider bridges the Wallet SDK to the Midnight.js contracts API, implementing the interfaces required by the contract deployment and transaction system. It manages cryptographic keys, transaction balancing, and wallet lifecycle operations. Create `bboard-cli/src/midnight-wallet-provider.ts` and add the following imports and class definition: bboard-cli/src/midnight-wallet-provider.ts ``` import { type CoinPublicKey, DustSecretKey, type EncPublicKey, type FinalizedTransaction, LedgerParameters, ZswapSecretKeys, } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { type MidnightProvider, type UnboundTransaction, type WalletProvider } from '@midnight-ntwrk/midnight-js-types'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import { type WalletFacade } from '@midnight-ntwrk/wallet-sdk-facade'; import type { Logger } from 'pino'; import { getInitialShieldedState } from './wallet-utils'; import { type DustWalletOptions, type EnvironmentConfiguration, FluentWalletBuilder } from '@midnight-ntwrk/testkit-js'; type UnshieldedKeystore = { getPublicKey(): unknown; signData(payload: Uint8Array): string; }; export class MidnightWalletProvider implements MidnightProvider, WalletProvider { logger: Logger; readonly env: EnvironmentConfiguration; readonly wallet: WalletFacade; readonly unshieldedKeystore: UnshieldedKeystore; readonly zswapSecretKeys: ZswapSecretKeys; readonly dustSecretKey: DustSecretKey; private constructor( logger: Logger, environmentConfiguration: EnvironmentConfiguration, wallet: WalletFacade, zswapSecretKeys: ZswapSecretKeys, dustSecretKey: DustSecretKey, unshieldedKeystore: UnshieldedKeystore, ) { this.logger = logger; this.env = environmentConfiguration; this.wallet = wallet; this.zswapSecretKeys = zswapSecretKeys; this.dustSecretKey = dustSecretKey; this.unshieldedKeystore = unshieldedKeystore; } ``` The class stores the wallet facade, the unshielded keystore (used to sign intent payloads when balancing transactions), cryptographic keys for shielded and DUST operations, and environment configuration. Importing the ledger types through the `@midnight-ntwrk/midnight-js-protocol/ledger` subpath replaces the standalone `@midnight-ntwrk/ledger-v8` package. ### Implement key provider methods[​](#implement-key-provider-methods "Direct link to Implement key provider methods") These methods expose the public keys needed for receiving shielded funds and decrypting transaction data: bboard-cli/src/midnight-wallet-provider.ts ``` getCoinPublicKey(): CoinPublicKey { return this.zswapSecretKeys.coinPublicKey; } getEncryptionPublicKey(): EncPublicKey { return this.zswapSecretKeys.encryptionPublicKey; } ``` The `getCoinPublicKey()` method returns the address for receiving shielded tokens, while `getEncryptionPublicKey()` provides the key for decrypting shielded transaction data sent to this wallet. ### Implement transaction methods[​](#implement-transaction-methods "Direct link to Implement transaction methods") These methods handle the transaction lifecycle from balancing through submission: bboard-cli/src/midnight-wallet-provider.ts ``` async balanceTx(tx: UnboundTransaction, ttl: Date = ttlOneHour()): Promise { const recipe = await this.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: this.zswapSecretKeys, dustSecretKey: this.dustSecretKey }, { ttl }, ); const signedRecipe = await this.wallet.signRecipe(recipe, (payload) => this.unshieldedKeystore.signData(payload)); return this.wallet.finalizeRecipe(signedRecipe); } submitTx(tx: FinalizedTransaction): Promise { return this.wallet.submitTransaction(tx); } ``` The `balanceTx()` method takes an unbound transaction (without inputs/outputs selected) and balances it by selecting appropriate UTXOs to cover fees and adding change outputs. It then asks the wallet to sign any unshielded intent payloads using the unshielded keystore before finalizing the recipe. The `submitTx()` method submits the finalized transaction to the network and returns the transaction hash. ### Implement lifecycle methods[​](#implement-lifecycle-methods "Direct link to Implement lifecycle methods") These methods control wallet startup and shutdown: bboard-cli/src/midnight-wallet-provider.ts ``` async start(): Promise { this.logger.info('Starting wallet...'); await this.wallet.start(this.zswapSecretKeys, this.dustSecretKey); } async stop(): Promise { return this.wallet.stop(); } ``` The `start()` method initializes the wallet with cryptographic keys and begins syncing with the blockchain. The `stop()` method gracefully shuts down the wallet and cleans up resources. Always call `stop()` before the application exits. ### Implement the build factory method[​](#implement-the-build-factory-method "Direct link to Implement the build factory method") The factory method creates and configures a wallet instance with proper DUST settings: bboard-cli/src/midnight-wallet-provider.ts ``` static async build(logger: Logger, env: EnvironmentConfiguration, seed?: string): Promise { const dustOptions: DustWalletOptions = { ledgerParams: LedgerParameters.initialParameters(), additionalFeeOverhead: env.walletNetworkId === 'undeployed' ? 500_000_000_000_000_000n : 1_000n, feeBlocksMargin: 5, }; const builder = FluentWalletBuilder.forEnvironment(env).withDustOptions(dustOptions); const buildResult = seed ? await builder.withSeed(seed).buildWithoutStarting() : await builder.withRandomSeed().buildWithoutStarting(); const { wallet, seeds, keystore } = buildResult as unknown as { wallet: WalletFacade; seeds: { masterSeed: string; shielded: Uint8Array; dust: Uint8Array }; keystore: UnshieldedKeystore; }; const initialState = await getInitialShieldedState(logger, wallet.shielded); logger.info( `Your wallet seed is: ${seeds.masterSeed} and your address is: ${initialState.address.coinPublicKeyString()}`, ); return new MidnightWalletProvider( logger, env, wallet, ZswapSecretKeys.fromSeed(seeds.shielded), DustSecretKey.fromSeed(seeds.dust), keystore, ); } } ``` The factory method configures DUST options with a network-dependent `additionalFeeOverhead`. The default value provided by `@midnight-ntwrk/testkit-js` (`500_000_000_000_000_000n`) is required on the `undeployed` (standalone) network — lower values can fail with `BalanceCheckOverspend` on the node side. On remote testnets, that overhead would require more DUST than the wallet typically holds, so the CLI overrides it to `1_000n`. If a seed is provided, the builder restores an existing wallet; otherwise it generates a new random seed. The builder result also exposes a pre-constructed `keystore` for signing unshielded intents. The method logs the seed and shielded address for user reference and stores all cryptographic material in the provider. ## Implement the main CLI logic[​](#implement-the-main-cli-logic "Direct link to Implement the main CLI logic") The main CLI module manages the entire bulletin board application, tying together wallet setup, contract interactions, and the interactive user interface. It manages the application lifecycle from environment startup through graceful shutdown. Create `bboard-cli/src/index.ts` and add the following imports: bboard-cli/src/index.ts ``` import { createInterface, type Interface } from 'node:readline/promises'; import { stdin as input, stdout as output } from 'node:process'; import { WebSocket } from 'ws'; import { BBoardAPI, type BBoardDerivedState, bboardPrivateStateKey, type BBoardProviders, type DeployedBBoardContract, type PrivateStateId, } from '../../api/src/index'; import { type WalletFacade } from '@midnight-ntwrk/wallet-sdk-facade'; import { ledger, type Ledger, State } from '../../contract/src/managed/bboard/contract/index.js'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { type Logger } from 'pino'; import { type Config, StandaloneConfig } from './config.js'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { type ContractAddress } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { assertIsContractAddress, toHex } from '@midnight-ntwrk/midnight-js-utils'; import { TestEnvironment } from '@midnight-ntwrk/testkit-js'; import { MidnightWalletProvider } from './midnight-wallet-provider'; import { randomBytes } from '../../api/src/utils'; import { unshieldedToken } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { syncWallet, waitForUnshieldedFunds } from './wallet-utils'; import { generateDust } from './generate-dust'; import { BBoardPrivateState } from '../../contract/src/witnesses.js'; // @ts-expect-error: It's needed to enable WebSocket usage through apollo globalThis.WebSocket = WebSocket; ``` The `globalThis.WebSocket` assignment configures the Node.js WebSocket implementation for browser-compatible APIs, enabling WebSocket connections to the Indexer and Node RPC services. ### Query ledger state[​](#query-ledger-state "Direct link to Query ledger state") This helper function retrieves the current public ledger state from a deployed contract: bboard-cli/src/index.ts ``` export const getBBoardLedgerState = async ( providers: BBoardProviders, contractAddress: ContractAddress, ): Promise => { assertIsContractAddress(contractAddress); const contractState = await providers.publicDataProvider.queryContractState(contractAddress); return contractState != null ? ledger(contractState.data) : null; }; ``` ### Deploy or join contract menu[​](#deploy-or-join-contract-menu "Direct link to Deploy or join contract menu") This function presents a menu allowing users to deploy a new bulletin board or connect to an existing one: bboard-cli/src/index.ts ``` const DEPLOY_OR_JOIN_QUESTION = ` You can do one of the following: 1. Deploy a new bulletin board contract 2. Join an existing bulletin board contract 3. Exit Which would you like to do? `; const deployOrJoin = async (providers: BBoardProviders, rli: Interface, logger: Logger): Promise => { let api: BBoardAPI | null = null; while (true) { const choice = await rli.question(DEPLOY_OR_JOIN_QUESTION); switch (choice) { case '1': api = await BBoardAPI.deploy(providers, logger); logger.info(`Deployed contract at address: ${api.deployedContractAddress}`); return api; case '2': api = await BBoardAPI.join(providers, await rli.question('What is the contract address (in hex)? '), logger); logger.info(`Joined contract at address: ${api.deployedContractAddress}`); return api; case '3': logger.info('Exiting...'); return null; default: logger.error(`Invalid choice: ${choice}`); } } }; ``` ### Display state helper functions[​](#display-state-helper-functions "Direct link to Display state helper functions") These functions display different views of the bulletin board state. Add them to visualize public ledger state, private state, and derived state: bboard-cli/src/index.ts ``` const displayLedgerState = async ( providers: BBoardProviders, deployedBBoardContract: DeployedBBoardContract, logger: Logger, ): Promise => { const contractAddress = deployedBBoardContract.deployTxData.public.contractAddress; const ledgerState = await getBBoardLedgerState(providers, contractAddress); if (ledgerState === null) { logger.info(`There is no bulletin board contract deployed at ${contractAddress}`); } else { const boardState = ledgerState.state === State.OCCUPIED ? 'occupied' : 'vacant'; const latestMessage = !ledgerState.message.is_some ? 'none' : ledgerState.message.value; logger.info(`Current state is: '${boardState}'`); logger.info(`Current message is: '${latestMessage}'`); logger.info(`Current sequence is: ${ledgerState.sequence}`); logger.info(`Current owner is: '${toHex(ledgerState.owner)}'`); } }; const displayPrivateState = async (providers: BBoardProviders, logger: Logger): Promise => { const privateState = await providers.privateStateProvider.get(bboardPrivateStateKey); if (privateState === null) { logger.info(`There is no existing bulletin board private state`); } else { logger.info(`Current secret key is: ${toHex(privateState.secretKey)}`); } }; const displayDerivedState = (ledgerState: BBoardDerivedState | undefined, logger: Logger) => { if (ledgerState === undefined) { logger.info(`No bulletin board state currently available`); } else { const boardState = ledgerState.state === State.OCCUPIED ? 'occupied' : 'vacant'; const latestMessage = ledgerState.state === State.OCCUPIED ? ledgerState.message : 'none'; logger.info(`Current state is: '${boardState}'`); logger.info(`Current message is: '${latestMessage}'`); logger.info(`Current sequence is: ${ledgerState.sequence}`); logger.info(`Current owner is: '${ledgerState.isOwner ? 'you' : 'not you'}'`); } }; ``` These display functions show: * **Ledger state**: Public on-chain data visible to all network participants * **Private state**: Local secret key that never appears on-chain * **Derived state**: Combines public and private data to compute ownership ### Main interaction loop[​](#main-interaction-loop "Direct link to Main interaction loop") The main loop provides the interactive menu for bulletin board operations: bboard-cli/src/index.ts ``` const MAIN_LOOP_QUESTION = ` You can do one of the following: 1. Post a message 2. Take down your message 3. Display the current ledger state (known by everyone) 4. Display the current private state (known only to this DApp instance) 5. Display the current derived state (known only to this DApp instance) 6. Exit Which would you like to do? `; const mainLoop = async (providers: BBoardProviders, rli: Interface, logger: Logger): Promise => { const bboardApi = await deployOrJoin(providers, rli, logger); if (bboardApi === null) { return; } let currentState: BBoardDerivedState | undefined; const stateObserver = { next: (state: BBoardDerivedState) => (currentState = state), }; const subscription = bboardApi.state$.subscribe(stateObserver); try { while (true) { const choice = await rli.question(MAIN_LOOP_QUESTION); try { switch (choice) { case '1': { const message = await rli.question(`What message do you want to post? `); await bboardApi.post(message); break; } case '2': await bboardApi.takeDown(); break; case '3': await displayLedgerState(providers, bboardApi.deployedContract, logger); break; case '4': await displayPrivateState(providers, logger); break; case '5': displayDerivedState(currentState, logger); break; case '6': logger.info('Exiting...'); return; default: logger.error(`Invalid choice: ${choice}`); } } catch (e) { logError(logger, e); logger.info('Returning to main menu...'); } } } finally { subscription.unsubscribe(); } }; ``` The loop first calls `deployOrJoin()` to initialize the contract connection. It subscribes to the reactive state observable to automatically receive updates whenever transactions modify the contract. Each menu action has its own `try`/`catch` so that a failed circuit invocation (for example, posting to an occupied board) logs the error and returns to the main menu instead of exiting. The outer `finally` block ensures the subscription is clean when the loop exits. ### Wallet setup menu[​](#wallet-setup-menu "Direct link to Wallet setup menu") This function handles wallet seed initialization. When the CLI runs against the local standalone network, the function skips the prompt and returns the genesis-mint wallet seed, which already holds tNIGHT and tDUST in the local node's genesis block. bboard-cli/src/index.ts ``` const GENESIS_MINT_WALLET_SEED = '0000000000000000000000000000000000000000000000000000000000000001'; const WALLET_LOOP_QUESTION = ` You can do one of the following: 1. Build a fresh wallet 2. Build wallet from a seed 3. Exit Which would you like to do? `; const buildWallet = async (config: Config, rli: Interface, logger: Logger): Promise => { if (config instanceof StandaloneConfig) { return GENESIS_MINT_WALLET_SEED; } while (true) { const choice = await rli.question(WALLET_LOOP_QUESTION); switch (choice) { case '1': return toHex(randomBytes(32)); case '2': return await rli.question('Enter your wallet seed: '); case '3': logger.info('Exiting...'); return undefined; default: logger.error(`Invalid choice: ${choice}`); } } }; ``` On remote networks, the function provides three options: * Generate a new wallet with a random seed * Restore your wallet from an existing seed * Exit the application ### Run function[​](#run-function "Direct link to Run function") The `run()` function coordinates the entire application lifecycle: bboard-cli/src/index.ts ``` export const run = async (config: Config, testEnv: TestEnvironment, logger: Logger): Promise => { const rli = createInterface({ input, output, terminal: true }); const providersToBeStopped: MidnightWalletProvider[] = []; try { const envConfiguration = await testEnv.start(); logger.info(`Environment started with configuration: ${JSON.stringify(envConfiguration)}`); const seed = await buildWallet(config, rli, logger); if (seed === undefined) { return; } const walletProvider = await MidnightWalletProvider.build(logger, envConfiguration, seed); providersToBeStopped.push(walletProvider); const walletFacade: WalletFacade = walletProvider.wallet; await walletProvider.start(); const unshieldedState = await waitForUnshieldedFunds(logger, walletFacade, envConfiguration, unshieldedToken()); const nightBalance = unshieldedState.balances[unshieldedToken().raw]; if (nightBalance === undefined) { logger.info('No funds received, exiting...'); return; } logger.info(`Your NIGHT wallet balance is: ${nightBalance}`); if (config.generateDust) { const dustGeneration = await generateDust(logger, seed, unshieldedState, walletFacade); if (dustGeneration) { logger.info(`Submitted dust generation registration transaction: ${dustGeneration}`); await syncWallet(logger, walletFacade); } } const zkConfigProvider = new NodeZkConfigProvider<'post' | 'takeDown'>(config.zkConfigPath); const providers: BBoardProviders = { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: config.privateStateStoreName, signingKeyStoreName: `${config.privateStateStoreName}-signing-keys`, privateStoragePasswordProvider: () => { return 'Bboard-Test-2026!'; }, accountId: seed, }), publicDataProvider: indexerPublicDataProvider(envConfiguration.indexer, envConfiguration.indexerWS), zkConfigProvider: zkConfigProvider, proofProvider: httpClientProofProvider(envConfiguration.proofServer, zkConfigProvider), walletProvider: walletProvider, midnightProvider: walletProvider, }; await mainLoop(providers, rli, logger); } catch (e) { logError(logger, e); logger.info('Exiting...'); } finally { try { rli.close(); rli.removeAllListeners(); } catch (e) { logError(logger, e); } finally { try { for (const wallet of providersToBeStopped) { logger.info('Stopping wallet...'); await wallet.stop(); } if (testEnv) { logger.info('Stopping test environment...'); await testEnv.shutdown(); } } catch (e) { logError(logger, e); } } } }; ``` The function executes the following workflow: 1. **Start environment**: Retrieves endpoint configuration for the network 2. **Build wallet**: Creates or restores a wallet from seed (or uses the genesis-mint seed on standalone) 3. **Wait for funds**: Ensures the wallet has tNIGHT tokens for fees 4. **Generate DUST**: Registers UTXOs for DUST generation (skipped on standalone, which already has DUST) 5. **Configure providers**: Sets up all six required providers (private state, public data, ZK config, proof, wallet, midnight). Midnight.js 4.x scopes private state per contract address — the `accountId` option (set to the wallet seed) keys the LevelDB store so multiple users on the same machine don't share state. 6. **Enter main loop**: Starts the interactive bulletin board session 7. **Cleanup**: Nested `finally` blocks guarantee cleanup of resources even if errors occur ### Error logging utility[​](#error-logging-utility "Direct link to Error logging utility") Add a helper function for logging errors: bboard-cli/src/index.ts ``` function logError(logger: Logger, e: unknown) { if (e instanceof Error) { logger.error(`Found error '${e.message}'`); logger.debug(`${e.stack}`); } else { logger.error(`Found error (unknown type)`); } } ``` This function checks if the error is an `Error` instance to access the message and stack trace, ensuring errors are always logged even when they don't follow standard JavaScript error patterns. ## Create the application entry points[​](#create-the-application-entry-points "Direct link to Create the application entry points") Each launcher creates the matching `Config` instance, initializes the logger, gets the test environment, and starts the CLI application. The launchers use top-level await for asynchronous initialization. * preprod * preview * standalone Create `bboard-cli/src/launcher/preprod.ts`: bboard-cli/src/launcher/preprod.ts ``` import { createLogger } from '../logger-utils.js'; import { run } from '../index.js'; import { PreprodRemoteConfig } from '../config.js'; const config = new PreprodRemoteConfig(); const logger = await createLogger(config.logDir); const testEnvironment = config.getEnvironment(logger); await run(config, testEnvironment, logger); ``` Create `bboard-cli/src/launcher/preview.ts`: bboard-cli/src/launcher/preview\.ts ``` import { createLogger } from '../logger-utils.js'; import { run } from '../index.js'; import { PreviewRemoteConfig } from '../config.js'; const config = new PreviewRemoteConfig(); const logger = await createLogger(config.logDir); const testEnvironment = config.getEnvironment(logger); await run(config, testEnvironment, logger); ``` Create `bboard-cli/src/launcher/standalone.ts`: bboard-cli/src/launcher/standalone.ts ``` import { createLogger } from '../logger-utils.js'; import { run } from '../index.js'; import { StandaloneConfig } from '../config.js'; const config = new StandaloneConfig(); const logger = await createLogger(config.logDir); const testEnvironment = config.getEnvironment(logger); await run(config, testEnvironment, logger); ``` info The `standalone` launcher connects to a local Midnight network running on your machine. For more information, see [Running a local network](/guides/networks-and-environments.md#running-a-local-network). ## Configure the proof server[​](#configure-the-proof-server "Direct link to Configure the proof server") Create `bboard-cli/proof-server-local.yml` for local development. This file exposes the proof server on a fixed host port so you can start it once and reuse it between CLI runs: bboard-cli/proof-server-local.yml ``` services: proof-server: image: midnightntwrk/proof-server:8.0.3 command: ['midnight-proof-server', '-v'] container_name: "proof-server-local" ports: - '6300:6300' ``` Also create `bboard-cli/proof-server.yml` for use by the testkit container manager. The testkit picks an ephemeral host port (`0:6300`) so multiple test runs don't conflict: bboard-cli/proof-server.yml ``` services: proof-server: image: midnightntwrk/proof-server:8.0.3 command: ['midnight-proof-server', '-v'] container_name: "proof-server_$TESTCONTAINERS_UID" ports: - '0:6300' ``` Start the long-lived local proof server before running the CLI: ``` docker compose -f proof-server-local.yml up -d ``` ## Next steps[​](#next-steps "Direct link to Next steps") You have now completed both implementation guides. Return to the [main CLI guide](/tutorials/bboard/bboard-cli.md#run-the-cli) to run the application and explore next steps. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Bulletin board contract This tutorial shows you how to build a privacy-preserving bulletin board smart contract on the Midnight blockchain. The bulletin board contract allows users to post and remove messages while maintaining privacy. Only the original poster can remove their message, and this is enforced through zero-knowledge (ZK) proofs without revealing the poster's identity on-chain. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin, ensure that you have: * **Compact toolchain installed**: For instructions, refer to the [install the toolchain](/getting-started/installation.md) guide * **Proof server running**: For instructions, refer to the [run the proof server](/getting-started/installation.md#set-up-the-proof-server) guide * **Node.js version 24+**: Verify with `node --version` ## Set up the project[​](#set-up-the-project "Direct link to Set up the project") Create the project root and contract directories: ``` mkdir -p example-bboard/contract/src cd example-bboard/contract ``` Your directory structure should now look like this: ``` example-bboard/ └── contract/ └── src/ ``` ## Write the smart contract[​](#write-the-smart-contract "Direct link to Write the smart contract") This section explains the process of writing the smart contract and understanding the key concepts. ### Create the contract file[​](#create-the-contract-file "Direct link to Create the contract file") Create `contract/src/bboard.compact`: ``` touch src/bboard.compact ``` Open this file in your code editor. ### Add the language version[​](#add-the-language-version "Direct link to Add the language version") The `pragma language_version` directive specifies which version of Compact your contract uses: ``` pragma language_version 0.23; ``` This directive: * Locks your contract to a minimum Compact version * Prevents breaking changes in future compiler versions ### Import the standard library[​](#import-the-standard-library "Direct link to Import the standard library") Import Compact's standard library for built-in types and functions: ``` pragma language_version 0.23; import CompactStandardLibrary; ``` The `CompactStandardLibrary` provides access to built-in types and functions in Compact, such as `Maybe` for optional values, `Counter` for tracking sequences, `persistentHash` for cryptographic commitments, `some` and `none` constructors for Maybe values. note To learn more about what's available in the standard library, see the [Compact standard library](/compact/standard-library.md) reference. ### Define the board state enum[​](#define-the-board-state-enum "Direct link to Define the board state enum") The bulletin board has two possible states. Define an enumeration type to represent them: ``` pragma language_version 0.23; import CompactStandardLibrary; export enum State { VACANT, OCCUPIED } ``` This enumeration: * `export` makes the enum accessible from TypeScript * `State` is the enum type name * `VACANT` represents an empty board (value 0) * `OCCUPIED` represents a board with a message (value 1) ### Define the ledger state[​](#define-the-ledger-state "Direct link to Define the ledger state") The ledger represents the public, on-chain state of your contract. For the bulletin board, you need four pieces of public information: ``` pragma language_version 0.23; import CompactStandardLibrary; export enum State { VACANT, OCCUPIED } export ledger state: State; export ledger message: Maybe>; export ledger sequence: Counter; export ledger owner: Bytes<32>; ``` Each ledger field serves a specific purpose: * `state`: Tracks whether the board is vacant or occupied * `message`: Stores the current message as an optional opaque string * `sequence`: A counter that increments each time a message is taken down, creating unique commitments for each posting cycle and preventing replay attacks * `owner`: Stores a cryptographic commitment to the poster's identity as a 32-byte hash The `Maybe` type indicates optional values. A message is `none` when the board is vacant and `some(value)` when occupied. The `Opaque<'string'>` type represents string data whose internal structure is irrelevant to the contract. ### Create the constructor[​](#create-the-constructor "Direct link to Create the constructor") The constructor initializes the ledger state when the contract is deployed: ``` // ... previous code ... constructor() { state = State.VACANT; message = none>(); sequence.increment(1); } ``` This constructor makes deliberate choices about what to explicitly initialize versus what to leave as default: * **`state = State.VACANT`**: Explicitly set to make the contract independent of enum ordering * **`message = none>()`**: Explicitly set to decouple from the standard library's `Maybe` default implementation * **`sequence.increment(1)`**: Increments from 0 to 1, so posts start at sequence number 1 * **`owner`**: Uninitialized, using the language-guaranteed default of 32 zero bytes The pattern: explicitly initialize values that depend on library or enum definitions, but rely on language-defined defaults when they're guaranteed by the specification. Constructor initialization Fields not explicitly initialized in the constructor receive default values for their type as defined by the Compact language specification. ### Declare the witness function[​](#declare-the-witness-function "Direct link to Declare the witness function") Before defining the circuits, declare a witness function: ``` // ... previous code ... witness localSecretKey(): Bytes<32>; ``` This declaration: * `witness` marks this as a function implemented in TypeScript or JavaScript that performs arbitrary computation. * `localSecretKey` returns a 32-byte value of the user's secret key. * The return value is private by default and doesn't appear on-chain or in public ledger state. Witnesses enable privacy-preserving computation. They can perform any computation, such as accessing private state or generating values, and return results that circuits use for proof generation. ### Create the post circuit[​](#create-the-post-circuit "Direct link to Create the post circuit") The `post` circuit allows users to post messages to the vacant board: ``` // ... previous code ... export circuit post(newMessage: Opaque<'string'>): [] { assert(state == State.VACANT, "Attempted to post to an occupied board"); owner = disclose(publicKey(localSecretKey(), sequence as Field as Bytes<32>)); message = disclose(some>(newMessage)); state = State.OCCUPIED; } ``` This circuit performs several operations: * **Validate board state**: `assert(state == State.VACANT, ...)` ensures posting only happens when the board is vacant. * **Generate commitment**: Calls `publicKey()` helper circuit to create a cryptographic commitment from the secret key and current sequence number. This is what allows only the original poster to take down their message. * **Disclose**: Wraps the commitment in `disclose()` to tell the compiler this value is safe to reveal on-chain. * **Store message**: Sets `message` to `some(newMessage)` and wraps it in `disclose()` to explicitly reveal it. * **Update state**: Changes `state = State.OCCUPIED` to mark the board as occupied. The `disclose` keyword is critical for security. By default, Compact prevents computed values from being assigned to public ledger fields. You *must* explicitly wrap values in `disclose()` to mark them as safe to reveal on-chain, ensuring you don't accidentally leak private data. The sequence counter is cast twice (`sequence as Field as Bytes<32>`) because you cannot directly cast from `Counter` to `Bytes<32>`. The intermediate `Field` cast provides a compatible type path. ### Create the takeDown circuit[​](#create-the-takedown-circuit "Direct link to Create the takeDown circuit") The `takeDown` circuit allows users to remove their own messages: ``` // ... previous code ... export circuit takeDown(): Opaque<'string'> { assert(state == State.OCCUPIED, "Attempted to take down post from an empty board"); assert(owner == publicKey(localSecretKey(), sequence as Field as Bytes<32>), "Attempted to take down post, but not the current owner"); const formerMsg = message.value; state = State.VACANT; sequence.increment(1); message = none>(); return formerMsg; } ``` This circuit performs several operations: * **Validate board state**: Ensures the board is occupied before attempting removal * **Regenerate commitment**: Calls `publicKey()` with the current user's secret key and sequence number * **Verify ownership**: Compares the regenerated commitment to the stored `owner` value * **Extract message**: Uses `message.value` to access the inner value from the `Maybe` type * **Update state**: Changes `state` to `State.VACANT` * **Increment sequence**: Advances the counter so the next post uses sequence number 2, 3, and so on * **Clear message**: Resets `message` to `none` * **Return message**: Returns the taken-down message to the caller The second `assert` is where privacy meets access control. The user proves they can regenerate the stored commitment without revealing their secret key. The ZK proof validates this assertion without exposing the private data. Note that `message` is cleared after extracting its value. This ensures the board is ready for the next post. ### Create the publicKey helper circuit[​](#create-the-publickey-helper-circuit "Direct link to Create the publicKey helper circuit") The `publicKey` circuit generates a cryptographic commitment to the poster's identity: ``` // ... previous code ... export circuit publicKey(sk: Bytes<32>, sequence: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "bboard:pk:"), sequence, sk]); } ``` This helper circuit: * Uses `pad(32, "bboard:pk:")` to create a domain separator * Creates a vector of three 32-byte values to hash together * Uses `persistentHash` from the standard library, which implements SHA-256 hashing * Takes an input value (`sk`) and sequence number as parameters * Returns a 32-byte cryptographic hash The commitment has critical properties: * **Domain separation**: The `"bboard:pk:"` prefix prevents hash collisions with other uses of the secret key * **One-way**: SHA-256 is cryptographically non-reversible, meaning you cannot discover the input from the hash output * **Deterministic**: The same inputs always produce the same output * **Unique per post**: The sequence number ensures each post has a different commitment The domain separator is a security best practice. It ensures that hashes generated for the bulletin board cannot be confused with hashes generated for other purposes, even if they use the same secret key. Your complete bulletin board contract should now look like this: ``` pragma language_version 0.23; import CompactStandardLibrary; export enum State { VACANT, OCCUPIED } export ledger state: State; export ledger message: Maybe>; export ledger sequence: Counter; export ledger owner: Bytes<32>; constructor() { state = State.VACANT; message = none>(); sequence.increment(1); } witness localSecretKey(): Bytes<32>; export circuit post(newMessage: Opaque<'string'>): [] { assert(state == State.VACANT, "Attempted to post to an occupied board"); owner = disclose(publicKey(localSecretKey(), sequence as Field as Bytes<32>)); message = disclose(some>(newMessage)); state = State.OCCUPIED; } export circuit takeDown(): Opaque<'string'> { assert(state == State.OCCUPIED, "Attempted to take down post from an empty board"); assert(owner == publicKey(localSecretKey(), sequence as Field as Bytes<32>), "Attempted to take down post, but not the current owner"); const formerMsg = message.value; state = State.VACANT; sequence.increment(1); message = none>(); return formerMsg; } export circuit publicKey(sk: Bytes<32>, sequence: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "bboard:pk:"), sequence, sk]); } ``` ## Compile the contract[​](#compile-the-contract "Direct link to Compile the contract") Compilation transforms your Compact code into ZK circuits and generates TypeScript APIs for interacting with the contract. ### Run the compiler[​](#run-the-compiler "Direct link to Run the compiler") From the `contract` directory, compile the contract: ``` compact compile src/bboard.compact src/managed/bboard ``` This command has three parts: * `compact compile` invokes the Compact compiler. * `src/bboard.compact` specifies the source file to compile. * `src/managed/bboard` specifies the output directory for generated files. You should see output similar to: ``` Compiling 2 circuits: circuit "post" (k=14, rows=10070) circuit "takeDown" (k=14, rows=10087) Overall progress [====================] 2/2 ``` ### Examine the generated files[​](#examine-the-generated-files "Direct link to Examine the generated files") After compilation, the `src/managed/bboard` directory contains: ``` src/managed/bboard/ ├── contract/ │ ├── index.d.ts # Type definitions │ ├── index.js # JavaScript implementation │ └── index.js.map ├── keys/ # Cryptographic keys │ ├── post.prover │ ├── post.verifier │ ├── takeDown.prover │ ├── takeDown.verifier ├── zkir/ # ZK Intermediate Representation │ ├── post.zkir │ ├── post.bzkir │ ├── takeDown.zkir │ ├── takeDown.bzkir └── compiler/ # Compiler metadata └── contract-info.json ``` Each directory serves the following purpose: * `contract/`: Contains the generated TypeScript API and JavaScript implementation that your DApp uses to interact with the contract * `keys/`: Cryptographic keys used for generating and verifying ZK proofs for each circuit * `zkir/`: Intermediate circuit representations used by the proof server * `compiler/`: Metadata about circuits, types, and structure in JSON format ## Understand the generated API[​](#understand-the-generated-api "Direct link to Understand the generated API") The Compact compiler generates TypeScript definitions that correspond to your contract code. Open `managed/bboard/contract/index.d.ts` to examine the generated types. ### State type[​](#state-type "Direct link to State type") The `State` enum from your Compact code becomes a TypeScript enum: ``` export enum State { VACANT = 0, OCCUPIED = 1 } ``` This allows TypeScript code to reference board states type-safely using `State.VACANT` and `State.OCCUPIED`. ### Circuit types[​](#circuit-types "Direct link to Circuit types") The `Circuits` type defines the callable functions: ``` export type Circuits = { post( context: __compactRuntime.CircuitContext, newMessage: string ): __compactRuntime.CircuitResults; takeDown( context: __compactRuntime.CircuitContext ): __compactRuntime.CircuitResults; publicKey( context: __compactRuntime.CircuitContext, sk: Uint8Array, sequence: Uint8Array ): __compactRuntime.CircuitResults; } ``` Each circuit method: * Corresponds to an exported circuit in your Compact code * Takes a `CircuitContext` that provides access to ledger state and witness functions * Accepts parameters matching the Compact circuit parameters * Returns `CircuitResults` containing the `ProofData`, which is sent to the proof server to generate the ZK proof * Uses appropriate JavaScript types (`string`, `Uint8Array`) for Compact types ### Ledger types[​](#ledger-types "Direct link to Ledger types") The `Ledger` type defines the public state structure: ``` export type Ledger = { readonly state: State; readonly message: { is_some: boolean, value: string }; readonly sequence: bigint; readonly owner: Uint8Array; } ``` Each field: * Corresponds to a ledger declaration in your Compact code * Uses JavaScript types: `State` enum, `string`, `bigint`, `Uint8Array` * Represents `Maybe` types as objects with `is_some: boolean` and `value` properties * Is marked as `readonly`, meaning state modifications can only happen through circuit calls tip To use the `Maybe` type annotation in your TypeScript code for the `message` ledger field, export it from your Compact contract: ``` export { Maybe }; ``` ### Witness types[​](#witness-types "Direct link to Witness types") The `Witnesses` type defines the required witness implementations: ``` export type Witnesses = { localSecretKey(context: __compactRuntime.WitnessContext): [PS, Uint8Array]; } ``` This type: * Corresponds to the `witness localSecretKey()` declaration in your Compact code * Takes a `WitnessContext` providing access to ledger state, private state, and contract address * Returns a tuple `[PS, Uint8Array]` containing the updated private state and the 32-byte secret key * Must be implemented by your DApp to provide private data during circuit execution ### Contract type[​](#contract-type "Direct link to Contract type") The `Contract` class ties everything together: ``` export declare class Contract = Witnesses> { witnesses: W; circuits: Circuits; impureCircuits: ImpureCircuits; constructor(witnesses: W); initialState(context: __compactRuntime.ConstructorContext): __compactRuntime.ConstructorResult; } ``` The `Contract` class provides the main interface for interacting with your compiled contract: * Uses type parameters `PS` for private state and `W` for witnesses * Provides `circuits` for pure circuit functions * Provides `impureCircuits` for circuits that interact with witnesses * Accepts witness implementations in the constructor * Initializes contract state through `initialState`, which calls your constructor ## Implement witness functions[​](#implement-witness-functions "Direct link to Implement witness functions") The bulletin board contract requires a witness implementation to provide access to the user's secret key during circuit execution. ### Create the witnesses file[​](#create-the-witnesses-file "Direct link to Create the witnesses file") Create `contract/src/witnesses.ts`: ``` import { Ledger } from "./managed/bboard/contract/index.js"; import { WitnessContext } from "@midnight-ntwrk/midnight-js-protocol/compact-runtime"; export type BBoardPrivateState = { readonly secretKey: Uint8Array; }; export const createBBoardPrivateState = (secretKey: Uint8Array) => ({ secretKey, }); export const witnesses = { localSecretKey: ({ privateState, }: WitnessContext): [ BBoardPrivateState, Uint8Array, ] => [privateState, privateState.secretKey], }; ``` This code defines: * `BBoardPrivateState`: The private state type with a `secretKey` field of type `Uint8Array`. * `createBBoardPrivateState()`: Helper function to initialize private state with a secret key. * `witnesses.localSecretKey`: Implementation that receives a `WitnessContext` and returns a tuple of `[BBoardPrivateState, Uint8Array]`. The function extracts the `privateState` from the context and returns both the unchanged private state and the secret key. The witness function receives a `WitnessContext` parameter that provides access to the ledger state, private state, and contract address. The Compact runtime passes this context automatically during circuit execution. Compact Runtime API The `WitnessContext` type is part of the Compact Runtime API. For detailed information about witness contexts and other runtime types, refer to the [Compact runtime API documentation](/api-reference/compact-runtime.md). ### Create the index file[​](#create-the-index-file "Direct link to Create the index file") Create `contract/src/index.ts` to re-export the contract API: ``` import { CompiledContract } from "@midnight-ntwrk/midnight-js-protocol/compact-js"; export * from "./managed/bboard/contract/index.js"; export * from "./witnesses"; import * as CompiledBBoardContract from "./managed/bboard/contract/index.js"; import * as Witnesses from "./witnesses"; export const CompiledBBoardContractContract = CompiledContract.make< CompiledBBoardContract.Contract >("BBoard", CompiledBBoardContract.Contract).pipe( CompiledContract.withWitnesses(Witnesses.witnesses), CompiledContract.withCompiledFileAssets("./managed/bboard"), ); ``` This file serves as the main entry point for the bulletin board contract. It re-exports all types and functions from the generated contract code and witness implementations, providing a single import point for consuming applications. ### Initialize the npm package[​](#initialize-the-npm-package "Direct link to Initialize the npm package") The contract needs a `package.json` file to manage dependencies, define build scripts, and package the contract for use in DApps. This makes it easy to compile, build, and distribute the contract as a reusable module. Create a `package.json` file in the `contract` directory: ``` npm init -y ``` This generates a basic `package.json` file with default values, which you'll customize in a later step to add compilation scripts and package metadata. ### Configure TypeScript[​](#configure-typescript "Direct link to Configure TypeScript") Create a `tsconfig.json` file in the `contract` directory: ``` { "include": ["src/**/*.ts"], "compilerOptions": { "rootDir": "src", "outDir": "dist", "declaration": true, "lib": ["ESNext"], "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "allowJs": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "strict": true, "isolatedModules": true, "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true } } ``` The key configuration options are: * `target` and `module`: Set to ES2022 for modern JavaScript features * `declaration`: Generates `.d.ts` type definition files for TypeScript consumers * `outDir`: Compiled JavaScript files go to `./dist` * `rootDir`: Source TypeScript files are in `./src` * `moduleResolution`: Set to `Bundler` to resolve subpath imports from the Midnight.js packages * `strict`: Enables strict type checking for better code quality Create a `tsconfig.build.json` file in the same directory to exclude test files from the production build: ``` { "extends": "./tsconfig.json", "exclude": ["src/test/**/*.ts"], "compilerOptions": {} } ``` ### Add build scripts[​](#add-build-scripts "Direct link to Add build scripts") Update your `contract/package.json` to include build scripts: ``` { "name": "@midnight-ntwrk/bboard-contract", "type": "module", "main": "./dist/index.js", "module": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "require": "./dist/index.js", "import": "./dist/index.js", "default": "./dist/index.js" } }, "scripts": { "build": "rm -rf dist && tsc --project tsconfig.build.json && cp -Rf ./src/managed ./dist/managed && cp ./src/bboard.compact ./dist", "compact": "compact compile src/bboard.compact ./src/managed/bboard", "typecheck": "tsc -p tsconfig.json --noEmit" }, "devDependencies": { "typescript": "^5.9.3" } } ``` Each script serves the following purpose: * `compact`: Runs the Compact compiler to generate circuits and TypeScript API * `typecheck`: Verifies TypeScript types without emitting JavaScript output * `build`: Compiles TypeScript using `tsconfig.build.json` and copies the generated `managed/` directory and contract source into `dist/` ### Build the contract[​](#build-the-contract "Direct link to Build the contract") The `compact` and `build` scripts run independently so that you can re-run the TypeScript build without recompiling the Compact contract: ``` npm install npm run compact npm run build ``` These commands: 1. Install dependencies (TypeScript compiler) 2. Compile the Compact contract to circuits and the generated TypeScript API under `src/managed/bboard/` 3. Compile TypeScript to JavaScript using `tsconfig.build.json`, which excludes the `src/test` directory 4. Copy the `managed/` directory and the source `bboard.compact` file into `dist/` If successful, you will have: * `src/managed/bboard/`: Generated contract code from the Compact compiler * `dist/`: Compiled JavaScript and type definitions * `dist/managed/bboard/`: Generated contract code copied for packaging * `dist/bboard.compact`: The source contract file ## Next steps[​](#next-steps "Direct link to Next steps") Now that you've built and compiled the bulletin board contract: * **Build the CLI**: Continue to [build the bulletin board CLI](/tutorials/bboard/bboard-cli.md) to create an interactive command-line interface * **Test the contract**: Add unit tests in `src/test/` to verify circuit behavior and commitment generation --- > For the complete documentation index, see [llms.txt](/llms.txt) # Battleship tutorial Write a Compact contract that models a game as a state machine with public and private data, then build a test suite to verify it on a local devnet. [✦](/tutorials/bship/smart-contract.md) ### [Battleship contract](/tutorials/bship/smart-contract.md) [Build a state-machine contract with explicit state management, private data verification, List operations, and intermediate witnesses.](/tutorials/bship/smart-contract.md) [Write the contract→](/tutorials/bship/smart-contract.md) [✦](/tutorials/bship/test-suite.md) ### [Battleship tests](/tutorials/bship/test-suite.md) [Write MidnightJS tests that verify contract behavior on a local devnet, covering both valid and adversarial interactions.](/tutorials/bship/test-suite.md) [Write the tests→](/tutorials/bship/test-suite.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Battleship contract The Battleship tutorial is an intermediate level demonstration of the following features: * Compact contracts as state machines * Explicit state management * Private state data (setting, getting, updating, verifying, maliciously manipulating) * Operations on a `List` * Intermediate Witness functionality * Frontend tests with MidnightJS It has two main components: 1. Compact contract 2. Test script This tutorial demonstrates writing safe and secure Compact contracts with a mix of public and private data while verifying the operation of the contract with MidnightJS in a local devnet test script. It is best consumed by writing each code block by hand rather than copying and pasting code. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin this tutorial, ensure you have: * [Installed the toolchain](/getting-started/installation.md) * Node.js v22+ * Completed a beginner tutorial (optional) ## Problem analysis[​](#problem-analysis "Direct link to Problem analysis") Battleship is a guessing game for two players. It is played on two individual grids with each player's ships marked on their grid. The location of a player's ships are hidden from the other player. Players alternate turns calling "shots" at the other player's ships with the objective of "sinking" those ships. The first player to correctly hit all of the opposing ships wins. Battleship is centered around the idea of private data (ships) and public data (shots, hits) being used in combination. The board game version comes with significant trust assumptions that make it vulnerable to malicious actors. A player could simply claim a MISS when it was in fact a HIT. They could move their ship in the middle of the game (change private state), or even look around the board at the location of the opposing player's ships to ensure a victory. Using blockchain, the rules of this game can be enforced by moving those trust assumptions on-chain. With Midnight, private data can be hidden in plain sight while verifying its validity in the private state of a given player. ## Program design[​](#program-design "Direct link to Program design") For the purposes of simplifying the code associated with this tutorial, it implements a more basic version of the game. The main differences in this version will be: * Using a single number line instead of a grid * A single number on the line represents the position of a ship * Reduce the number of HITS required to win to two ### Operational steps[​](#operational-steps "Direct link to Operational steps") First, consider the operational components of the contract. What does the contract need to do? In order, it needs to: 1. Deploy the contract and allow player 1 to set their board 2. Allow player 2 to join the game and set their board 3. Player 1 shoots at board 2 4. Player 2 checks their board for a HIT or MISS 5. Player 2 shoots at board 1 6. Player 1 checks their board for HIT or MISS 7. Steps 3-6 continue until `board1Hits == 2 || board2Hits == 2` 8. Assign a winner ### Data: public vs private[​](#data-public-vs-private "Direct link to Data: public vs private") One of the more challenging ideas in developing Midnight DApps is the mix of private and public data. Adhering to best-practice strategies is recommended to ensure that data is handled as intended and only made public when necessary. In this game, both players have the same needs in reference to their data: | Public data | Private data | | ----------- | ------------ | | DApp ID | Address | | Hits | Ships | | Shots | Password | | States | HIT/MISS | In order to enforce the rules of the game and ensure that neither player cheats, they provide a commitment to their ship locations and publish a hash of that commitment to the ledger. *All ledger data is public*, so care must be taken to manage private state data (ships) on-chain so that it can later be verified as unchanged. ### Cheating assertions[​](#cheating-assertions "Direct link to Cheating assertions") The most common way that players cheat in Battleship is to claim a MISS when a particular "shot" was in fact a HIT. In this DApp, this means that a player attempts to maliciously manipulate their private state data. Verifcation checks can ensure the validity of a `ShotState` to check that a MISS was in fact a MISS. There is no need to trust Alice or Bob, that trust can be enforced through Compact code. Specific tests in the frontend test suite will attempt to exploit the contract in this way and verify that these will be rejected by the verification checks. The contract will handle several cheating vectors such as: * Double shots * Repeating a previous HIT to increment `hitCount` * Claiming a MISS when it was in fact a HIT * Changing ship locations mid-game Smart contract developers *must be diligent in writing defensive programs.* The public and permissionless nature of blockchain means that contracts are accessible to anyone with a node command line. Intentionally guarding circuits through access control, input validation and explicit state management will create more secure programs than those without these considerations. ### State machines[​](#state-machines "Direct link to State machines") Compact contracts are best thought of as state machines, so the next consideration is for the states of the contract. Custom states are needed for the following: * BoardState * ShotState * WinState * TurnState By managing each of these states explicitly and pairing them with `assert` statements, access can be restricted to only the specific function needing to be available at any given state. For example, using `TurnState`, the contract can ensure that a player shoots only when it is their turn. Turn order:
`PLAYER_1_SHOOT` → `PLAYER_2_CHECK` → `PLAYER_2_SHOOT` → `PLAYER_1_CHECK` → repeat The `PLAYER_1_SHOOT` circuit will be available first, and access to others will be blocked. After a successful state transition, `PLAYER_2_CHECK` will be "unlocked" and access to `PLAYER_1_SHOOT` will be unavailable. ## Compact tutorial[​](#compact-tutorial "Direct link to Compact tutorial") Compact provides the right mix of public and private data management to enable the Battleship implementation elegantly. ### Setup[​](#setup "Direct link to Setup") Start with Compact code setup: ``` mkdir example-battleship && cd example-battleship mkdir contract && cd contract touch battleship.compact ``` Open the project in your text editor and open `battleship.compact`. The first thing to do is declare the language version and imports: ``` pragma language_version 0.23; import CompactStandardLibrary; ``` Then declare the custom states: ``` export enum BoardState { UNSET, SET } export enum ShotState { MISS, HIT } export enum TurnState { PLAYER_1_SHOOT, PLAYER_1_CHECK, PLAYER_2_SHOOT, PLAYER_2_CHECK, } export enum WinState { CONTINUE_PLAY, PLAYER_1_WINS, PLAYER_2_WINS } ``` Next, declare the *public* ledger fields: ``` export ledger player1: Bytes<32>; export ledger player2: Bytes<32>; export ledger turn: TurnState; export ledger board1: Set>;// linear board shape export ledger board2: Set>;// hashed storage of ship locations export ledger board1State: BoardState; export ledger board2State: BoardState; export ledger player1Shot: List>;// current shot export ledger player2Shot: List>; export ledger board1Hits: Set>;// previous hits stored for later assertions export ledger board2Hits: Set>; export ledger winState: WinState; export ledger board1HitCount: Counter; export ledger board2HitCount: Counter; ``` All ledger fields are publicly visible. In order to hide private data in these fields, Compact provides hashing functions. Implementation of this circuit will come later, for now, just be aware of the strategy needed to hide this data publicly. ### Witness declaration[​](#witness-declaration "Direct link to Witness declaration") To set and access private state data, declare the `witness` functions: ``` witness localSk(): Bytes<32>; witness localSetBoard(_x1: Uint<8>, _x2: Uint<8>): BoardState; witness localCheckBoard(x: Uint<8>): ShotState; ``` Witness functions are declared in Compact, but their implementation is left to the Typescript frontend. *Never trust data from a witness* function without strictly verifying it first. Each Typescript instance has the ability to manipulate these functions and therefore a Compact contract can never assume that a witness function was implemented as expected. Verify this data rigorously through `assert` statements. ### Constructor[​](#constructor "Direct link to Constructor") Next, set up the contructor that executes on contract deployment. For simplicity, assume that `player1` (Alice) is deploying the contract so that a few operations can be bundled together. First validate the inputs are within the boundaries of the game: ``` constructor(_x1: Uint<8>, _x2: Uint<8>) { // input verification checks assert(_x1 != _x2, "Cannot use the same number twice"); assert(_x1 > 0 && _x2 > 0, "No zero index, board starts at 1"); assert(_x1 <= 20 && _x2 <= 20, "Out of bounds, please keep ships on the board"); }// end of constructor ``` The use of an underscore(\_x1) prefixing an identifier is a good practice in cryptography to track management of private data. This does nothing for the compiler, but it helps you as a developer better track information needing to remain private. Then assign a DApp specific public key for `player1`: ``` // user id and assignment const _sk = localSk(); const pubKey = getDappPubKey(_sk); player1 = disclose(pubKey); }// end of constructor ``` This pattern accesses a secret key from the player's private state, hashing that with a domain seperator so that user interactions can be traced inside this DApp, but not outside of it. The `getDappPublicKey` circuit will be written later. In order to store private state data (\_x1, \_x2) publicly, that data needs to be hashed: ``` // hash the inputs to verify them later, user needs to provide the same value and _sk const hash1 = commitBoardSpace(_x1 as Bytes<32>, _sk); board1.insert(hash1); const hash2 = commitBoardSpace(_x2 as Bytes<32>, _sk); board1.insert(hash2); }// end of constructor ``` Storing hashes computed in this way makes it impossible to derive the private state data underneath, unless an attacker also gains access to a players private state. These are one-way, deterministic functions, so they can never be revealed. To verify the ship locations have not changed, the player is asked to present the same data later in the program. The data is hashed again and the hashes compared. If the hashes don't match, the player provided different data. Now, ask the player to set these ship locations on their local board: ``` // disclose only what you need (localBoardState); const localBoardState = localSetBoard(_x1, _x2); assert(localBoardState == BoardState.SET, "Please update the state of board1 to SET"); board1State = disclose(localBoardState); }// end of constructor ``` `localSetBoardState` is a witness function, so do not trust its return value is as expected, this must be enforced through an `assert`. The assumption is that the board will be set when this off-chain function completes, so `assert` this specifically. Ship locations can be verified against the original when the player is asked to check their board. The final operations of the constructor are public state assignments: ``` // setting initial states board2State = BoardState.UNSET; winState = WinState.CONTINUE_PLAY; }// end of constructor ``` Setting these publicly enables their use in `assert`s to verify the states are as expected before allowing access to specific functions. ### Bob joins the game[​](#bob-joins-the-game "Direct link to Bob joins the game") The next thing that needs to happen to advance the game, according to the program design, is `player2` (Bob) accepts the game and sets their ship locations. The `acceptGame` circuit takes in the two ships as arguments (privately) and assigns an ID for Bob that is specific to this DApp. A verification check is also added to verify that `player1` is not attempting to play against themselves: ``` export circuit acceptGame(_x1: Uint<8>, _x2: Uint<8>): [] { // caller verification checks const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player1 != disclose(pubKey), "You cannot play against yourself"); }// end of acceptGame ``` Add an explicit state management check to ensure the game state is as expected before allowing further access: ``` // state verification check assert(board2State == BoardState.UNSET, "There is already a player2"); }// end of acceptGame ``` This state is updated at the end of this circuit, rendering the circuit inaccessible for the remainer of the contract lifecycle. Now verify the inputs are within bounds: ``` // input verification checks assert(_x1 != _x2, "Cannot use the same number twice"); assert(_x1 > 0 && _x2 > 0, "No zero index, please keep ships on the board"); assert(_x1 <= 20 && _x2 <= 20, "Out of bounds, please keep ships on the board"); }// end of acceptGame ``` All checks have now passed, the caller is assigned as `player2`: ``` // user assignment player2 = disclose(pubKey); }// end of acceptGame ``` `player2` also needs to hide their private data publicly: ``` // hash inputs and store them to the ledger for comparison later const hash1 = commitBoardSpace(_x1 as Bytes<32>, _sk); board2.insert(hash1); const hash2 = commitBoardSpace(_x2 as Bytes<32>, _sk); board2.insert(hash2); }// end of acceptGame ``` Now that they have committed to these values publicly, ask the player to set their board locally: ``` // setting the state locally and verifying const localBoardState = localSetBoard(_x1, _x2); assert(localBoardState == BoardState.SET, "Please update the state of your board to SET"); }// end of acceptGame ``` Finally, on-chain state is updated to transition to the next game state: ``` // setting on-chain state board2State = disclose(localBoardState); // updating on-chain state turn = TurnState.PLAYER_1_SHOOT; }// end of acceptGame ``` Now both players are set up with public commitments to their private data. The program will catch any attempt to present different data for ship locations in later `checkBoard` circuits. ### Hashing circuits[​](#hashing-circuits "Direct link to Hashing circuits") Before going any further in the game flow, implement the necessary hashing functions: ``` // hashing a commitment to a board space circuit commitBoardSpace(_x: Bytes<32>, _sk: Bytes<32>): Bytes<32> { const hash = persistentHash>>([_x, _sk]); return disclose(hash); } // hashing a DApp specific public key to identify the user (only in this contract) circuit getDappPubKey(_sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "battleship:pk:"), _sk]); } ``` `commitBoardSpace` takes in a single ship location `_x` and hashes it using `persistentHash` and a `_sk`. This pattern ensures that the data in `_x` cannot be guessed. Given the small board size (20), it would be relatively easy for a malicious actor to brute-force hash all of the possible numbers and compare the hashes with the on-chain ship locations. Hashing with complex binary data, like a `_sk`, makes a brute-force attack nearly impossible. A similar pattern is used for `getDappPubKey`, though it only combines the `_sk` with a domain seperator ("battleship:pk:") to reduce hash collision from other DApps using similar patterns. `persistentCommit` offers similar functionality with different input requirements. ### Shoot circuits[​](#shoot-circuits "Direct link to Shoot circuits") Back to the game operation, it is now `player1`'s turn to shoot: ``` export circuit player1Shoot (x: Uint<8>): [] { // caller verification check const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player1 == disclose(pubKey), "You are not player1"); }// end of player1Shoot ``` Use the same pattern of hashing the `_sk` through `getDappPubKey` to identify the user calling is the same that has already been assigned as `player1`. Any difference in the hashes indicates a different player is calling this circuit. After verifying the caller is `player1`, verify state is as expected and inputs are valid: ``` // state verification checks assert(board2State == BoardState.SET, "Player 2 has not yet set their board"); assert(turn == TurnState.PLAYER_1_SHOOT, "It is not player1 turn to shoot"); assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); // input validation assert(x > 0 && x <= 20, "Shot out of bounds, please shoot on the board"); }// end of player1Shoot ``` Now that the input has been verified, `disclose` the shot in preparation for public storage and verify that it is not a previously HIT location: ``` // shots are public knowledge const currentShot = disclose(x); assert(!board2Hits.member(currentShot), "Cheat Detected: Player1: Attempt to repeat a previous HIT"); }// end of player1Shoot ``` The `disclose` keyword itself does not make a value public, it is an explicit, manual requirement in Compact for the programmer to notify the compiler that a piece of data, which is currently private, is intending to be made public. This is typically done through a ledger value assignment. Update on-chain state and data: ``` // on-chain state updates player1Shot.pushFront(currentShot); turn = TurnState.PLAYER_2_CHECK; }// end of player1Shoot ``` `player1Shot` is a `List`, allowing ordered access to elements. This program takes the front element from the `List` as the current shot. `player2` has the same needs as `player1` in this context, the same circuit is implemented for them with differences in identifiers specific to the appropriate player: ``` export circuit player2Shoot(x: Uint<8>): [] { // caller verification checks const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player2 == disclose(pubKey), "You are not player2"); // state verification checks assert(turn == TurnState.PLAYER_2_SHOOT, "It is not player2 turn to shoot"); assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); // input validation assert(x > 0 && x <= 20, "Shot out of bounds, please shoot on the board"); // shots are public knowledge const currentShot = disclose(x); assert(!board1Hits.member(currentShot), "Cheat Detected: Player2: Attempt to repeat a previous HIT"); // on-chain state updates player2Shot.pushFront(currentShot); turn = TurnState.PLAYER_1_CHECK; }// end of player2Shoot ``` Inspect this circuit now that you have the code complete in front of you. What is the most noticeable pattern in "shoot" circuits? There are as many `assert` statements as code operations! This is a sign of a safe and secure smart contract. Always `assert` *everything you assume* about a particular piece of data, state or identity. This most commonly equates to: state verification checks, authorization checks and input validation assertions. Only after rigorously verifying the data is as expected should you feel comfortable in using it in your intended functions. ### Check boards locally[​](#check-boards-locally "Direct link to Check boards locally") The last interesting thing the contract needs to do is allow a player to check their board for a HIT or MISS. They do this locally (private) and return their desired response publicly. The contract needs to enforce the correct response. Start with some detailed `asserts` before processing any data: ``` export circuit checkBoard1(): [] { // caller verification check const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player1 == disclose(pubKey), "You are not player1"); // state verification checks assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); assert(turn == TurnState.PLAYER_1_CHECK, "It is not Player 1 turn to CHECK"); assert(!player2Shot.isEmpty(), "No shot to check"); // shot processing const currentShot = player2Shot.head().value; assert(!board1Hits.member(currentShot), "Cheat Detected: Player2: Attempt to repeat a previous HIT"); player2Shot.popFront(); }// end of checkBoard1 ``` First the caller is verified to be `player2`, then the various state expectations are verified before moving on to storing `currentShot` for processing and clearing `player1Shot` with `popFront()`. Now, an honesty check. Remember that claiming a MISS when a shot was in fact a HIT is the most common cheating vector. So the `honestyCheckHash` is created and state is verified to be valid: ``` // hash for comparision with on-chain hash const honestyCheckHash = commitBoardSpace(currentShot as Bytes<32>, _sk); // currentShot has already been exposed, but we need to satisfy the compiler here too const shotState = disclose(localCheckBoard(currentShot)); assert(shotState == ShotState.HIT || shotState == ShotState.MISS, "Please provide a valid state"); }// end of checkBoard1 ``` Now that `shotState` is verified to be one of two possible valid states, each can be conditionally handled. First if a MISS is claimed -- don't trust, verify: ``` // conditional handling if(shotState == ShotState.MISS){ // don't trust, verify assert(!board1.member(honestyCheckHash), "Cheat Detected: Player 1: claimed a MISS, when it was in fact a HIT"); turn = TurnState.PLAYER_1_SHOOT; } else { }// end of checkBoard1 ``` The `assert` here is what keeps players honest. It is not possible for this data to be changed or falsified. If `player1` attempts to cheat, the contract detects this and rejects the interaction. If the shot is HIT, that condition is handled: ``` // don't trust, verify assert(board1.member(honestyCheckHash), "Cheat Detected: Player 1: claimed a HIT, when is was in fact a MISS. Why would they do that?"); board1HitCount.increment(1); board1Hits.insert(currentShot); turn = TurnState.PLAYER_1_SHOOT; // did someone win? winState = board1HitCount == 2 ? WinState.PLAYER_2_WINS : WinState.CONTINUE_PLAY; }// end of if...else }// end of checkBoard1 ``` Always verify the input is what is expected. `player1` could claim a HIT when it was a MISS, but why would they do that? The `board1HitCount` is icremented and the shot added to the successful hits. `turn` state is then updated before checking if this is the HIT that wins the game. `player2` has the same needs as `player1` here, so the same circuit is implemented with different identifier names specific to the appropriate player: ``` export circuit checkBoard2(): [] { // caller verification const _sk = localSk(); const pubKey = getDappPubKey(_sk); assert(player2 == disclose(pubKey), "You are not player2"); // state verification assert(board2State == BoardState.SET, "Player 2 has not set the board yet"); assert(winState == WinState.CONTINUE_PLAY, "A winner has already been declared"); assert(turn == TurnState.PLAYER_2_CHECK, "It is not Player 2 turn to CHECK"); assert(!player1Shot.isEmpty(), "No shot to check"); // shot processing const currentShot = player1Shot.head().value; assert(!board2Hits.member(currentShot), "Cheat Detected: Player 1: Attempt to repeat a previous HIT"); player1Shot.popFront(); // on-chain board comparison hash const honestyCheckHash = commitBoardSpace(currentShot as Bytes<32>, _sk); // state return verification const shotState = disclose(localCheckBoard(currentShot)); assert(shotState == ShotState.HIT || shotState == ShotState.MISS, "Please provide a valid state"); // conditional handling if(shotState == ShotState.MISS){ // don't trust, verify assert(!board2.member(honestyCheckHash), "Cheat Detected: Player 2: claimed a MISS, when it was in fact a HIT"); turn = TurnState.PLAYER_2_SHOOT; } else { // dont trust, verify assert(board2.member(honestyCheckHash), "Cheat Detected: Player 2: claimed a HIT, when it was in fact a MISS. Why would they do that?"); board2HitCount.increment(1); board2Hits.insert(currentShot); turn = TurnState.PLAYER_2_SHOOT; // did someone win? winState = board2HitCount == 2 ? WinState.PLAYER_1_WINS : WinState.CONTINUE_PLAY; } }// end of checkBoard2 ``` That is all of the Compact code needed to build a safe and secure Battleship game! ### Compact compile[​](#compact-compile "Direct link to Compact compile") To compile this code, run the Compact compiler. From the `/contract` folder: ``` compact compile battleship.compact managed/battleship ``` Successful output: ``` Compiling 5 circuits: circuit "acceptGame" (k=14, rows=12767) circuit "checkBoard1" (k=14, rows=8649) circuit "checkBoard2" (k=14, rows=8650) circuit "player1Shoot" (k=13, rows=4226) circuit "player2Shoot" (k=13, rows=4222) Overall progress [====================] 5/5 ``` To further inspect circuit data run the zkir linter (optional): ``` npx compact-zkir-lint -r managed/battleship/zkir ``` Successful output: ``` zkir-lint: scanned 5 file(s) acceptGame (v2, k=12): clean instructions: 159 inputs: 2 constrain_bits: 4 cond_select: 6 guarded regions: 0 (max depth 0) proof payload: ~192KB checkBoard1 (v2, k=12): clean instructions: 400 inputs: 0 constrain_bits: 2 cond_select: 62 guarded regions: 0 (max depth 1) proof payload: ~192KB checkBoard2 (v2, k=12): clean instructions: 416 inputs: 0 constrain_bits: 2 cond_select: 61 guarded regions: 0 (max depth 1) proof payload: ~192KB player1Shoot (v2, k=11): clean instructions: 185 inputs: 1 constrain_bits: 3 cond_select: 4 guarded regions: 0 (max depth 0) proof payload: ~96KB player2Shoot (v2, k=11): clean instructions: 168 inputs: 1 constrain_bits: 3 cond_select: 4 guarded regions: 0 (max depth 0) proof payload: ~96KB 0 error(s), 0 warning(s), 0 info(s) | 5/5 clean ``` ## Witnesses[​](#witnesses "Direct link to Witnesses") If you recall from the Compact section of this tutorial, witnesses are only declared in Compact, they are actually implemented in the Typescript frontend. This allows a developer to delegate expensive compute operations off-chain and to isolate private state functions. Before writing any Typescript, create a config file: ``` cd .. touch tsconfig.json ``` Populate it: ``` { "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "lib": ["ES2022"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "isolatedModules": true, "verbatimModuleSyntax": true, "noEmit": true, "outDir": "dist", "rootDir": "." }, "include": ["src/**/*.ts", "contract/**/*.ts"] } ``` Before moving on to testing the contract, the necessary witness functionality needs to be implemented. From inside the `/contract` directory: ``` cd contract touch witnesses.ts ``` Start with imports: ``` import { type Ledger, BoardState, ShotState } from './managed/battleship/contract/index.js'; import { type WitnessContext } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; ``` Now the private state data relative to the program needs a custom type: ``` export type BattlePrivateState = { x1: bigint, x2: bigint, boardState: number, shotState: number, sk: Uint8Array, }; ``` `x1` and `x2` are the private locations of a player's ships. The `boardState` starts as a private state piece of data and becomes public to allow the game to start. `shotState` is a shot-by-shot decision made by each player to either present the correct response or to cheat and provide the incorrect response, which the Compact code guards against and this behavior will be verified with the frontend test script. Write a helper function to create an object of our `BattlePrivateState` type: ``` export const createBattlePrivateState = ( x1: bigint, x2: bigint, boardState: number, shotState: number, sk: Uint8Array, ) => ({ x1, x2, boardState, shotState, sk }); ``` This will be used in the tests to create private state for each of the players, as well as simulating the manipulation of their private state. Now the `witnesses` declared by the Compact code can be implemented, starting with a simple "getter" of private state data: ``` export const witnesses = { localSk: ({ privateState }: WitnessContext): [ BattlePrivateState, Uint8Array ] => { return [privateState, privateState.sk]; },// end of localSk };// end of witnesses ``` Witness function signatures must match exactly with the corresponding Compact declaration and they *always* take the `privateState` object as an argument, followed by the `WitnessContext` type with ``. The next two lines denote the return type(s) of the function. Witness functions always require passing the `privateState` as the first return value, followed by any returns specified by the function signature. Implement a "setter" of private state data: ``` localSetBoard: ({ privateState }: WitnessContext, x1: bigint, x2: bigint): [ BattlePrivateState, BoardState ] => { privateState.x1 = x1; privateState.x2 = x2; privateState.boardState = BoardState.SET; return [privateState, privateState.boardState]; },// end of localSetBoard };// end of witnesses ``` The shape of this function is similar to `localSk()` in its requirements, this time `x1` and `x2` have been added as inputs followed by setting these in the actual `privateState` object. Finally, update `privateState.boardState` before returning this value to the contract. The final witness function needs to perform a check of a players private state data: ``` localCheckBoard: ({ privateState }: WitnessContext, x: bigint): [ BattlePrivateState, ShotState ] => { let currentShot = ShotState.MISS;// reset to default -- MISS if(x == privateState.x1 || x == privateState.x2){ currentShot = ShotState.HIT;// only HIT if it is in fact a HIT } privateState.shotState = currentShot; return [privateState, privateState.shotState]; },// end of localCheckBoard };//end of witnesses ``` It is important to note that operations on private state data in witness functions are not verified in any way. It is imperative that DApp developers always verify that computations in witness functions were performed to expectations through `assert` statements. There are rigorous checks built into the `.compact` code and the frontend test suite will verify their correct operation. That is everything needed for off-chain witnesses. You can now export the compiled contract. ### Exports[​](#exports "Direct link to Exports") From the `/contract` directory: ``` touch index.ts ``` Use the `index.ts` file to export the compiled contract and necessary types: ``` import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import path from 'node:path'; export { Contract, ledger, pureCircuits, type Witnesses, type Ledger, type ImpureCircuits, type PureCircuits } from './managed/battleship/contract/index.js'; import { Contract } from './managed/battleship/contract/index.js'; import { witnesses } from './witnesses.js'; const currentDir = path.resolve(new URL(import.meta.url).pathname, '..'); export const zkConfigPath = path.resolve(currentDir, 'managed', 'battleship'); export const CompiledBattleshipContract = CompiledContract.make( 'BattleshipContract', Contract, ).pipe( CompiledContract.withWitnesses(witnesses), CompiledContract.withCompiledFileAssets(zkConfigPath), ) ``` That completes the code needed for Compact and its supporting files. To recap, the directory structure should look like this: ``` contract/ ├── managed/ | └── battleship/ | ├── compiler/ | ├── contract/ | ├── keys/ | └── zkir/ ├── battleship.compact ├── index.ts └── witnesses.ts ``` ## Next steps[​](#next-steps "Direct link to Next steps") The next steps will be covered in the [test-suite](/tutorials/bship/test-suite.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Battleship tests The next phase in the smart contract development lifecycle is the frontend test suite. This is where smart contract developers run many iterations of tests on different instances of the contract. The permissionless nature of a public blockchain means that all contract circuits are available essentially as public APIs for each contract instance. Developers must test everything they assume about the interaction with their contract, both succeeding and failing calls. The failure tests are just as important as the passing tests, because they are guarding against vulnerabilities in contracts. Successful test suites are those that comprehensively cover *every possible interaction with a contract*. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * Completing the Battleship [smart-contract](/tutorials/bship/smart-contract.md) tutorial * Yarn ## Setup[​](#setup "Direct link to Setup") Set up the project for testing by copying the following configuration files. ### package.json[​](#packagejson "Direct link to package.json") From the project root: ``` touch package.json ``` Populate the file: ``` { "name": "battleship", "version": "0.1.0", "private": true, "type": "module", "engines": { "node": ">=22.0.0" }, "scripts": { "compile": "compact compile contract/battleship.compact contract/managed/battleship", "test": "NODE_OPTIONS='--experimental-vm-modules' vitest run", "test:local": "MIDNIGHT_NETWORK=local yarn test", "env:up": "docker compose up -d --wait", "env:down": "docker compose down", "wait:dust": "vite-node scripts/wait-for-dust.ts", "validate": "yarn env:up && yarn wait:dust && yarn test:local; yarn env:down" }, "dependencies": { "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-contracts": "4.1.1", "@midnight-ntwrk/midnight-js-http-client-proof-provider": "4.1.1", "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "4.1.1", "@midnight-ntwrk/midnight-js-level-private-state-provider": "4.1.1", "@midnight-ntwrk/midnight-js-node-zk-config-provider": "4.1.1", "@midnight-ntwrk/testkit-js": "4.1.1", "@midnight-ntwrk/wallet-sdk": "1.2.0", "axios": "^1.13.6", "pino": "^9.0.0", "pino-pretty": "^13.0.0", "rxjs": "^7.8.2", "testcontainers": "^11.13.0", "ws": "^8.14.2" }, "devDependencies": { "@types/node": "^22.0.0", "@types/ws": "^8.5.9", "typescript": "^5.7.0", "vitest": "^4.1.0" }, "packageManager": "yarn@1.22.22" } ``` Install dependencies: ``` yarn install ``` ### vitest.config.ts[​](#vitestconfigts "Direct link to vitest.config.ts") Create the test config file: ``` touch vitest.config.ts ``` Populate it: ``` import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { environment: 'node', globals: true, testTimeout: 10 * 60_000, hookTimeout: 15 * 60_000, include: ['src/**/*.test.ts'], reporters: ['default'], sequence: { concurrent: false }, disableConsoleIntercept: true, }, }); ``` ### compose.yml[​](#composeyml "Direct link to compose.yml") Add the docker configuration for deploying to local devnet: ``` touch compose.yml ``` Populate it: ``` services: proof-server: image: 'midnightntwrk/proof-server:8.1.0' command: ['midnight-proof-server', '-v'] ports: - '127.0.0.1:6300:6300' environment: RUST_BACKTRACE: 'full' healthcheck: test: ['CMD-SHELL', 'echo > /dev/tcp/127.0.0.1/6300'] interval: 10s timeout: 5s retries: 20 start_period: 10s indexer: image: 'midnightntwrk/indexer-standalone:4.3.3' ports: - '127.0.0.1:8088:8088' environment: RUST_LOG: 'indexer=info,chain_indexer=info,indexer_api=info,wallet_indexer=info,indexer_common=info,fastrace_opentelemetry=off,info' APP__INFRA__NODE__URL: 'ws://node:9944' APP__APPLICATION__NETWORK_ID: 'undeployed' APP__INFRA__STORAGE__PASSWORD: 'indexer' APP__INFRA__PUB_SUB__PASSWORD: 'indexer' APP__INFRA__LEDGER_STATE_STORAGE__PASSWORD: 'indexer' APP__INFRA__SECRET: '303132333435363738393031323334353637383930313233343536373839303132' APP__INFRA__SPO_NODE__URL: 'ws://node:9944' APP__INFRA__SPO_NODE__BLOCKFROST_ID: 'e2e-test-dummy-id' healthcheck: test: ['CMD-SHELL', 'cat /var/run/indexer-standalone/running'] interval: 10s timeout: 5s retries: 20 start_period: 10s depends_on: node: condition: service_healthy node: image: 'midnightntwrk/midnight-node:1.0.0' ports: - '127.0.0.1:9944:9944' healthcheck: test: ['CMD', 'curl', '-f', 'http://localhost:9944/health'] interval: 2s timeout: 5s retries: 20 start_period: 5s environment: CFG_PRESET: 'dev' SIDECHAIN_BLOCK_BENEFICIARY: '04bcf7ad3be7a5c790460be82a713af570f22e0f801f6659ab8e84a52be6969e' ``` note This is a local devnet configuration *only*. Certain environment variables are present that should not be included in production applications. ### Midnight setup[​](#midnight-setup "Direct link to Midnight setup") For the Midnight specific setup: ``` mkdir src && cd src ``` Create the network config file: ``` touch config.ts ``` Populate the file: ``` export type NetworkConfig = { networkId: string; indexer: string; indexerWS: string; node: string; nodeWS: string; proofServer: string; faucet: string; }; // depends on docker config in compose.yml running export const LOCAL_CONFIG: NetworkConfig = { networkId: 'undeployed', indexer: 'http://127.0.0.1:8088/api/v4/graphql', indexerWS: 'ws://127.0.0.1:8088/api/v4/graphql/ws', node: 'http://127.0.0.1:9944', nodeWS: 'ws://127.0.0.1:9944', proofServer: 'http://127.0.0.1:6300', faucet: '', }; export function getConfig(): NetworkConfig { const network = process.env['MIDNIGHT_NETWORK'] ?? 'local'; if (network !== 'local') { throw new Error( `Unknown network: ${network}. This harness only supports 'local'.`, ); } return LOCAL_CONFIG; } ``` This config file is only setup for local devnet, but it can be extended to support other network configurations by adding to this pattern. Create the wallet class to enable creation of multiple wallets: ``` touch wallet.ts ``` Populate the file: ``` import { type CoinPublicKey, DustSecretKey, type EncPublicKey, type FinalizedTransaction, LedgerParameters, ZswapSecretKeys, } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import type { MidnightProvider, UnboundTransaction, WalletProvider, } from '@midnight-ntwrk/midnight-js-types'; import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils'; import type { WalletFacade, FacadeState, UnshieldedKeystore, } from '@midnight-ntwrk/wallet-sdk'; import { type DustWalletOptions, type EnvironmentConfiguration, FluentWalletBuilder, } from '@midnight-ntwrk/testkit-js'; import * as Rx from 'rxjs'; import type { Logger } from 'pino'; export type WalletSecret = | { kind: 'seed'; value: string } | { kind: 'mnemonic'; value: string }; export class MidnightWalletProvider implements MidnightProvider, WalletProvider { readonly wallet: WalletFacade; readonly unshieldedKeystore: UnshieldedKeystore; private constructor( private readonly logger: Logger, wallet: WalletFacade, private readonly zswapSecretKeys: ZswapSecretKeys, private readonly dustSecretKey: DustSecretKey, unshieldedKeystore: UnshieldedKeystore, ) { this.wallet = wallet; this.unshieldedKeystore = unshieldedKeystore; } getCoinPublicKey(): CoinPublicKey { return this.zswapSecretKeys.coinPublicKey; } getEncryptionPublicKey(): EncPublicKey { return this.zswapSecretKeys.encryptionPublicKey; } async balanceTx( tx: UnboundTransaction, ttl: Date = ttlOneHour(), ): Promise { const recipe = await this.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: this.zswapSecretKeys, dustSecretKey: this.dustSecretKey, }, { ttl }, ); return await this.wallet.finalizeRecipe(recipe); } submitTx(tx: FinalizedTransaction): Promise { return this.wallet.submitTransaction(tx); } async start(): Promise { this.logger.info('Starting wallet...'); await this.wallet.start(this.zswapSecretKeys, this.dustSecretKey); } async stop(): Promise { return this.wallet.stop(); } static async build( logger: Logger, env: EnvironmentConfiguration, secret: WalletSecret, ): Promise { const dustOptions: DustWalletOptions = { ledgerParams: LedgerParameters.initialParameters(), additionalFeeOverhead: 1_000n, feeBlocksMargin: 5, }; const base = FluentWalletBuilder.forEnvironment(env) .withDustOptions(dustOptions); const builder = secret.kind === 'mnemonic' ? base.withMnemonic(secret.value) : base.withSeed(secret.value); const buildResult = await builder.buildWithoutStarting(); const { wallet, seeds, keystore } = buildResult as { wallet: WalletFacade; seeds: { masterSeed: string; shielded: Uint8Array; dust: Uint8Array; }; keystore: UnshieldedKeystore; }; logger.info( `Wallet built from ${secret.kind}; master seed: ${seeds.masterSeed.slice(0, 8)}...`, ); return new MidnightWalletProvider( logger, wallet, ZswapSecretKeys.fromSeed(seeds.shielded), DustSecretKey.fromSeed(seeds.dust), keystore, ); } } function isProgressStrictlyComplete(progress: unknown): boolean { if (!progress || typeof progress !== 'object') { return false; } const candidate = progress as { isStrictlyComplete?: unknown }; if (typeof candidate.isStrictlyComplete !== 'function') { return false; } return (candidate.isStrictlyComplete as () => boolean)(); } export async function syncWallet( logger: Logger, wallet: WalletFacade, timeout = 300_000, ): Promise { logger.info('Syncing wallet...'); let emissionCount = 0; return Rx.firstValueFrom( wallet.state().pipe( Rx.tap((state: FacadeState) => { emissionCount++; const shielded = isProgressStrictlyComplete(state.shielded.state.progress); const unshielded = isProgressStrictlyComplete(state.unshielded.progress); const dust = isProgressStrictlyComplete(state.dust.state.progress); logger.info( `Wallet sync [${emissionCount}]: shielded=${shielded}, unshielded=${unshielded}, dust=${dust}`, ); if (!shielded) { logger.debug(` shielded.progress: ${JSON.stringify(state.shielded.state.progress)}`); } if (!unshielded) { logger.debug(` unshielded.progress: ${JSON.stringify(state.unshielded.progress)}`); } if (!dust) { logger.debug(` dust.progress: ${JSON.stringify(state.dust.state.progress)}`); } }), Rx.filter( (state: FacadeState) => isProgressStrictlyComplete(state.shielded.state.progress) && isProgressStrictlyComplete(state.dust.state.progress) && isProgressStrictlyComplete(state.unshielded.progress), ), Rx.tap(() => logger.info(`Wallet sync complete after ${emissionCount} emissions`)), Rx.timeout({ each: timeout, with: () => Rx.throwError( () => new Error(`Wallet sync timeout after ${timeout}ms (${emissionCount} emissions received)`), ), }), Rx.catchError((err) => { logger.error(`Wallet sync error: ${err}`); return Rx.throwError(() => err); }), ), ); } ``` This wallet class can be reused across different projects, it does not change significantly with different Compact contract implementations. Create the providers file: ``` touch providers.ts ``` The providers are an important component of MidnightJS and they provide an interface for setting and retrieving data from private state, public state, wallet operations and more. This will be demonstrated in the actual test file. Populate the providers file: ``` // Returns the providers in an object which can be created for each users individual tests import { type MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { type MidnightWalletProvider } from './wallet.js'; import { type NetworkConfig } from './config.js'; export type BattleshipCircuits = 'acceptGame' | 'player1Shoot' | 'checkBoard1' | 'player2Shoot' | 'checkBoard2'; export type BattleshipProviders = MidnightProviders; export function buildProviders( wallet: MidnightWalletProvider, zkConfigPath: string, config: NetworkConfig, ): BattleshipProviders { const zkConfigProvider = new NodeZkConfigProvider(zkConfigPath); return { privateStateProvider: levelPrivateStateProvider({ privateStateStoreName: `battleship-${Date.now()}`, // this password has requirements (capital/special chars >= 3) privateStoragePasswordProvider: () => 'Battleship-Test-Password', accountId: wallet.getCoinPublicKey(), }), publicDataProvider: indexerPublicDataProvider( config.indexer, config.indexerWS, ), zkConfigProvider, proofProvider: httpClientProofProvider( config.proofServer, zkConfigProvider, ), walletProvider: wallet, midnightProvider: wallet, }; } ``` ## Tests, tests, and more tests[​](#tests-tests-and-more-tests "Direct link to Tests, tests, and more tests") Create the test directory and file: ``` mkdir test && cd test touch battle.test.ts ``` ### Test imports[​](#test-imports "Direct link to Test imports") The test file is an extremely important component of this process, so it is important to understand the concepts here. First, import necessary packages: ``` import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { randomBytes } from 'node:crypto'; import pino from 'pino'; import { submitCallTx, deployContract } from '@midnight-ntwrk/midnight-js-contracts'; import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import type { ContractAddress } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { type EnvironmentConfiguration, waitForFunds } from '@midnight-ntwrk/testkit-js'; import { getConfig } from '../config.js'; import { MidnightWalletProvider, syncWallet, type WalletSecret } from '../wallet.js'; import { buildProviders, type BattleshipProviders } from '../providers.js'; import { CompiledBattleshipContract, ledger, zkConfigPath, } from '../../contract/index.js'; import { BoardState, ShotState, WinState, TurnState, Contract } from '../../contract/managed/battleship/contract/index.js'; import { createBattlePrivateState } from '../../contract/witnesses.js'; import type { FinalizedCallTxData } from '@midnight-ntwrk/midnight-js-contracts'; ``` ### Wallet preparation[​](#wallet-preparation "Direct link to Wallet preparation") Create identifiers for the players: ``` const ALICE_SEED = '0000000000000000000000000000000000000000000000000000000000000001'; const BOB_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; const ALICE_PRIVATE_ID = 'alicePrivateState'; const BOB_PRIVATE_ID = 'bobPrivateState'; const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info', transport: { target: 'pino-pretty' }, }); ``` Local devnet comes with pre-funded addresses for the first 3 seed accounts. Alice is assigned to one and Bob to two. Each player also needs a string for identifying their private state. Next, setup for the main test: ``` describe('Battleship Smart Contract via midnight-js', async () => { let aliceWallet: MidnightWalletProvider; let bobWallet: MidnightWalletProvider; let aliceProviders: BattleshipProviders; let bobProviders: BattleshipProviders; let contractAddress: ContractAddress; const config = getConfig(); const board1x1 = BigInt(1); const board1x2 = BigInt(2); const board2x1 = BigInt(10); const board2x2 = BigInt(11); });// end of describe ``` `MidnightWalletProvider` is the type defined by the wallet class exported from `wallet.ts` and `BattleshipProviders` comes from the `providers.ts` exports. `getConfig()` returns the network configuration from the `config.ts` file and is currently set up to operate on an `undeployed` network. The `const` assignments that follow are for placing each player's ship locations uniquely. These are assigned here for programmatic testing, but in the production version of this application these values would be presented by the user in some UI component. ### Ledger queries[​](#ledger-queries "Direct link to Ledger queries") Write a helper function for querying the ledger: ``` async function queryLedger(providers: BattleshipProviders) { const state = await providers.publicDataProvider.queryContractState(contractAddress); expect(state).not.toBeNull(); return ledger(state!.data); } })// end of describe ``` This function starts to demonstrate the use of `providers` for each player. A particular player's provider object can be passed in to operate on the `publicDataProvider` and return the contract state as it exists currently on the blockchain. This function will be put to use soon. ### beforeAll[​](#beforeall "Direct link to beforeAll") Now, perform `beforeAll` test operations: ``` // setup before tests beforeAll(async () => { setNetworkId(config.networkId); const envConfig: EnvironmentConfiguration = { walletNetworkId: config.networkId, networkId: config.networkId, indexer: config.indexer, indexerWS: config.indexerWS, node: config.node, nodeWS: config.nodeWS, faucet: config.faucet, proofServer: config.proofServer, }; aliceWallet = await MidnightWalletProvider.build(logger, envConfig, ALICE_SEED); await aliceWallet.start(); await syncWallet(logger, aliceWallet.wallet, 600_000); bobWallet = await MidnightWalletProvider.build(logger, envConfig, BOB_SEED); await bobWallet.start(); await syncWallet(logger, bobWallet.wallet, 600_000); aliceProviders = buildProviders(aliceWallet, zkConfigPath, config); bobProviders = buildProviders(bobWallet, zkConfigPath, config); logger.info('Providers initialized, ready to test.'); });// end of beforeAll })// end of describe ``` `setNetworkId()` is a necessary call through MidnightJS to identify which network it needs to interact with for things like address formatting. Each user then calls `build()` from the wallet class to prepare a wallet. That wallet is then started and synced with the network by calling other functions of the wallet class. Finally, each user builds their providers (public, private, wallet) by calling `buildProviders()` from the exports in `providers.ts`. ### afterAll[​](#afterall "Direct link to afterAll") After the tests complete these wallets need to be stopped, so `afterAll()`: ``` // tear down after tests afterAll(async () => { if(aliceWallet) { logger.info('Stopping aliceWallet...'); await aliceWallet.stop(); } if(bobWallet) { logger.info('Stopping bobWallet...'); await bobWallet.stop(); } }); })// end of describe ``` The first tests are ready to be written! Each individual test should be structured as an `it()` from the Vitest package: ``` it('deploys the contract', async () => { }); });// end of describe ``` ### Deploying the contract[​](#deploying-the-contract "Direct link to Deploying the contract") Deploying the contract is the logical first thing to do, it sends the contract code out to the network and allows access to the contract circuits via MidnightJS calls. In order to call the `deployContract` function of MidnightJS an initial private state needs to be created for *Alice the Deployer(TM)*: ``` it('deploys the contract', async () => { const aliceSk = randomBytes(32); const alicePrivateState = createBattlePrivateState( board1x1,// x1 ship location board1x2,// x2 BoardState.UNSET, ShotState.MISS, aliceSk, ); }); });// end of describe ``` `aliceSk` is a collection of random bytes signifying a DApp specific secret key. This is the key that will be hashed to publish a DApp specific public key for each player. With this pattern, players can be tracked in this DApp, but not outside of it. `alicePrivateState` is the return value of calling the `createBattlePrivateState` function exported from `witnesses.ts`. This creates a properly typed object that matches the expectations of the compiled contract accessed through MidnightJS. Deploy the contract to the blockchain: ``` const deployed: DeployedContract = await (deployContract)(aliceProviders, { compiledContract: CompiledBattleshipContract, privateStateId: ALICE_PRIVATE_ID, initialPrivateState: alicePrivateState, args: [alicePrivateState.x1, alicePrivateState.x2] }); });// end of it('deploys the contract') });// end of describe ``` `deployContract` is the MidnightJS function to deploy the contract to the blockchain. It takes the following arguments: * `aliceProviders` the providers object of the user making the call * `compiledContract` is the compiled Battleship contract from the `index.ts` file * `privateStateId` is the unique identifier to the private state of the caller * `initialPrivateState` is the starting private state for the caller, the return value of the `createBattlePrivateState` function * `args` are any constructor arguments required by the contract When this call finalizes, it returns a value of the `DeployedContract` type that can be inspected and verified itself. Now that the contract is deployed, set the global `contractAddress` and private state for Alice: ``` contractAddress = deployed.deployTxData.public.contractAddress; aliceProviders.privateStateProvider.setContractAddress(contractAddress); await aliceProviders.privateStateProvider.set(ALICE_PRIVATE_ID, alicePrivateState); logger.info(`Contract deployed at: ${contractAddress}`); expect(contractAddress).toBeDefined(); expect(contractAddress.length).toBeGreaterThan(0); });// end of it('deploys the contract') });// end of describe ``` Failing to call `setContractAddress()` before accessing `aliceProviders.privateStateProvider` will cause an error. Always assign the contract address as soon as it is available. It is important to note that simply creating an object of the private state for Alice through `createBattlePrivateState` is not enough. This needs to be passed in to `privateStateProvider.set()` to initialize the MidnightJS provider for private state, this is where private state will be accessed in future tests. Because the contract is deployed it should have an initial state on the blockchain that reflects successful constructor execution. Use the `queryLedger()` function to check that the state is as expected: ``` const state = await queryLedger(aliceProviders); expect(state.board1State).toEqual(BoardState.SET); expect(state.board2State).toEqual(BoardState.UNSET); expect(state.winState).toEqual(WinState.CONTINUE_PLAY); });// end of it('deploys the contract') });// end of describe ``` If you flip back to the `.compact` file and inspect the contructor, it will give you a good indication of expected states and what should be tested. Now that the first test is complete, run it and see if it passes. Be sure the docker engine is running and start the local devnet: ``` yarn env:up ``` Local devnet requires a Node, Indexer and Proof server running locally, so be sure to leave these services running for the duration of these tests and check the status of the container before moving on to the next step. In a *seperate terminal*, execute the test script on local devnet: ``` yarn test:local ``` The test should start by syncing player wallets and initializing their providers. After that it should display a successful deployment of the contract! ``` [20:32:05.816] INFO (11363): Wallet sync complete after 104 emissions [20:32:05.824] INFO (11363): Providers initialized, ready to test. ✓ src/test/battleship.test.ts (1 test) 29035ms ✓ Battleship Smart Contract via midnight-js > deploys the contract 21282ms Test Files 1 passed (1) Tests 1 passed (1) ``` It is good practice to run each test after writing them, so that you can verify proper execution before moving on to the next step. ### Bob accepts the game[​](#bob-accepts-the-game "Direct link to Bob accepts the game") Bob is ready to accept the game: ``` });// end of it('deploys the contract') it('Allows Bob to acceptGame', async () => { const bobSk = randomBytes(32); const bobInitialPrivateState = createBattlePrivateState( board2x1, board2x2, BoardState.UNSET, ShotState.MISS, bobSk ); bobProviders.privateStateProvider.setContractAddress(contractAddress); await bobProviders.privateStateProvider.set(BOB_PRIVATE_ID, bobInitialPrivateState); const bobPrivateState = await bobProviders.privateStateProvider.get(BOB_PRIVATE_ID); logger.info(`Bob is accepting the game...`); const txData: FinalizedCallTxData = await (submitCallTx)(bobProviders, { compiledContract: CompiledBattleshipContract, contractAddress, privateStateId: BOB_PRIVATE_ID, circuitId: 'acceptGame', args: [bobPrivateState.x1, bobPrivateState.x2] }); logger.info(`Bob successfully joined the game!`); const state = await queryLedger(bobProviders); expect(state.board2State).toEqual(BoardState.SET); expect(state.board2.size()).toEqual(2n); expect(state.turn).toEqual(TurnState.PLAYER_1_SHOOT); }); });// end of describe ``` Bob's private state is set up in the same way as Alice, though this time the shape of the MidnightJS function has changed slightly. `submitCallTx` is the function to execute for basic contract calls and it has similar requirements to `deployContract`. Inspect it closely to check for differences. `submitCallTx` is what will be used to interact with the contract now that it is deployed. note The return value of `submitCallTx` is captured in `txData` for demonstration. It is not being used here, but holds useful information for inspecting circuit return data (status, txId, txHash, block info, fees, unshielded outputs, etc..). ### Alice takes the first shot[​](#alice-takes-the-first-shot "Direct link to Alice takes the first shot") Now that the contract is deployed and Bob has joined the game, the `turn` value recorded on the ledger means that it is Alice's turn to shoot. Write that test: ``` it('Allows Alice to take the first shot(MISS)', async () => { const shot = BigInt(5);// miss logger.info(`Alice shoots (MISS) at Bobs board...`); const txData: FinalizedCallTxData = await (submitCallTx)(aliceProviders, { compiledContract: CompiledBattleshipContract, contractAddress, privateStateId: ALICE_PRIVATE_ID, circuitId: 'player1Shoot', args: [shot] }); logger.info(`Alice shot successfully!`); const state = await queryLedger(aliceProviders); expect(state.board2HitCount).toEqual(0n); expect(state.player1Shot.head().is_some).toBeTruthy(); expect(state.player1Shot.head().value).toEqual(shot); expect(state.turn).toEqual(TurnState.PLAYER_2_CHECK); }); });// end of describe ``` This pattern should start to look familiar and continue to be used for most of the remaining tests. But what about the pattern for failed transaction calls? After all, testing for expected failures is just as important as testing the successful calls. Add a cheat attempt by Bob to this test to simulate attempting to shoot out of turn: ``` it('Allows Alice to take the first shot(MISS)', async () => { const shot = BigInt(5);// miss // new logger.info(`Bob tries to shoot out of turn...`); await expect(async () => { await (submitCallTx)(bobProviders, { compiledContract: CompiledBattleshipContract, contractAddress, privateStateId: BOB_PRIVATE_ID, circuitId: 'player2Shoot', args: [BigInt(1)]// arbitrary }); }).rejects.toThrow();// .rejects.toThrow() for calls expecting to fail logger.info(`Bobs shot (out of turn) was rejected!`); // end new logger.info(`Alice shoots (MISS) at Bobs board...`); const txData: FinalizedCallTxData = await (submitCallTx)(aliceProviders, { compiledContract: CompiledBattleshipContract, contractAddress, privateStateId: ALICE_PRIVATE_ID, circuitId: 'player1Shoot', args: [shot] }); logger.info(`Alice shot successfully!`); const state = await queryLedger(aliceProviders); expect(state.board2HitCount).toEqual(0n); expect(state.player1Shot.head().is_some).toBeTruthy(); expect(state.player1Shot.head().value).toEqual(shot); expect(state.turn).toEqual(TurnState.PLAYER_2_CHECK); }); });// end of describe ``` This is a test of the Compact explicit state management. If the `assert` statements are implemented correctly with the custom `TurnState`, the contract will not allow Bob to cheat here. Run these tests to find out: ``` yarn test:local ``` ``` Bobs shot (out of turn) was rejected! ``` No cheating Bob. ### Test yourself[​](#test-yourself "Direct link to Test yourself") Now that you've seen the pattern for successful and failing calls, write some tests yourself that progress the interaction of the contract. Look back at the `.compact` code to verify the state after a certain circuit executes and check these through `queryLedger()` at the end of each test. (hint: `submitCallTx` calls to circuits with no arguments should omit the `args` field.) For a challenge, work with the returned `txData` from `submitCallTx` to inspect and operate on the return values there. To view the entire test suite for reference see `battleship.test.ts` in [example-battleship](https://github.com/midnightntwrk/example-battleship/blob/main/src/test/battleship.test.ts). The linear progression of this tutorial has reached its end. Using the test file in the link above should provide the needed code for completing these tests. ### Further cheating attempts[​](#further-cheating-attempts "Direct link to Further cheating attempts") The next interesting thing to consider are the other guards against cheating. A lot of emphasis was put on the protection implemented in the Compact contract, but this should be tested explicitly. To simulate Bob(or Alice) attempting to maliciously change their private state, create a new private state object and set the private state provider: ``` logger.info(`Bob realizes it is going to be a HIT and tries to cheat...`); const bobPrivateState = await bobProviders.privateStateProvider.get(BOB_PRIVATE_ID); const cheatBobPrivateState = createBattlePrivateState( BigInt(15), BigInt(16), BoardState.SET, ShotState.MISS, bobPrivateState.sk, ); await bobProviders.privateStateProvider.set(BOB_PRIVATE_ID, cheatBobPrivateState); await expect(async () => { await (submitCallTx)(bobProviders, { compiledContract: CompiledBattleshipContract, contractAddress, privateStateId: BOB_PRIVATE_ID, circuitId: 'checkBoard2', }); }).rejects.toThrow(); logger.info(`Bobs cheating attempt was rejected!`); logger.info(`Bob is resetting his board to the original private state...`); await bobProviders.privateStateProvider.set(BOB_PRIVATE_ID, bobPrivateState); logger.info(`Bob successfully reverted his private state to the original!`); ``` * `bobProviders.privateStateProvider.get(BOB_PRIVATE_ID)` retrieves the current private state * `createBattlePrivateState` creates a new private state object with different locations for Bob's ships * `bobProviders.privateStateProvider.set()` sets the private state for Bob to the new object * Then run the call for `submitCallTx` as expecting `.rejects.toThrow()` and watch Bob get rejected! * Be sure to reset Bob's private state to the original ship locations so that future calls succeed when expected to do so ## Conclusion[​](#conclusion "Direct link to Conclusion") This concludes the Battleship tutorial. Some important lessons have been covered: * Private state management (setting, getting and changing it) in MidnightJS * Explicit state management in our Compact code * Calling in to our contract through MidnightJS * Successful and failing contract calls and tests * Defensive programming Thanks for following along. Shout out in the Discord dev-chat that you've become a Battleship master or share any feedback on this tutorial or if you mustache us any questions. To inspect the full Battleship repository, see [example-battleship](https://github.com/midnightntwrk/example-battleship). --- > For the complete documentation index, see [llms.txt](/llms.txt) # Leaderboard tutorial Build a full-stack DApp from Compact contract to production deployment. Players submit scores with privacy controls and prove ownership of entries using ZK proofs. [✦](/tutorials/leaderboard/overview.md) ### [Overview](/tutorials/leaderboard/overview.md) [Architecture, prerequisites, and what you build across all four sections of the leaderboard tutorial.](/tutorials/leaderboard/overview.md) [Read overview→](/tutorials/leaderboard/overview.md) [✦](/tutorials/leaderboard/smart-contract.md) ### [Smart contract](/tutorials/leaderboard/smart-contract.md) [Define structured on-chain data with Map, Counter, and custom structs. Control privacy with disclose() and witness functions.](/tutorials/leaderboard/smart-contract.md) [Write the contract→](/tutorials/leaderboard/smart-contract.md) [✦](/tutorials/leaderboard/api-layer.md) ### [TypeScript integration](/tutorials/leaderboard/api-layer.md) [Set up the witness provider, contract exports, and a shared API class for deploying and interacting with the contract.](/tutorials/leaderboard/api-layer.md) [Build the API→](/tutorials/leaderboard/api-layer.md) [✦](/tutorials/leaderboard/browser-dapp.md) ### [Browser DApp](/tutorials/leaderboard/browser-dapp.md) [Build a React frontend that connects to Lace wallet, reads state from the indexer, and submits scores on-chain.](/tutorials/leaderboard/browser-dapp.md) [Build the frontend→](/tutorials/leaderboard/browser-dapp.md) [✦](/tutorials/leaderboard/deployment.md) ### [Production deployment](/tutorials/leaderboard/deployment.md) [Deploy the leaderboard frontend to Vercel with compiled circuit keys and TypeScript bindings.](/tutorials/leaderboard/deployment.md) [Deploy to production→](/tutorials/leaderboard/deployment.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Part 2: TypeScript integration You create the TypeScript layer that connects the compiled Compact contract to your application. This includes the witness provider that feeds private data into the ZK circuit, the contract exports that bundle everything into a deployable unit, and a shared API class that wraps all contract interactions. ## Contract package: witnesses and exports[​](#contract-package-witnesses-and-exports "Direct link to Contract package: witnesses and exports") The contract package needs two TypeScript files that wire the compiled Compact bindings to your application code. ### Witness provider[​](#witness-provider "Direct link to Witness provider") Create the witness file that provides `localSecretKey` and `getCustomName` to the contract at runtime. ``` touch contract/src/witnesses.ts ``` The `localSecretKey` witness returns the user's secret key from private state. The `getCustomName` witness returns a custom display name. Both return a `[newPrivateState, value]` tuple. ``` export type LeaderboardPrivateState = { readonly secretKey: Uint8Array; }; export const createLeaderboardPrivateState = (secretKey: Uint8Array): LeaderboardPrivateState => ({ secretKey, }); let _customName = new Uint8Array(32); export const setCustomName = (name: string): void => { _customName = new Uint8Array(32); _customName.set(new TextEncoder().encode(name).slice(0, 32)); }; export const createWitnesses = () => ({ localSecretKey: ({ privateState, }: { privateState: LeaderboardPrivateState; }): [LeaderboardPrivateState, Uint8Array] => [privateState, privateState.secretKey], getCustomName: ({ privateState, }: { privateState: LeaderboardPrivateState; }): [LeaderboardPrivateState, Uint8Array] => [privateState, _customName], }); ``` ### Contract exports[​](#contract-exports "Direct link to Contract exports") Create the contract exports file that bundles the contract definition, witnesses, and compiled circuit assets into a single object. ``` touch contract/src/index.ts ``` The key export is `CompiledLeaderboardContract`, which combines the contract definition with its witnesses and compiled circuit file assets. ``` import { CompiledContract } from '@midnight-ntwrk/compact-js'; export * as Leaderboard from '../managed/leaderboard/contract/index.js'; export { createWitnesses, setCustomName, createLeaderboardPrivateState } from './witnesses.js'; export type { LeaderboardPrivateState } from './witnesses.js'; import * as LeaderboardContract from '../managed/leaderboard/contract/index.js'; import { createWitnesses } from './witnesses.js'; export const CompiledLeaderboardContract = CompiledContract.make( 'leaderboard', LeaderboardContract.Contract, ).pipe( CompiledContract.withWitnesses(createWitnesses()), CompiledContract.withCompiledFileAssets('./managed/leaderboard'), ); ``` Build the contract package. ``` cd contract && npm run build && cd .. ``` ## API package[​](#api-package "Direct link to API package") Create the API package directory and its `package.json`. This package wraps all contract interactions in a platform-agnostic `LeaderboardAPI` class. ``` mkdir -p api/src/utils touch api/package.json ``` The API package compiles to `dist/` and exposes its entry point for the UI to import. ``` { "name": "@midnight-ntwrk/leaderboard-api", "version": "0.1.0", "private": true, "type": "module", "module": "./dist/index.js", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "rm -rf dist && tsc --project tsconfig.build.json" } } ``` Create the TypeScript configuration for the API package. It uses the same `"Bundler"` module resolution as the contract package. ``` touch api/tsconfig.json ``` ``` { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "declaration": true, "strict": true, "esModuleInterop": true, "skipLibCheck": true, "outDir": "dist" }, "include": ["src"] } ``` Create the build configuration for the API package. ``` touch api/tsconfig.build.json ``` The build configuration extends the base and excludes test files from the production build. ``` { "extends": "./tsconfig.json", "exclude": ["src/test"] } ``` ### Shared type definitions[​](#shared-type-definitions "Direct link to Shared type definitions") Create the shared type definitions. These define the provider interface that each platform must satisfy, along with the types for leaderboard entries and derived state. ``` touch api/src/common-types.ts ``` `MidnightProviders` represents all of the services a DApp needs: proof generation, state storage, indexer access, wallet operations, and ZK config. The `LeaderboardCircuitKeys` type lists the circuit names from the contract. ``` import { type MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; import { type FoundContract } from '@midnight-ntwrk/midnight-js-contracts'; import { type LeaderboardPrivateState } from '../../contract/src/index'; export const leaderboardPrivateStateKey = 'leaderboardPrivateState'; export type PrivateStateId = typeof leaderboardPrivateStateKey; export type LeaderboardCircuitKeys = 'submitScore' | 'verifyOwnership'; export type LeaderboardProviders = MidnightProviders; export type DeployedLeaderboardContract = FoundContract; export interface LeaderboardEntry { readonly id: number; readonly score: number; readonly displayName: string; readonly ownerHash: string; } export interface LeaderboardDerivedState { readonly entryCount: number; readonly entries: LeaderboardEntry[]; } ``` ### Display name decoder[​](#display-name-decoder "Direct link to Display name decoder") Create the utility that converts raw ledger bytes into human-readable display names. ``` touch api/src/utils/index.ts ``` This converts raw `Bytes<32>` from the ledger into display names. Printable ASCII (custom/public mode) is returned as-is. Non-ASCII (anonymous mode) is converted into a deterministic generated name. ``` const ADJECTIVES = [ 'Crimson', 'Shadow', 'Silver', 'Crystal', 'Golden', 'Ember', 'Frost', 'Storm', 'Iron', 'Cobalt', 'Jade', 'Onyx', 'Scarlet', 'Azure', 'Violet', 'Neon', 'Phantom', 'Rogue', 'Cosmic', 'Lunar', 'Solar', 'Arctic', 'Mystic', 'Nova', 'Stealth', 'Prism', 'Cipher', 'Echo', 'Apex', 'Dusk', 'Blaze', 'Volt', ]; const NOUNS = [ 'Tiger', 'Phoenix', 'Wolf', 'Dragon', 'Falcon', 'Viper', 'Raven', 'Lynx', 'Panther', 'Hawk', 'Cobra', 'Mantis', 'Shark', 'Eagle', 'Jaguar', 'Owl', 'Fox', 'Bear', 'Crane', 'Orca', 'Sphinx', 'Hydra', 'Puma', 'Scorpion', 'Raptor', 'Griffin', 'Coyote', 'Badger', 'Bison', 'Condor', 'Stag', 'Wasp', ]; export const decodeDisplayName = (bytes: Uint8Array, entryId: number, score: number): string => { const decoded = new TextDecoder().decode(bytes).replace(/\0/g, '').trim(); if (decoded.length > 0 && decoded.split('').every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) < 127)) { return decoded; } const h = (bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]) >>> 0; const seed = (h ^ (entryId * 2654435761) ^ (score * 1597334677)) >>> 0; return `${ADJECTIVES[seed % ADJECTIVES.length]} ${NOUNS[(seed >>> 16) % NOUNS.length]}`; }; ``` ### LeaderboardAPI class[​](#leaderboardapi-class "Direct link to LeaderboardAPI class") Create the main API file. The `LeaderboardAPI` class wraps `deployContract` and `findDeployedContract` from `midnight-js-contracts` into a single entry point for all contract operations. ``` touch api/src/index.ts ``` The `submitScore` method conditionally calls `setCustomName` before the transaction. The `!!customName` expression converts the presence of a name into the boolean the contract expects. The `deploy` and `join` methods accept a `secretKey` from the caller rather than generating their own. This lets the browser layer persist the secret across page refreshes. ``` import * as Leaderboard from '../../contract/managed/leaderboard/contract/index.js'; import { type ContractAddress } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { type Logger } from 'pino'; import { type LeaderboardDerivedState, type LeaderboardEntry, type LeaderboardProviders, type DeployedLeaderboardContract, leaderboardPrivateStateKey, } from './common-types.js'; import { CompiledLeaderboardContract, createLeaderboardPrivateState, type LeaderboardPrivateState } from '../../contract/src/index'; import { setCustomName } from '../../contract/src/witnesses.js'; import * as utils from './utils/index.js'; import { deployContract, findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; import { map, type Observable } from 'rxjs'; export class LeaderboardAPI { private constructor( public readonly deployedContract: DeployedLeaderboardContract, providers: LeaderboardProviders, private readonly logger?: Logger, ) { this.deployedContractAddress = deployedContract.deployTxData.public.contractAddress; providers.privateStateProvider.setContractAddress(this.deployedContractAddress); this.state$ = providers.publicDataProvider .contractStateObservable(this.deployedContractAddress, { type: 'latest' }) .pipe( map((contractState) => Leaderboard.ledger(contractState.data)), map((ledgerState): LeaderboardDerivedState => { const entries: LeaderboardEntry[] = []; for (const [key, entry] of ledgerState.scores) { entries.push({ id: Number(key), score: Number(entry.score), displayName: utils.decodeDisplayName(entry.displayName, Number(key), Number(entry.score)), ownerHash: entry.ownerHash.toString(), }); } entries.sort((a, b) => b.score - a.score); return { entryCount: Number(ledgerState.nextId), entries }; }), ); } readonly deployedContractAddress: ContractAddress; readonly state$: Observable; async submitScore(score: number, customName?: string): Promise { if (customName) { setCustomName(customName); } await (this.deployedContract as any).callTx.submitScore(BigInt(score), !!customName); } async verifyOwnership(entryId: number): Promise { await (this.deployedContract as any).callTx.verifyOwnership(BigInt(entryId)); } static async deploy(providers: LeaderboardProviders, secretKey: Uint8Array, logger?: Logger): Promise { const deployedContract = await deployContract(providers as any, { compiledContract: CompiledLeaderboardContract, privateStateId: leaderboardPrivateStateKey, initialPrivateState: createLeaderboardPrivateState(secretKey), }); return new LeaderboardAPI(deployedContract, providers, logger); } static async join(providers: LeaderboardProviders, contractAddress: ContractAddress, secretKey: Uint8Array, logger?: Logger): Promise { const deployedContract = await findDeployedContract(providers as any, { contractAddress, compiledContract: CompiledLeaderboardContract, privateStateId: leaderboardPrivateStateKey, initialPrivateState: createLeaderboardPrivateState(secretKey), }); return new LeaderboardAPI(deployedContract, providers, logger); } } export * as utils from './utils/index.js'; export * from './common-types.js'; ``` Build both packages. ``` npm run build ``` A successful build produces a `dist/` directory in both `contract/` and `api/`. In the next part, you build the React frontend that consumes this API. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Part 3: Browser DApp In this section, you build a React frontend that connects to the Lace wallet and reads leaderboard data from the indexer. The frontend also submits scores on-chain and lets you prove ownership of your entries. ## Set up the UI package[​](#set-up-the-ui-package "Direct link to Set up the UI package") Create the UI workspace directory structure and its `package.json`. ``` mkdir -p leaderboard-ui/src/contexts leaderboard-ui/src/hooks touch leaderboard-ui/package.json ``` The `leaderboard-contract` workspace dependency gives the UI access to the compiled contract bindings. The `dev` script copies circuit keys into `public/` so the browser can fetch them at runtime. ``` { "name": "leaderboard-ui", "version": "0.1.0", "private": true, "type": "module", "scripts": { "dev": "mkdir -p ./public/keys ./public/zkir && cp -r ../contract/managed/leaderboard/keys/* ./public/keys/ && cp -r ../contract/managed/leaderboard/zkir/* ./public/zkir/ && vite", "build": "tsc && vite build --mode preprod && cp -r ../contract/managed/leaderboard/keys ./dist/keys && cp -r ../contract/managed/leaderboard/zkir ./dist/zkir", "preview": "vite preview" }, "dependencies": { "@midnight-ntwrk/dapp-connector-api": "4.0.1", "@midnight-ntwrk/midnight-js-contracts": "4.1.1", "@midnight-ntwrk/midnight-js-fetch-zk-config-provider": "4.1.1", "@midnight-ntwrk/midnight-js-http-client-proof-provider": "4.1.1", "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "4.1.1", "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-types": "4.1.1", "@midnight-ntwrk/midnight-js-utils": "4.1.1", "buffer": "^6.0.3", "fp-ts": "^2.16.11", "leaderboard-contract": "*", "react": "^19.0.0", "react-dom": "^19.0.0", "rxjs": "^7.8.2", "semver": "^7.7.4", "pino": "^10.3.1" }, "devDependencies": { "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@types/semver": "^7.7.1", "@vitejs/plugin-react": "^5.1.4", "typescript": "^5.9.3", "vite": "^7.3.1", "vite-plugin-top-level-await": "^1.6.0", "vite-plugin-wasm": "^3.5.0" } } ``` ## Vite configuration[​](#vite-configuration "Direct link to Vite configuration") The Midnight SDK uses WebAssembly modules for cryptographic operations. Vite needs specific plugins to handle WASM imports in the browser. ``` touch leaderboard-ui/vite.config.ts ``` The Vite configuration enables WebAssembly support, sets up the WASM module resolver for the Midnight runtime, and configures the development server on port 3000. ``` import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import wasm from 'vite-plugin-wasm'; import topLevelAwait from 'vite-plugin-top-level-await'; export default defineConfig({ cacheDir: './.vite', build: { target: 'esnext', minify: false, rollupOptions: { output: { manualChunks: { wasm: ['@midnight-ntwrk/onchain-runtime-v3'], }, }, }, commonjsOptions: { transformMixedEsModules: true, extensions: ['.js', '.cjs'], ignoreDynamicRequires: true, }, }, plugins: [ react(), wasm(), topLevelAwait({ promiseExportName: '__tla', promiseImportName: (i) => `__tla_${i}`, }), { name: 'wasm-module-resolver', resolveId(source, importer) { if ( source === '@midnight-ntwrk/onchain-runtime-v3' && importer && importer.includes('@midnight-ntwrk/compact-runtime') ) { return { id: source, external: false, moduleSideEffects: true }; } return null; }, }, ], optimizeDeps: { esbuildOptions: { target: 'esnext', supported: { 'top-level-await': true }, platform: 'browser', format: 'esm', loader: { '.wasm': 'binary' }, }, include: ['@midnight-ntwrk/compact-runtime'], exclude: [ '@midnight-ntwrk/onchain-runtime-v3', '@midnight-ntwrk/onchain-runtime-v3/midnight_onchain_runtime_wasm_bg.wasm', '@midnight-ntwrk/onchain-runtime-v3/midnight_onchain_runtime_wasm.js', ], }, resolve: { extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.wasm'], mainFields: ['browser', 'module', 'main'], }, server: { port: 3000, open: true }, }); ``` ## TypeScript config[​](#typescript-config "Direct link to TypeScript config") The TypeScript configuration needs `"types": ["vite/client"]` so that `import.meta.env` references compile correctly. Midnight SDK subpath imports require the `"bundler"` module resolution. ``` touch leaderboard-ui/tsconfig.json ``` This configuration targets ES2022 with React JSX transform enabled. ``` { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "types": ["vite/client"] }, "include": ["src"] } ``` ## Environment variables[​](#environment-variables "Direct link to Environment variables") Create the local development environment file. Leave `VITE_DEFAULT_CONTRACT` empty until you deploy a contract in a later step. ``` touch leaderboard-ui/.env ``` Vite loads these variables at build time. Any variable prefixed with `VITE_` is available in the browser via `import.meta.env`. ``` VITE_NETWORK_ID=preprod VITE_INDEXER_URL=https://indexer.preprod.midnight.network/api/v4/graphql VITE_INDEXER_WS_URL=wss://indexer.preprod.midnight.network/api/v4/graphql/ws VITE_DEFAULT_CONTRACT= ``` ## HTML entry point[​](#html-entry-point "Direct link to HTML entry point") Create the HTML shell that Vite uses as the application entry point. The browser loads the `src/main.tsx` script as an ES module. ``` touch leaderboard-ui/index.html ``` Vite transforms this file during development, injecting hot module reload support and resolving the TypeScript entry point. ``` Midnight Leaderboard
``` ## Application entry point[​](#application-entry-point "Direct link to Application entry point") Several Midnight SDK packages use Node.js `Buffer`, which does not exist in the browser. The entry point must polyfill it before any other imports. ``` touch leaderboard-ui/src/main.tsx touch leaderboard-ui/src/App.css ``` The entry point polyfills `Buffer` into the global scope, then mounts the React application. ``` import { Buffer } from 'buffer'; (globalThis as any).Buffer = Buffer; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import App from './App'; import './App.css'; createRoot(document.getElementById('root')!).render( ); ``` ## In-memory private state provider[​](#in-memory-private-state-provider "Direct link to In-memory private state provider") The `midnight-js-contracts` library requires a `PrivateStateProvider`. In the browser, an in-memory implementation is sufficient. ``` touch leaderboard-ui/src/in-memory-private-state-provider.ts ``` The provider stores private state and signing keys in memory, scoped by contract address. It implements the full `PrivateStateProvider` interface including import and export operations. ``` import type { ContractAddress, SigningKey } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import type { ExportPrivateStatesOptions, ExportSigningKeysOptions, ImportPrivateStatesOptions, ImportPrivateStatesResult, ImportSigningKeysOptions, ImportSigningKeysResult, PrivateStateExport, PrivateStateId, PrivateStateProvider, SigningKeyExport, } from '@midnight-ntwrk/midnight-js-types'; export const inMemoryPrivateStateProvider = (): PrivateStateProvider => { const privateStates = new Map>(); const signingKeys = new Map(); let contractAddress: ContractAddress | null = null; const requireContractAddress = (): ContractAddress => { if (contractAddress === null) throw new Error('Contract address not set'); return contractAddress; }; const getScopedStates = (address: ContractAddress): Map => { let scopedStates = privateStates.get(address); if (!scopedStates) { scopedStates = new Map(); privateStates.set(address, scopedStates); } return scopedStates; }; const encode = (value: T): string => JSON.stringify(value); const decode = (value: string): T => JSON.parse(value) as T; return { setContractAddress(address: ContractAddress): void { contractAddress = address; }, set(key: PSI, state: PS): Promise { getScopedStates(requireContractAddress()).set(key, state); return Promise.resolve(); }, get(key: PSI): Promise { return Promise.resolve(getScopedStates(requireContractAddress()).get(key) ?? null); }, remove(key: PSI): Promise { getScopedStates(requireContractAddress()).delete(key); return Promise.resolve(); }, clear(): Promise { privateStates.delete(requireContractAddress()); return Promise.resolve(); }, setSigningKey(addr: ContractAddress, key: SigningKey): Promise { signingKeys.set(addr, key); return Promise.resolve(); }, getSigningKey(addr: ContractAddress): Promise { return Promise.resolve(signingKeys.get(addr) ?? null); }, removeSigningKey(addr: ContractAddress): Promise { signingKeys.delete(addr); return Promise.resolve(); }, clearSigningKeys(): Promise { signingKeys.clear(); return Promise.resolve(); }, exportPrivateStates(_options?: ExportPrivateStatesOptions): Promise { const address = requireContractAddress(); const states = Object.fromEntries( Array.from(getScopedStates(address).entries()).map(([k, v]) => [k, encode(v)]), ); return Promise.resolve({ format: 'midnight-private-state-export', encryptedPayload: encode({ contractAddress: address, states }), salt: 'in-memory', }); }, importPrivateStates(exportData: PrivateStateExport, options?: ImportPrivateStatesOptions): Promise { const address = requireContractAddress(); const strategy = options?.conflictStrategy ?? 'error'; const payload = decode<{ states?: Record }>(exportData.encryptedPayload); const scopedStates = getScopedStates(address); let imported = 0, skipped = 0, overwritten = 0; for (const [rawId, serialized] of Object.entries(payload.states ?? {})) { const id = rawId as PSI; if (scopedStates.has(id)) { if (strategy === 'skip') { skipped++; continue; } if (strategy === 'error') return Promise.reject(new Error(`Conflict: ${id}`)); overwritten++; } else { imported++; } scopedStates.set(id, decode(serialized)); } return Promise.resolve({ imported, skipped, overwritten }); }, exportSigningKeys(_options?: ExportSigningKeysOptions): Promise { return Promise.resolve({ format: 'midnight-signing-key-export', encryptedPayload: encode({ keys: Object.fromEntries(signingKeys.entries()) }), salt: 'in-memory', }); }, importSigningKeys(exportData: SigningKeyExport, options?: ImportSigningKeysOptions): Promise { const strategy = options?.conflictStrategy ?? 'error'; const payload = decode<{ keys?: Record }>(exportData.encryptedPayload); let imported = 0, skipped = 0, overwritten = 0; for (const [addr, key] of Object.entries(payload.keys ?? {})) { if (signingKeys.has(addr)) { if (strategy === 'skip') { skipped++; continue; } if (strategy === 'error') return Promise.reject(new Error(`Conflict: ${addr}`)); overwritten++; } else { imported++; } signingKeys.set(addr, key); } return Promise.resolve({ imported, skipped, overwritten }); }, }; }; ``` ## Read on-chain state[​](#read-on-chain-state "Direct link to Read on-chain state") This hook queries the Midnight indexer directly via GraphQL, deserializes the contract state, and parses it using the compiled contract's `ledger()` function. It imports `decodeDisplayName` from the API utils created in Part 2 to convert raw `Bytes<32>` into readable names. It auto-refreshes every 15 seconds and requires no wallet connection. ``` touch leaderboard-ui/src/hooks/useLeaderboard.ts ``` The hook fetches contract state from the indexer, deserializes it using the compiled contract's `ledger()` function, and returns a sorted list of entries. ``` import { useState, useEffect, useCallback } from 'react'; import { ContractState } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { Leaderboard } from 'leaderboard-contract'; import { decodeDisplayName } from '../../../api/src/utils/index.js'; const INDEXER_URL = import.meta.env.VITE_INDEXER_URL ?? 'https://indexer.preprod.midnight.network/api/v4/graphql'; const CONTRACT_STATE_QUERY = ` query ContractState($address: HexEncoded!) { contractAction(address: $address) { state } } `; export interface LeaderboardEntry { id: number; score: number; displayName: string; ownerHash: string; } function hexToBytes(hex: string): Uint8Array { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) { bytes[i / 2] = parseInt(hex.substr(i, 2), 16); } return bytes; } export function useLeaderboard(contractAddress: string | null, refreshInterval = 15_000) { const [entries, setEntries] = useState([]); const [entryCount, setEntryCount] = useState(0); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const fetchLeaderboard = useCallback(async () => { if (!contractAddress || !/^[0-9a-fA-F]{64}$/.test(contractAddress)) return; try { setLoading(true); const res = await fetch(INDEXER_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: CONTRACT_STATE_QUERY, variables: { address: contractAddress } }), }); const gql = await res.json(); if (gql.errors) throw new Error(gql.errors[0]?.message ?? 'Indexer query failed'); const stateHex = gql.data?.contractAction?.state; if (!stateHex) throw new Error('Contract not found'); const contractState = ContractState.deserialize(hexToBytes(stateHex)); const ledgerState = Leaderboard.ledger(contractState.data); const parsed: LeaderboardEntry[] = []; for (const [key, entry] of ledgerState.scores) { parsed.push({ id: Number(key), score: Number(entry.score), displayName: decodeDisplayName(entry.displayName, Number(key), Number(entry.score)), ownerHash: entry.ownerHash.toString(), }); } parsed.sort((a, b) => b.score - a.score); setEntries(parsed); setEntryCount(Number(ledgerState.nextId)); setError(null); } catch (e: any) { setError(e.message); } finally { setLoading(false); } }, [contractAddress]); useEffect(() => { fetchLeaderboard(); }, [fetchLeaderboard]); useEffect(() => { if (!contractAddress) return; const interval = setInterval(fetchLeaderboard, refreshInterval); return () => clearInterval(interval); }, [contractAddress, refreshInterval, fetchLeaderboard]); return { entries, entryCount, loading, error, refresh: fetchLeaderboard }; } ``` ## Wallet bridge[​](#wallet-bridge "Direct link to Wallet bridge") The `BrowserLeaderboardManager` connects to the Lace wallet via the DApp Connector API, initializes all providers, and delegates contract operations to the `LeaderboardAPI`. The manager generates a random 32-byte secret key on first use and stores it in `localStorage`. On subsequent visits, it retrieves the same key. This ensures that ownership verification works even after the page is refreshed or the browser is restarted. The `walletProvider.balanceTx` method bridges the DApp and your wallet. The DApp builds an unbalanced transaction with the contract circuit proof and sends it to Lace for balancing. Lace adds DUST fees and Zswap proofs, then returns a finalized transaction ready to submit. Call `setNetworkId()` before initializing any providers. ``` touch leaderboard-ui/src/contexts/BrowserLeaderboardManager.ts ``` The manager class handles wallet connection, provider initialization, secret key persistence, and contract deployment or joining. ``` import { LeaderboardAPI, type LeaderboardCircuitKeys, type LeaderboardProviders } from '../../../api/src/index'; import { type ContractAddress, fromHex, toHex } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { BehaviorSubject, catchError, concatMap, filter, firstValueFrom, interval, map, type Observable, take, throwError, timeout } from 'rxjs'; import { pipe as fnPipe } from 'fp-ts/function'; import { type Logger } from 'pino'; import { type ConnectedAPI, type InitialAPI } from '@midnight-ntwrk/dapp-connector-api'; import { FetchZkConfigProvider } from '@midnight-ntwrk/midnight-js-fetch-zk-config-provider'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import semver from 'semver'; import { Binding, type FinalizedTransaction, Proof, SignatureEnabled, Transaction, type TransactionId } from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { type LeaderboardPrivateState } from 'leaderboard-contract'; import { inMemoryPrivateStateProvider } from '../in-memory-private-state-provider'; import { type NetworkId, setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import type { UnboundTransaction } from '@midnight-ntwrk/midnight-js-types'; export type LeaderboardDeployment = | { readonly status: 'in-progress' } | { readonly status: 'deployed'; readonly api: LeaderboardAPI } | { readonly status: 'failed'; readonly error: Error }; export class BrowserLeaderboardManager { readonly #deploymentsSubject = new BehaviorSubject>>([]); #initializedProviders: Promise | undefined; constructor(private readonly logger: Logger) {} readonly deployments$: Observable>> = this.#deploymentsSubject; resolve(contractAddress?: ContractAddress): Observable { const deployments = this.#deploymentsSubject.value; const existing = deployments.find( (d) => d.value.status === 'deployed' && d.value.api.deployedContractAddress === contractAddress, ); if (existing) return existing; const secretKey = this.getSecretKey(); const deployment = new BehaviorSubject({ status: 'in-progress' }); if (contractAddress) { void this.run(deployment, (providers) => LeaderboardAPI.join(providers, contractAddress, secretKey, this.logger)); } else { void this.run(deployment, (providers) => LeaderboardAPI.deploy(providers, secretKey, this.logger)); } this.#deploymentsSubject.next([...deployments, deployment]); return deployment; } private getSecretKey(): Uint8Array { const storageKey = 'midnight-leaderboard-secret'; const stored = localStorage.getItem(storageKey); if (stored) { return Uint8Array.from(atob(stored), (c) => c.charCodeAt(0)); } const secret = crypto.getRandomValues(new Uint8Array(32)); localStorage.setItem(storageKey, btoa(String.fromCharCode(...secret))); return secret; } private getProviders(): Promise { return this.#initializedProviders ?? (this.#initializedProviders = initializeProviders(this.logger)); } private async run( deployment: BehaviorSubject, factory: (providers: LeaderboardProviders) => Promise, ): Promise { try { const providers = await this.getProviders(); const api = await factory(providers); deployment.next({ status: 'deployed', api }); } catch (error: unknown) { console.error('Contract operation failed:', error); let err: Error; if (error instanceof Error) { err = error; } else if (typeof error === 'string') { err = new Error(error); } else { err = new Error(JSON.stringify(error) || 'Unknown error during contract operation'); } deployment.next({ status: 'failed', error: err }); } } } const COMPATIBLE_CONNECTOR_API_VERSION = '4.x'; const initializeProviders = async (logger: Logger): Promise => { const networkId = import.meta.env.VITE_NETWORK_ID as NetworkId; setNetworkId(networkId); const connectedAPI = await connectToWallet(logger, networkId); const config = await connectedAPI.getConfiguration(); const proofServerUri = config.proverServerUri!; const shieldedAddresses = await connectedAPI.getShieldedAddresses(); const zkConfigProvider = new FetchZkConfigProvider(window.location.origin, fetch.bind(window)); return { privateStateProvider: inMemoryPrivateStateProvider(), zkConfigProvider, proofProvider: httpClientProofProvider(proofServerUri, zkConfigProvider), publicDataProvider: indexerPublicDataProvider(config.indexerUri, config.indexerWsUri), walletProvider: { getCoinPublicKey: () => shieldedAddresses.shieldedCoinPublicKey, getEncryptionPublicKey: () => shieldedAddresses.shieldedEncryptionPublicKey, balanceTx: async (tx: UnboundTransaction): Promise => { const received = await connectedAPI.balanceUnsealedTransaction(toHex(tx.serialize())); return Transaction.deserialize('signature', 'proof', 'binding', fromHex(received.tx)); }, }, midnightProvider: { submitTx: async (tx: FinalizedTransaction): Promise => { await connectedAPI.submitTransaction(toHex(tx.serialize())); return tx.identifiers()[0]; }, }, }; }; const getFirstCompatibleWallet = (): InitialAPI | undefined => { if (!window.midnight) return undefined; return Object.values(window.midnight).find( (wallet): wallet is InitialAPI => !!wallet && typeof wallet === 'object' && 'apiVersion' in wallet && semver.satisfies(wallet.apiVersion, COMPATIBLE_CONNECTOR_API_VERSION), ); }; const connectToWallet = (logger: Logger, networkId: string): Promise => firstValueFrom( fnPipe( interval(100), map(() => getFirstCompatibleWallet()), filter((api): api is InitialAPI => !!api), take(1), timeout({ first: 3_000, with: () => throwError(() => new Error('Could not find Midnight Lace wallet.')) }), concatMap(async (initialAPI) => initialAPI.connect(networkId)), timeout({ first: 5_000, with: () => throwError(() => new Error('Lace wallet failed to respond.')) }), catchError((error) => throwError(() => error instanceof Error ? error : new Error('Wallet not authorized'))), ), ); ``` ## Application component[​](#application-component "Direct link to Application component") The `App.tsx` component ties everything together: wallet detection, the click challenge game, score submission with privacy mode selection, leaderboard display, and ownership verification. The three UI privacy modes map to two contract paths. Anonymous sends `undefined` as the custom name, triggering the contract's `else` branch which stores a hash as the display name. Public and Custom both send a string through the witness (the wallet address or a user-typed name), triggering the contract's `if` branch. Ownership verification calls `verifyOwnership` on the API and tracks verified entries in local React state. If the caller is not the owner, then the contract's `assert` fails and the network rejects the transaction. ``` touch leaderboard-ui/src/App.tsx ``` The component uses a shared `BrowserLeaderboardManager` instance via `useRef` to ensure the same secret key and providers are used across all contract operations within a session. ``` import { useState, useEffect, useCallback, useRef } from 'react'; import type { InitialAPI, ConnectedAPI } from '@midnight-ntwrk/dapp-connector-api'; import { useLeaderboard } from './hooks/useLeaderboard'; import { BrowserLeaderboardManager } from './contexts/BrowserLeaderboardManager'; import pino from 'pino'; const NETWORK_ID = import.meta.env.VITE_NETWORK_ID ?? 'preprod'; const DEFAULT_CONTRACT = import.meta.env.VITE_DEFAULT_CONTRACT ?? ''; enum DisplayMode { PUBLIC = 0, ANONYMOUS = 1, CUSTOM = 2 } type WalletState = 'detecting' | 'no-wallet' | 'ready' | 'connecting' | 'connected'; function findWallet(): InitialAPI | undefined { const midnight = (window as any).midnight; if (!midnight) return undefined; return Object.values(midnight).find( (w): w is InitialAPI => !!w && typeof w === 'object' && 'apiVersion' in w, ); } function truncAddr(addr: string): string { return addr.length <= 24 ? addr : `${addr.slice(0, 14)}...${addr.slice(-8)}`; } function friendlyError(e: any): string { const msg = extractErrorMessage(e); if (msg.includes('User rejected')) return 'Transaction cancelled.'; if (msg.includes('not the owner')) return 'This entry does not belong to your wallet.'; if (msg.includes('entry not found')) return 'Entry not found on the leaderboard.'; if (msg.includes('Failed to fetch') || msg.includes('Failed Proof Server')) return 'Could not reach the proof server. Check your connection and try again.'; if (msg.includes('mismatched verifier keys')) return 'Contract version mismatch. Try deploying a new leaderboard.'; if (msg.includes('submission') || msg.includes('Submission')) return 'Transaction failed to submit. Please try again.'; return msg || 'An unexpected error occurred. Check the browser console for details.'; } function extractErrorMessage(e: any): string { if (!e) return ''; if (e.message && e.message !== '') return e.message; const failure = e?.cause?.failure; if (failure?.message) return failure.message; if (failure?.cause?.message) return failure.cause.message; if (e?.cause?.message) return e.cause.message; try { return JSON.stringify(e); } catch { return String(e); } } export default function App() { const [walletState, setWalletState] = useState('detecting'); const [walletAPI, setWalletAPI] = useState(); const [wallet, setWallet] = useState(null); const [address, setAddress] = useState(null); const [error, setError] = useState(null); const [contractAddress, setContractAddress] = useState(DEFAULT_CONTRACT); const [joinInput, setJoinInput] = useState(''); const [showJoinPanel, setShowJoinPanel] = useState(false); const [deploying, setDeploying] = useState(false); const [clicks, setClicks] = useState(0); const [isPlaying, setIsPlaying] = useState(false); const [timeLeft, setTimeLeft] = useState(10); const [showResult, setShowResult] = useState(false); const [lastScore, setLastScore] = useState(0); const timerRef = useRef | null>(null); const clickRef = useRef(0); const [displayMode, setDisplayMode] = useState(DisplayMode.ANONYMOUS); const [customName, setCustomName] = useState(''); const [submitting, setSubmitting] = useState(false); const [submitStatus, setSubmitStatus] = useState(null); const [verifyingId, setVerifyingId] = useState(null); const [verifiedIds, setVerifiedIds] = useState>(new Set()); const managerRef = useRef(null); const getManager = useCallback(() => { if (!managerRef.current) { const logger = pino({ level: 'warn', browser: { asObject: true } }); managerRef.current = new BrowserLeaderboardManager(logger); } return managerRef.current; }, []); const { entries: leaderboardEntries, refresh: refreshLeaderboard } = useLeaderboard(contractAddress || null); const leaderboard = leaderboardEntries.map((e, i) => ({ rank: i + 1, id: e.id, displayName: e.displayName, score: BigInt(e.score), })); // Wallet detection: poll for Lace extension useEffect(() => { const found = findWallet(); if (found) { setWalletAPI(found); setWalletState('ready'); return; } let elapsed = 0; const t = setInterval(() => { elapsed += 100; const w = findWallet(); if (w) { setWalletAPI(w); setWalletState('ready'); clearInterval(t); } else if (elapsed >= 5_000) { setWalletState('no-wallet'); clearInterval(t); } }, 100); return () => clearInterval(t); }, []); const connect = useCallback(async () => { if (!walletAPI) return; setWalletState('connecting'); setError(null); try { const c = await walletAPI.connect(NETWORK_ID); setWallet(c); const { unshieldedAddress } = await c.getUnshieldedAddress(); setAddress(unshieldedAddress); setWalletState('connected'); } catch (e) { setError(friendlyError(e)); setWalletState('ready'); } }, [walletAPI]); // Helper to resolve a contract (deploy or join) const resolveContract = useCallback(async (addr?: any) => { const manager = getManager(); const deployment$ = manager.resolve(addr); return new Promise((resolve, reject) => { const sub = deployment$.subscribe((d) => { if (d.status === 'deployed') { Promise.resolve().then(() => sub.unsubscribe()); resolve(d); } if (d.status === 'failed') { Promise.resolve().then(() => sub.unsubscribe()); reject(d.error); } }); }); }, [getManager]); const deployContract = useCallback(async () => { if (!wallet) return; setDeploying(true); setError(null); try { const result = await resolveContract(); setContractAddress(result.api.deployedContractAddress); setShowJoinPanel(false); setClicks(0); setShowResult(false); } catch (e: any) { setError(friendlyError(e)); } finally { setDeploying(false); } }, [wallet, resolveContract]); const joinContract = useCallback(() => { const addr = joinInput.trim(); if (!addr || !/^[0-9a-fA-F]{64}$/.test(addr)) { setError('Invalid contract address. Must be 64 hex characters.'); return; } setContractAddress(addr); setShowJoinPanel(false); setJoinInput(''); }, [joinInput]); // Game logic const startGame = useCallback(() => { setClicks(0); clickRef.current = 0; setTimeLeft(10); setIsPlaying(true); setShowResult(false); timerRef.current = setInterval(() => { setTimeLeft(prev => { if (prev <= 1) { clearInterval(timerRef.current!); setIsPlaying(false); setShowResult(true); setLastScore(clickRef.current); return 0; } return prev - 1; }); }, 1_000); }, []); const handleClick = useCallback(() => { if (!isPlaying) return; clickRef.current += 1; setClicks(clickRef.current); }, [isPlaying]); useEffect(() => () => { if (timerRef.current) clearInterval(timerRef.current); }, []); // Submit score const submitScore = useCallback(async () => { if (lastScore === 0 || !wallet) return; setSubmitting(true); setSubmitStatus('Joining contract...'); setError(null); try { const result = await resolveContract(contractAddress as any); setSubmitStatus('Generating proof & submitting...'); const name = displayMode === DisplayMode.PUBLIC ? address!.slice(0, 12) + '..' + address!.slice(-12) : displayMode === DisplayMode.CUSTOM ? customName : undefined; await result.api.submitScore(lastScore, name); setSubmitting(false); setSubmitStatus(null); setShowResult(false); setLastScore(0); setTimeout(() => refreshLeaderboard(), 3000); } catch (e: any) { setSubmitting(false); setSubmitStatus(null); setError(friendlyError(e)); } }, [wallet, lastScore, displayMode, customName, contractAddress, refreshLeaderboard, address, resolveContract]); // Verify ownership const verifyEntry = useCallback(async (entryId: number) => { if (!wallet) return; setVerifyingId(entryId); setError(null); try { const result = await resolveContract(contractAddress as any); await result.api.verifyOwnership(entryId); setVerifiedIds(prev => new Set(prev).add(entryId)); } catch (e: any) { setError(friendlyError(e)); } finally { setVerifyingId(null); } }, [wallet, contractAddress, resolveContract]); const isConnected = walletState === 'connected'; return (

Midnight Leaderboard

{walletState === 'no-wallet' ? (
Install Lace Wallet ) : isConnected && address ? (

Connected: {truncAddr(address)}

) : ( )} {error &&

{error}

}

Contract: {truncAddr(contractAddress)}

{showJoinPanel && (
setJoinInput(e.target.value)} /> {isConnected ? ( ) : ( )}
)}

Click Challenge

Time: {isPlaying ? timeLeft : 10}s | Clicks: {clicks}

{isPlaying && ( )} {!isPlaying && !showResult && ( )} {lastScore > 0 && !isPlaying && (
{([[DisplayMode.ANONYMOUS, 'Anonymous'], [DisplayMode.PUBLIC, 'Public'], [DisplayMode.CUSTOM, 'Custom']] as const).map(([m, label]) => ( ))}
{displayMode === DisplayMode.CUSTOM && ( setCustomName(e.target.value)} /> )} {isConnected ? ( ) : ( )}
)}

Leaderboard ({leaderboard.length} entries)

{leaderboard.length === 0 ? (

No scores yet.

) : ( {leaderboard.map(e => ( ))}
#PlayerScore
{e.rank} {e.displayName} {verifiedIds.has(e.id) && ✓ yours} {Number(e.score).toLocaleString()} {isConnected && !verifiedIds.has(e.id) && ( )}
)}
); } ``` ## Install and run[​](#install-and-run "Direct link to Install and run") Reinstall dependencies to pick up the new workspace. ``` npm install ``` Start the proof server. ``` docker run -d -p 6300:6300 midnightntwrk/proof-server:8.0.3 -- midnight-proof-server --network preprod ``` Start the dev server. ``` cd leaderboard-ui npm run dev ``` Open `http://localhost:3000` in Chrome with Lace installed. The leaderboard loads from the indexer immediately. ## Deploy a contract[​](#deploy-a-contract "Direct link to Deploy a contract") Before you can submit scores, you need a deployed contract. Connect your wallet, then click **Switch Contract** and **Deploy New**. This creates a new leaderboard contract on Preprod and copies the address to your clipboard. Update `VITE_DEFAULT_CONTRACT` in your `.env` file with the new contract address, then restart the dev server so it loads automatically on future visits. tDUST required Deploying a contract requires tDUST in your wallet. If you see a transaction submission error, open Lace, go to the Tokens tab, and click **Generate tDUST**. Once deployed, play the click challenge, choose a privacy mode, and submit your score to the chain. ## Next steps[​](#next-steps "Direct link to Next steps") With the DApp running locally, you can move on to [Production deployment](/tutorials/leaderboard/deployment.md) to deploy the frontend to Vercel. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Part 4: Production deployment In this section, you deploy the leaderboard frontend to Vercel. ## Vercel build configuration[​](#vercel-build-configuration "Direct link to Vercel build configuration") Create the Vercel build configuration. This tells Vercel how to build the monorepo: it compiles the contract and API packages first, then builds the Vite frontend. ``` touch vercel.json ``` The `buildCommand` chains the TypeScript compilation for each workspace package. The `outputDirectory` points to the Vite build output. ``` { "buildCommand": "cd contract && npm run build && cd ../api && npm run build && cd ../leaderboard-ui && npm run build", "outputDirectory": "leaderboard-ui/dist", "installCommand": "npm install", "framework": null } ``` ### Compiled contract output[​](#compiled-contract-output "Direct link to Compiled contract output") Vercel does not have the Compact compiler installed. Make sure `contract/managed/` is not in your `.gitignore` so your push to GitHub includes the compiled circuit keys and TypeScript bindings. ### Production environment file[​](#production-environment-file "Direct link to Production environment file") Create the production environment file with your deployed contract address. ``` touch leaderboard-ui/.env.preprod ``` The `leaderboard-ui` build script runs `vite build --mode preprod`, which loads `.env.preprod` instead of `.env`. ``` VITE_NETWORK_ID=preprod VITE_INDEXER_URL=https://indexer.preprod.midnight.network/api/v4/graphql VITE_INDEXER_WS_URL=wss://indexer.preprod.midnight.network/api/v4/graphql/ws VITE_DEFAULT_CONTRACT= ``` ### Deploy to Vercel[​](#deploy-to-vercel "Direct link to Deploy to Vercel") Import the repository and deploy it from the Vercel dashboard. 1. Go to [vercel.com](https://vercel.com) and sign in with GitHub. 2. Click **Add New Project** and import your repository. 3. Make sure the **Root Directory** setting is empty (not set to a subdirectory). 4. Click **Deploy**. ## Test the production deployment[​](#test-the-production-deployment "Direct link to Test the production deployment") Visit your Vercel URL in Chrome with Lace installed. The leaderboard loads from the indexer. Connect your wallet and submit a score to verify the full pipeline works end to end. ## Summary[​](#summary "Direct link to Summary") The production stack relies on the following services. | Component | Service | | --------------------------- | ---------------------- | | Frontend | Vercel | | Chain and indexer | Midnight Preprod | | Wallet and proof generation | Lace browser extension | | Test tokens | Preprod faucet | This architecture scales to any Midnight DApp. The contract defines the on-chain logic. The API layer wraps it for TypeScript consumption. The frontend connects via Lace, and the wallet's proof server handles proof generation. --- > For the complete documentation index, see [llms.txt](/llms.txt) # Build a privacy-preserving leaderboard DApp This tutorial walks you through building a full-stack DApp on the Midnight Network. You write a Compact smart contract, integrate it with TypeScript, build a browser-based frontend with Lace wallet support, and deploy the finished application to production. By the end, you have a working arcade-style leaderboard where players submit scores with privacy controls and prove ownership of entries using zero-knowledge proofs. ## What you learn[​](#what-you-learn "Direct link to What you learn") This tutorial covers four areas of Midnight DApp development. ### Smart contract (Compact)[​](#smart-contract-compact "Direct link to Smart contract (Compact)") * Define structured on-chain data with `Map`, `Counter`, and custom structs. * Control what data goes on-chain with `disclose()`. * Use witnesses to feed private data into ZK circuits on demand. * Use `assert` to enforce ownership checks. * Hash with `persistentHash` for anonymous identity. ### TypeScript integration[​](#typescript-integration "Direct link to TypeScript integration") * Compile Compact contracts and work with the generated TypeScript bindings. * Build a platform-agnostic API layer with `midnight-js-contracts`. * Create witness providers that bridge private data into the circuit. ### Browser DApp[​](#browser-dapp "Direct link to Browser DApp") * Connect to the Lace wallet via the DApp Connector API. * Initialize providers for proof generation, indexer access, wallet operations, and ZK config. * Read on-chain state directly from the indexer without a wallet. * Submit transactions through the browser with ZK proof generation. ### Production deployment[​](#production-deployment "Direct link to Production deployment") * Deploy the frontend to Vercel. * Configure environment variables for different networks. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") You need the following tools installed before starting. * [Node.js v22+](https://nodejs.org/) (use `nvm install 22` if needed). * [Compact toolchain](https://docs.midnight.network/getting-started/installation#install-compact). * [Docker](https://docs.docker.com/desktop/) (for the local proof server). * [Lace wallet](https://chromewebstore.google.com/detail/lace/gafhhkghbfjjkeiendhlofajokpaflmk) browser extension. ### Wallet setup[​](#wallet-setup "Direct link to Wallet setup") 1. Install the Lace extension and create a new wallet. 2. Set the network to **Preprod**. 3. Set the proof server to `http://localhost:6300`. 4. Fund your wallet with tNIGHT from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/). 5. Go to Tokens, click **Generate tDUST**, and confirm the transaction. > **Note:** tDUST is required to pay transaction fees on Preprod. It is generated from your tNIGHT balance. ## Project structure[​](#project-structure "Direct link to Project structure") The finished project has three workspace packages and a Docker configuration for the proof server. ``` midnight-leaderboard/ ├── contract/ # Compact smart contract + TypeScript bindings │ ├── leaderboard.compact │ ├── src/ │ │ ├── index.ts # Compiled contract exports + witness wiring │ │ └── witnesses.ts # Witness provider │ └── managed/ # Compiler output ├── api/ # Shared business logic (platform-agnostic) │ └── src/ │ ├── index.ts # LeaderboardAPI class │ ├── common-types.ts │ └── utils/index.ts ├── leaderboard-ui/ # React + Vite browser DApp │ └── src/ │ ├── App.tsx # Game UI + leaderboard + wallet connection │ ├── main.tsx # Entry point with Buffer polyfill │ ├── contexts/ # Lace wallet provider bridge │ └── hooks/ # Indexer read hook ├── proof-server/ # Docker config for the local proof server │ └── Dockerfile ├── vercel.json # Frontend deployment config └── package.json # Workspace root ``` ## Tutorial sections[​](#tutorial-sections "Direct link to Tutorial sections") Each part builds on the previous one. Complete them in order. | Section | What you build | | --------------------------------------------------------------------- | ------------------------------------------------------------------------- | | [Part 1: Smart contract](/tutorials/leaderboard/smart-contract.md) | Write the Compact contract with privacy modes and ownership verification. | | [Part 2: TypeScript integration](/tutorials/leaderboard/api-layer.md) | Set up the contract package, witnesses, and shared API layer. | | [Part 3: Browser DApp](/tutorials/leaderboard/browser-dapp.md) | Build the React frontend with Lace wallet and indexer reads. | | [Part 4: Production deployment](/tutorials/leaderboard/deployment.md) | Deploy the frontend to Vercel. | --- > For the complete documentation index, see [llms.txt](/llms.txt) # Part 1: The smart contract In this section, you write the Compact smart contract that powers the leaderboard. ## Initialize the project[​](#initialize-the-project "Direct link to Initialize the project") Create the project directory, then set up the root `package.json` with workspace configuration and Midnight SDK dependencies. ``` mkdir midnight-leaderboard cd midnight-leaderboard touch package.json ``` This configures npm workspaces and includes all Midnight SDK dependencies. ``` { "name": "midnight-leaderboard", "version": "0.1.0", "private": true, "type": "module", "workspaces": ["contract", "api", "leaderboard-ui"], "scripts": { "compile": "cd contract && npm run compact", "build": "cd contract && npm run build && cd ../api && npm run build" }, "devDependencies": { "@vitejs/plugin-react": "^5.1.4", "typescript": "^5.9.3", "vite": "^7.3.1", "vite-plugin-top-level-await": "^1.6.0", "vite-plugin-wasm": "^3.5.0" }, "dependencies": { "@midnight-ntwrk/compact-js": "2.5.1", "@midnight-ntwrk/dapp-connector-api": "4.0.1", "@midnight-ntwrk/midnight-js-contracts": "4.1.1", "@midnight-ntwrk/midnight-js-fetch-zk-config-provider": "4.1.1", "@midnight-ntwrk/midnight-js-http-client-proof-provider": "4.1.1", "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "4.1.1", "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-types": "4.1.1", "@midnight-ntwrk/midnight-js-utils": "4.1.1", "fp-ts": "^2.16.11", "graphql": "^16.11.0", "effect": "^3.14.0", "pino": "^10.3.1", "rxjs": "^7.8.2", "semver": "^7.7.4" }, "overrides": { "smoldot": "npm:@aspect-build/empty@0.0.0" } } ``` Create the contract directory structure and its `package.json`, which defines the compile and build scripts for the Compact contract. ``` mkdir -p contract/src touch contract/package.json ``` The `compact` script invokes the Compact compiler. The `build` script compiles TypeScript and copies the managed output into `dist/`. ``` { "name": "leaderboard-contract", "version": "0.1.0", "private": true, "type": "module", "main": "dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "default": "./dist/index.js" } }, "scripts": { "compact": "compact compile leaderboard.compact managed/leaderboard", "build": "rm -rf dist && tsc --project tsconfig.build.json && cp -Rf ./managed ./dist/managed" } } ``` The witnesses use `TextEncoder`, which requires the `"DOM"` lib entry. The `compact-js` subpath exports require `"Bundler"` module resolution. The `"types": []` prevents TypeScript from automatically including type definitions from the monorepo root that belong to other packages. ``` touch contract/tsconfig.build.json ``` This TypeScript configuration targets ES2022 and outputs declaration files alongside the compiled JavaScript. ``` { "compilerOptions": { "outDir": "dist", "declaration": true, "lib": ["ESNext", "DOM"], "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "allowJs": true, "strict": true, "isolatedModules": true, "sourceMap": true, "esModuleInterop": true, "skipLibCheck": true, "types": [] }, "include": ["src"] } ``` ## Write the contract[​](#write-the-contract "Direct link to Write the contract") Create the contract source file. This file contains the entire Compact smart contract. ``` touch contract/leaderboard.compact ``` The contract defines a `ScoreEntry` struct stored in a `Map` keyed by an auto-incrementing counter. A `witness` function lets the frontend feed private data into the circuit on demand. ``` pragma language_version 0.23; import CompactStandardLibrary; struct ScoreEntry { score: Uint<64>, displayName: Bytes<32>, ownerHash: Bytes<32> } export ledger scores: Map, ScoreEntry>; export ledger nextId: Counter; witness localSecretKey(): Bytes<32>; witness getCustomName(): Bytes<32>; ``` `scores` is a public ledger field readable from the indexer. `nextId` auto-increments to assign unique entry IDs. The two `witness` declarations tell the compiler that the TypeScript host provides `localSecretKey` and `getCustomName` at runtime. `localSecretKey` returns a random secret stored in the user's private state. `getCustomName` returns a custom display name. ### ownerCommitment[​](#ownercommitment "Direct link to ownerCommitment") This helper circuit derives an on-chain identity from the user's secret key. It hashes the secret with a domain separator using `persistentHash`, producing a deterministic commitment that can be stored on the ledger and verified later without revealing the secret. ``` export circuit ownerCommitment(sk: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "leaderboard:owner:"), sk]); } ``` ### submitScore[​](#submitscore "Direct link to submitScore") The main circuit creates a new leaderboard entry with the caller's score, display name, and owner commitment. ``` export circuit submitScore( score: Uint<64>, useCustomName: Boolean ): [] { const sk = localSecretKey(); const ownerHash = ownerCommitment(sk); nextId.increment(1); const entryId = disclose(nextId.read() as Uint<64>); if (disclose(useCustomName)) { const customName = getCustomName(); scores.insert(entryId, ScoreEntry { score: disclose(score), displayName: disclose(customName), ownerHash: disclose(ownerHash) }); } else { scores.insert(entryId, ScoreEntry { score: disclose(score), displayName: disclose(persistentHash>(sk)), ownerHash: disclose(ownerHash) }); } } ``` `localSecretKey()` calls the witness to retrieve the user's secret from private state. The secret never leaves the user's machine and never appears on-chain. `ownerCommitment(sk)` hashes the secret with a domain separator to produce a deterministic identity. The domain separator `"leaderboard:owner:"` ensures this hash cannot collide with hashes used for other purposes. `disclose()` marks data as safe to store publicly on-chain. Every value in a ledger write must be disclosed. The `if/else` branch controls what gets stored as the display name. When `useCustomName` is true, the contract calls the `getCustomName()` witness to retrieve a name from the TypeScript host. The application layer uses this for both custom-named and public-address submissions, deciding which value to feed through the witness. When `useCustomName` is false, the contract does not invoke a witness and sets the display name to `persistentHash(sk)`. This produces raw hash bytes that the UI renders as a generated name like "Crimson Tiger." ### verifyOwnership[​](#verifyownership "Direct link to verifyOwnership") The verification circuit lets a user prove they own a leaderboard entry without revealing their secret key. ``` export circuit verifyOwnership(targetEntryId: Uint<64>): [] { assert(scores.member(disclose(targetEntryId)), "entry not found"); const entry = scores.lookup(disclose(targetEntryId)); const callerHash = ownerCommitment(localSecretKey()); assert(callerHash == entry.ownerHash, "not the owner"); } ``` The caller proves that `ownerCommitment(theirSecretKey)` matches the `ownerHash` stored in the entry. The secret key never leaves the user's machine. The proof server generates the proof locally. You can use it to claim a prize, verify identity, or present to a badge system. It does not write anything to the ledger. ## Compile the contract[​](#compile-the-contract "Direct link to Compile the contract") Install the project dependencies and compile the contract. The compiler generates TypeScript bindings, circuit keys, and ZKIR files in `contract/managed/leaderboard/`. ``` npm install npm run compile ``` Expected output: ``` Compiling 2 circuits: circuit "submitScore" (k=13, rows=4720) circuit "verifyOwnership" (k=13, rows=2352) ``` --- > For the complete documentation index, see [llms.txt](/llms.txt) # Private party tutorial Write a Compact contract that demonstrates the privacy boundary in Midnight, including Unshielded tokens, then run a test suite to verify it on a local devnet. [✦](/tutorials/private-party/smart-contract.md) ### [Private party contract](/tutorials/private-party/smart-contract.md) [Build a privacy application that demonstrates the privacy boundary in Midnight DApps.](/tutorials/private-party/smart-contract.md) [Write the contract→](/tutorials/private-party/smart-contract.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Private party contract The private party tutorial is a beginner-level demonstration of the following features: * Unshielded token send/receive (NIGHT) * The privacy boundary * persistentCommit * DApp-specific public keys It has two main components: 1. Compact contract 2. Test script This tutorial demonstrates writing safe and secure Compact contracts with no witnesses and private data, and verifying the contract's operation with MidnightJS in a local devnet test script. Write each code block by hand rather than copying and pasting code. The focus in this tutorial is on Compact, the test script is provided. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") Before you begin this tutorial, ensure you have: * [Installed the toolchain](/getting-started/installation.md) * Node.js v22+ ## Problem analysis[​](#problem-analysis "Direct link to Problem analysis") The private party contract lets the party organizer collect RSVP notifications while maintaining attendee privacy up to a specific boundary, where attendees then become public. This tutorial refers to this as the "privacy boundary," an important element to understand when developing Midnight DApps. In this example, paying the entry fee in Unshielded NIGHT tokens crosses the privacy boundary. In Compact, privacy is the default and you as the DApp developer hold the responsibility to manually transition a piece of data from private to public. However, certain functions in Compact are *always public*. For example, ledger writes, returns from exported circuits, contract-to-contract calls, and Unshielded token transfers are all public. Hashing and commitment schemes in Compact can obfuscate data passed through the first three of these domains, but what about Unshielded tokens? Unshielded tokens are always public. This tutorial will demonstrate absolute privacy for party attendees until the Unshielded token transfer, at which point the privacy boundary is crossed and privacy is no longer maintained. ## Program design[​](#program-design "Direct link to Program design") The private party program maintains privacy of party attendees by letting them RSVP to a party with a DApp-specific public key that hides their identity. The party organizer collects an entry fee in NIGHT tokens. NIGHT is an Unshielded token, and therefore these transactions are public. The attendees of the party remain private until they pay the entry fee and arrive at the party. The organizer maintains privacy within the DApp until the contract pays out the fees claimed by the organizer. ### Operational steps[​](#operational-steps "Direct link to Operational steps") First, consider the operational components of the contract. What does the contract need to do? In order, it needs to: 1. Deploy the contract and allow the organizer to set some initial values 2. Privately allow attendees to RSVP to the party 3. Give access to the organizer (and only the organizer) to start the party 4. Allow attendees who have previously RSVP'd to check-in to the party 5. Close the doors for entry (organizer only) 6. Payout fees to the organizer ### Data: private by default[​](#data-private-by-default "Direct link to Data: private by default") Compact treats data as private by default. This application demonstrates setting a piece of private state data and passing it privately into Compact circuits. No party attendee data is public until the Unshielded token transfer occurs. Always-public domains While Compact treats all data as private by default, certain domains are *always public*. This includes: * Ledger fields * Returns from exported circuits * Contract to contract calls * Unshielded transactions ### Access control[​](#access-control "Direct link to Access control") An important aspect of developing smart contracts in open public systems, like the Midnight blockchain, is access control to circuits. Once you deploy the contract to the blockchain, its circuits effectively become public APIs that *anyone* can call. Secure Compact contracts need to guard access to circuits intended for only a specific user or type of user. ## Compact tutorial[​](#compact-tutorial "Direct link to Compact tutorial") Compact provides a significant amount of flexibility for a DApp developer to precisely define a mix of public and private data. This tutorial focuses primarily on the Compact code and the remaining setup code comes with the repository. ### Setup[​](#setup "Direct link to Setup") Start by cloning the private party repository: ``` git clone git@github.com:midnightntwrk/example-private-party.git ``` Open the project in your text editor and navigate to the `contracts` directory before creating a new `.compact` file. ``` cd example-private-party/contracts && touch private-party.compact ``` The first thing to do is declare the language version and imports: ``` pragma language_version 0.23; import CompactStandardLibrary; ``` Then declare an enum of custom states: ``` export enum PartyState { NOT_STARTED, READY, STARTED, DOORS_CLOSED, FEES_CLAIMED } ``` Next, declare the *public* ledger fields: ``` export sealed ledger organizer: Bytes<32>; export sealed ledger maxListSize: Uint<16>; export sealed ledger entryFee: Uint<16>; export ledger partyState: PartyState; export ledger hashedPartyGoers: Set>; export ledger checkedInParty: Set; ``` The keyword `sealed` denotes immutable ledger fields that can only be set during constructor execution and cannot be changed after the constructor completes. ### Witnesses[​](#witnesses "Direct link to Witnesses") This contract uses no witness functions, but they can be useful to modify private state data in-circuit, provide off-chain computation, or enable functionality that does not exist in Compact, such as division. Witnesses are only declared in Compact. They are implemented in the off-chain TypeScript code, and therefore the return from a witness cannot be trusted without prior validation. For a demonstration of witness functions, see the [Battleship tutorial](/tutorials/bship/smart-contract.md#witnesses). This tutorial will access private state data via Compact circuit inputs. ### Constructor[​](#constructor "Direct link to Constructor") Next, set up the constructor that executes on contract deployment. The party organizer will deploy this contract. First, validate the inputs are non-zero before creating a unique identifier for the organizer: ``` constructor (partySize: Uint<16>, fee: Uint<16>, _secret: Bytes<32>) { assert(partySize > 0, "The party size must be greater than zero"); assert(fee > 0, "Fee must be greater than zero"); const pubKey = getDappPublicKey(_secret); organizer = disclose(pubKey); }// end of constructor ``` The implementation for `getDappPublicKey()` comes later. For now, understand that the organizer provides a secret that is hashed to provide a "public key" specific to this DApp. Compact circuit inputs are private, so `_secret` passes from private state directly to the circuit inputs and is never exposed publicly. The `pubKey` is safe to store on the ledger publicly, because it does not tie to the organizer's address or any other identifying information. Now that you have verified the inputs and privately identified the party organizer, set the remaining ledger fields: ``` entryFee = disclose(fee); maxListSize = disclose(partySize); partyState = PartyState.NOT_STARTED; }// end of constructor ``` Before the party starts, attendees need to RSVP that they plan to attend the party. You will implement the following circuit to allow this privately: ``` export circuit rsvp(_address: UserAddress, _secret: Bytes<32>): [] { const pubKey = getDappPublicKey(_secret); // caller authentication check assert(pubKey != organizer, "Organizer cannot RSVP to the party"); // state verification check assert(partyState == PartyState.NOT_STARTED, "The party has already started"); assert(hashedPartyGoers.size() < maxListSize, "The list is full"); }// end of rsvp ``` The same `getDappPublicKey()` circuit can be used for both organizers and party attendees to create a unique identifier that maintains privacy. The unique `_secret` passed into this circuit returns a different hash for each secret. After `assert`ing that the organizer isn't trying to attend their own party, the state of the contract is verified to be correct to accept RSVPs. Next, create a commitment to the `UserAddress` provided by the caller: ``` // party goer address remains private const commitHash = commitAddress(_secret, _address.bytes); assert(!hashedPartyGoers.member(commitHash), "You are already on the list"); hashedPartyGoers.insert(commitHash);// doesn't need disclose bc persistentCommit }// end of rsvp ``` With this pattern, the caller of this circuit ties the provided address to their secret and creates a cryptographic commitment to these values. The `commitAddress()` circuit will be written later, but it allows public storage of the hash while maintaining privacy of the underlying values and enabling a check of these values later. The last thing to do in this circuit is automatically trigger a state change if the list is full: ``` if (hashedPartyGoers.size() == maxListSize) { partyState = PartyState.READY; } }// end of rsvp ``` Now that the RSVP circuit is working, add the ability for the organizer to start the party: ``` export circuit startParty(_secret: Bytes<32>): [] { const pubKey = getDappPublicKey(_secret); assert(organizer == pubKey, "Only the organizer can start the party"); assert(partyState == PartyState.READY || partyState == PartyState.NOT_STARTED, "The party is not in the correct state for this operation"); partyState = PartyState.STARTED; }// end of startParty ``` This circuit identifies the caller's `pubKey`, checks that it matches the previously stored organizer's public key, and ensures the contract state is one of two possible values before updating the contract state. Changing the contract state allows party attendees to check in to the party. Start the `checkIn` circuit: ``` export circuit checkIn(address: UserAddress, _secret: Bytes<32>): [] { // state verification checks assert(partyState == PartyState.STARTED, "The party has not been started. Call the party police"); assert(checkedInParty.size() < hashedPartyGoers.size(), "All guests have already checked in"); const commitHash = commitAddress(_secret, address.bytes); // caller verification checks assert(hashedPartyGoers.member(commitHash), "You are not on the list"); assert(!checkedInParty.member(disclose(address)), "You have already checked in"); }// end of checkIn ``` This circuit intends to be called only by attendees who have already RSVP'd and restricts access to those on the `hashedPartyGoers` list. If the circuit caller is not on this list, or has provided a different `address` or `_secret` their circuit call will not pass the caller verification checks. The `commitAddress()` circuit makes use of a one-way, deterministic hashing function. In order to prove that the caller is some previously stored caller, they provide the same values and those values are hashed again. Comparing these two hashes should match if the caller provided the same value. Now that the caller is identified and state is as expected, the contract needs to accept payment. Payment for the party is denominated in NIGHT, which is an Unshielded token. All Unshielded tokens are public transactions. The private party attendees are now public: ``` // take in unshielded payment, party goers are now public receiveUnshielded(nativeToken(), entryFee as Uint<128>); checkedInParty.insert(disclose(address)); }// end of checkIn ``` The `nativeToken()` function returns the default color of all zeroes, indicating the NIGHT token. After the payment transaction completes, the `address` is `disclose()` and written to the ledger publicly. What disclose() does `disclose()` itself *does not* make a value public. It only tells the compiler that you, the DApp developer, are marking this value as safe to store publicly. The last thing to do in this circuit is to automatically close the doors to the party if everyone has checked in: ``` if(checkedInParty.size() == maxListSize) { partyState = PartyState.DOORS_CLOSED; } }// end of checkIn ``` If the `maxListSize` is never reached, a manual circuit needs to be provided for the organizer to change this state: ``` export circuit closeEntry(_secret: Bytes<32>): [] { const pubKey = getDappPublicKey(_secret); assert(organizer == pubKey, "Only organizer can close the doors"); assert(partyState == PartyState.STARTED, "Party in wrong state"); partyState = PartyState.DOORS_CLOSED; }// end of closeEntry ``` The contract accepted the NIGHT tokens and now holds them for claiming by the organizer. The contract needs to provide a circuit that allows the organizer to claim these fees: ``` export circuit claimFees(address: UserAddress, _secret: Bytes<32>): [] { const pubKey = getDappPublicKey(_secret); assert(organizer == pubKey, "You are not the organizer"); // state verification checks assert(partyState == PartyState.DOORS_CLOSED, "The doors are not yet closed"); assert(checkedInParty.size() > 0, "No fees to claim"); // calculate contract balance of NIGHT tokens const totalCollected = checkedInParty.size() * entryFee; assert(unshieldedBalanceGte(nativeToken(), totalCollected), "Contract balance wrong"); // send to organizer, they are now public sendUnshielded( nativeToken(), disclose(totalCollected) as Uint<128>, right(disclose(address)) ); partyState = PartyState.FEES_CLAIMED; } ``` This circuit has similar components to previous circuits, except that it calculates the available balance of tokens before sending them to the organizer. This makes the organizer public through the `sendUnshielded()` function. It is important to verify through `unshieldedBalanceGte()` that the contract balance is as expected. If the balance is too low to perform the `sendUnshielded()` transaction, the circuit execution will fail. Now the `commitAddress()` circuit: ``` circuit commitAddress(_address: Bytes<32>, _secret: Bytes<32>): Bytes<32> { return persistentCommit>(_address, _secret); } ``` This circuit makes use of `persistentCommit` to obfuscate the `_address` which is hashed with a random salt value, in this case the `_secret`. It is important to always use sufficiently random salt values, because the inputs to `persistentCommit` can be any simple value that is easily guessable. Due to the sufficiently random salt value, the hash returned does not need to be passed through `disclose()` before crossing into the public domain. It is already considered safe to do so. Now the `getDappPublicKey()` circuit: ``` circuit getDappPublicKey(_secret: Bytes<32>): Bytes<32> { return persistentHash>>([pad(32, "private-party:pk:"), _secret]); } ``` By contrast, the `persistentHash` function is for arbitrary binary data, like the `_secret`. Hashed with the domain separator specific to this DApp, it produces a "DApp-specific public key" that needs to be disclosed if intending to cross into the public domain. This is currently the only safe way to verify the caller of a Compact circuit. That is all of the Compact code needed to enable your private party! ### Compilation[​](#compilation "Direct link to Compilation") To compile the contract: ``` yarn compile ``` Successful output: ``` $ compact compile contract/private-party.compact contract/managed/private-party Compiling 5 circuits: circuit "checkIn" (k=13, rows=4530) circuit "claimFees" (k=13, rows=4512) circuit "closeEntry" (k=13, rows=4203) circuit "rsvp" (k=14, rows=8423) circuit "startParty" (k=13, rows=4232) Done in 8.24s. ``` If compilation is not successful, carefully read and understand the compiler error message and correct the error. Fighting the compiler is one of the most useful ways to learn new languages. To further inspect circuit data run the zkir linter (optional), from the `/contract` directory: ``` npx compact-zkir-lint -r managed/private-party/zkir ``` Successful output: ``` zkir-lint: scanned 5 file(s) checkIn (v2, k=11): clean instructions: 258 inputs: 4 constrain_bits: 4 cond_select: 6 guarded regions: 0 (max depth 0) proof payload: ~96KB claimFees (v2, k=11): clean instructions: 303 inputs: 4 constrain_bits: 4 cond_select: 2 guarded regions: 0 (max depth 0) proof payload: ~96KB closeEntry (v2, k=11): clean instructions: 63 inputs: 2 constrain_bits: 2 cond_select: 1 guarded regions: 0 (max depth 0) proof payload: ~96KB rsvp (v2, k=12): clean instructions: 179 inputs: 4 constrain_bits: 4 cond_select: 7 guarded regions: 0 (max depth 0) proof payload: ~192KB startParty (v2, k=11): clean instructions: 84 inputs: 2 constrain_bits: 2 cond_select: 8 guarded regions: 0 (max depth 1) proof payload: ~96KB 0 error(s), 0 warning(s), 0 info(s) | 5/5 clean ``` ### Testing[​](#testing "Direct link to Testing") Compilation only satisfies the Compact compiler with proper syntax. To ensure the contract operates as expected, run the test suite. Comprehensive test suites are essential in writing safe and secure contracts. Be sure the Docker engine is running and start the local devnet: ``` yarn env:up ``` This will create a small local blockchain in a Docker container that consists of: * Midnight Node * Midnight Indexer * Midnight proof server The proof server is a vital component of Midnight's zero-knowledge proof system. To learn more, see [Zero-knowledge proofs](/concepts/zero-knowledge-proofs.md). Run the test suite: ``` yarn test:local ``` Successful output: ``` [17:27:12.796] INFO (46073): Wallet sync [22]: shielded=true, unshielded=true, dust=true [17:27:12.796] INFO (46073): Wallet sync complete after 22 emissions [17:27:12.800] INFO (46073): Providers initialized. Ready to test. [17:27:12.800] INFO (46073): Bob providers successfully initialized [17:27:12.801] INFO (46073): Claire providers successfully initialized [17:27:12.802] INFO (46073): Deploying a contract the easy way... [17:27:32.867] INFO (46073): Contract deployed at 7da6acdcd5792da7f7278fb5362ec61b35e6693763bb3c7459720ef7945287e8 [17:27:33.013] INFO (46073): Bob is sending an RSVP... [17:27:51.082] INFO (46073): Bob rsvp'd successfully! [17:27:51.158] INFO (46073): Alice tries to rsvp... [17:27:51.232] INFO (46073): Alice was rejected! [17:27:51.373] INFO (46073): Claire is attempting to rsvp... [17:28:08.412] INFO (46073): Claire successfully rsvp'd! [17:28:08.492] INFO (46073): Bob tries to start the party... [17:28:08.567] INFO (46073): Bob was rejected! [17:28:08.636] INFO (46073): Alice starts the party... [17:28:26.688] INFO (46073): Alice started the party successfully! [17:28:26.761] INFO (46073): Bob is checking in... [17:28:44.976] INFO (46073): Bob has successfully checked in and is now public! [17:28:45.055] INFO (46073): Bob is attempting to close the doors... [17:28:45.128] INFO (46073): Bob was rejected! [17:28:45.196] INFO (46073): Alice is closing the doors... [17:29:02.303] INFO (46073): Alice has successfully closed the doors! [17:29:02.381] INFO (46073): Alice NIGHT balance before claimFees: 250000000000000 [17:29:02.381] INFO (46073): Alice is claiming fees... [17:29:21.979] INFO (46073): Alice has successfully claimed fees! [17:29:45.155] INFO (46073): Alice NIGHT balance after claimFees: 250000000000005 [17:29:45.155] INFO (46073): Alice NIGHT balance delta: 5 [17:29:45.177] INFO (46073): Unproven tx created. Pending contract address: 33b39d93fcd9b1c06df5d44020776b291cbb356bd40b75e1e928eb9e41f15656 [17:29:45.178] INFO (46073): proven tx received from proof server [17:29:46.082] INFO (46073): Balanced tx ready for submission [17:30:01.943] INFO (46073): Submitted tx id: 004081caf449e3cdd86f9c0abfac77b06e9b635ae9e6b5954c10200f8d6eac3ace [17:30:02.952] INFO (46073): Finalized! Status: SucceedEntirely, block: 31 ✓ src/test/party.test.ts (11 tests) 166950ms ✓ Private Party smart contract via midnight-js > Deploys a contract (the easy way) 20076ms ✓ Private Party smart contract via midnight-js > Allows Bob to rsvp (privately) 17232ms ✓ Private Party smart contract via midnight-js > Blocks organizers from rsvp 145ms ✓ Private Party smart contract via midnight-js > Allows Claire to rsvp(privately) 17184ms ✓ Private Party smart contract via midnight-js > Blocks non-organizers from starting the party 154ms ✓ Private Party smart contract via midnight-js > starts the party 17177ms ✓ Private Party smart contract via midnight-js > Allows Bob to check in 17338ms ✓ Private Party smart contract via midnight-js > Blocks non-organizers from closing the doors 150ms ✓ Private Party smart contract via midnight-js > Closes the doors to the party 17175ms ✓ Private Party smart contract via midnight-js > Allows Alice to claimFees 41849ms ✓ Private Party smart contract via midnight-js > Deploys the contract(the hard way) 16823ms ``` Read through the MidnightJS components that enable these tests in `/src/test/party.test.ts`. To learn more about testing specifically, see [Test and debug](/compact/test-and-debug.md). ## Conclusion[​](#conclusion "Direct link to Conclusion") This concludes the private party tutorial. The inclusion of the Unshielded NIGHT token exposed the party attendees. To maintain their privacy, rework this contract and test suite to use Shielded tokens. To inspect the full private-party repository, see [example-private-party](https://github.com/midnightntwrk/example-private-party). If you have questions, reach out in the Discord dev-chat channel. ## Next steps[​](#next-steps "Direct link to Next steps") For a more comprehensive, from scratch tutorial, see [Battleship](/tutorials/bship.md) or move on to a more advanced use case with [ZK-loan](/tutorials/zk-loan.md). --- > For the complete documentation index, see [llms.txt](/llms.txt) # ZK Loan tutorial Build a loan application that privately evaluates credit data with ZK proofs. The credit score, income, and employment tenure never leave your machine. [✦](/tutorials/zk-loan/smart-contract.md) ### [Smart contract](/tutorials/zk-loan/smart-contract.md) [Write a Compact contract that defines loan logic, eligibility tiers, and on-chain state for private credit evaluation.](/tutorials/zk-loan/smart-contract.md) [Write the contract→](/tutorials/zk-loan/smart-contract.md) [✦](/tutorials/zk-loan/attestation-api.md) ### [Attestation API](/tutorials/zk-loan/attestation-api.md) [Build a REST server that signs credit data with Schnorr signatures so the contract can verify it came from a trusted source.](/tutorials/zk-loan/attestation-api.md) [Build the API→](/tutorials/zk-loan/attestation-api.md) [✦](/tutorials/zk-loan/cli.md) ### [CLI and end-to-end testing](/tutorials/zk-loan/cli.md) [Build the CLI that ties contract, attestation API, and proof server together, then run the full flow end-to-end on a local network.](/tutorials/zk-loan/cli.md) [Build the CLI→](/tutorials/zk-loan/cli.md) --- > For the complete documentation index, see [llms.txt](/llms.txt) # Attestation API A smart contract that nobody can talk to is just a proof of concept sitting in a compiler's output directory. [Part 1](/tutorials/zk-loan/smart-contract.md) covered the implementation of a zero-knowledge (ZK) loan-scoring smart contract using Compact. Credit scores, income, and employment tenure remain private, while only the loan outcome lands on-chain. It also covered the Schnorr signature module that prevents users from fabricating their own credit data, and the TypeScript witness that feeds private inputs to the prover. But right now, that smart contract has no way to receive signed credit data or generate ZK proofs. This part builds the two pieces of off-chain infrastructure that make the smart contract functional: * **Attestation API**: A REST server that signs credit data with Schnorr signatures on the Jubjub curve. It acts as the trusted data provider, a stand-in for a bank or credit bureau, whose signatures the smart contract verifies inside the ZK circuit. * **Proof server**: A Docker container running Midnight's proof generation service locally. Every transaction that touches the smart contract requires a ZK proof, and this service produces them. This section also walks through the attestation flow end-to-end, showing how credit data flows from the attestation API to the ZK proof without ever appearing on-chain. **Prerequisites**: Make sure you have completed [Part 1](/tutorials/zk-loan/smart-contract.md) and have the compiled smart contract package ready in the `contract/dist/` directory. ## Build the attestation API[​](#build-the-attestation-api "Direct link to Build the attestation API") The attestation API is a trusted service that signs credit data with Schnorr signatures. In production, this would be a bank or credit bureau's API. For this tutorial, the REST server is built with Restify. The API has three endpoints: * `POST /attest`: Accepts credit data and a user's public key hash, returns a Schnorr signature * `GET /provider-info`: Returns the provider's ID and public key. The CLI uses these to register the provider on-chain. * `GET /health`: Returns the server's status ### Type definitions[​](#type-definitions "Direct link to Type definitions") Start by defining the request and response shapes. Create a file `types.ts` inside the `zkloan-credit-scorer-attestation-api/src` folder and then add the following code snippet: ``` export interface AttestationRequest { creditScore: number; monthlyIncome: number; monthsAsCustomer: number; userPubKeyHash: string; } export interface AttestationResponse { signature: { announcement: { x: string; y: string }; response: string; }; message: { creditScore: string; monthlyIncome: string; monthsAsCustomer: string; userPubKeyHash: string; }; } export interface ProviderInfoResponse { providerId: number; publicKey: { x: string; y: string }; } export interface HealthResponse { status: string; providerId: number; } ``` A few things to note about these types: * `AttestationRequest` takes numeric credit data and a stringified `userPubKeyHash`. The hash is a `bigint` under the hood, but JSON does not support arbitrary-precision integers, so it is serialized as a string. * `AttestationResponse` returns the Schnorr signature components (announcement point and scalar response) as strings for the same reason. * The `message` field echoes back the signed data, allowing the caller to verify the signature. ### Schnorr signing implementation[​](#schnorr-signing-implementation "Direct link to Schnorr signing implementation") The signing module generates key pairs and produces Schnorr signatures that the on-chain smart contract can verify. Create a file `signing.ts` inside the `zkloan-credit-scorer-attestation-api/src` folder and add the following code snippet: ``` import { ecMulGenerator, type JubjubPoint } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { ZKLoanCreditScorer } from 'zkloan-credit-scorer-contract'; const { pureCircuits } = ZKLoanCreditScorer; type SchnorrSignature = { announcement: JubjubPoint; response: bigint; }; import * as crypto from 'crypto'; const JUBJUB_ORDER = 6554484396890773809930967563523245729705921265872317281365359162392183254199n; const TWO_248 = 452312848583266388373324160190187140051835877600158453279131187530910662656n; function randomScalar(): bigint { const bytes = crypto.randomBytes(32); let val = BigInt('0x' + bytes.toString('hex')); return val % JUBJUB_ORDER; } export function generateKeyPair(): { sk: bigint; pk: JubjubPoint } { const sk = randomScalar(); const pk = ecMulGenerator(sk); return { sk, pk }; } export function getPublicKey(sk: bigint): JubjubPoint { return ecMulGenerator(((sk % JUBJUB_ORDER) + JUBJUB_ORDER) % JUBJUB_ORDER); } export function sign( sk: bigint, msg: bigint[], ): SchnorrSignature { sk = ((sk % JUBJUB_ORDER) + JUBJUB_ORDER) % JUBJUB_ORDER; const pk = ecMulGenerator(sk); const k = randomScalar(); const R = ecMulGenerator(k); // pureCircuits.schnorrChallenge returns the full transientHash output. // The circuit truncates it to 248 bits (mod 2^248) before using in EC ops. const cFull = pureCircuits.schnorrChallenge(R.x, R.y, pk.x, pk.y, msg); const c = cFull % TWO_248; // Compute response: s = (k + c * sk) mod JUBJUB_ORDER const s = ((k + c * sk) % JUBJUB_ORDER + JUBJUB_ORDER) % JUBJUB_ORDER; return { announcement: R, response: s }; } export function signCreditData( sk: bigint, creditScore: number, monthlyIncome: number, monthsAsCustomer: number, userPubKeyHash: bigint, ): SchnorrSignature { const msg: bigint[] = [ BigInt(creditScore), BigInt(monthlyIncome), BigInt(monthsAsCustomer), userPubKeyHash, ]; return sign(sk, msg); } ``` #### How the signing works[​](#how-the-signing-works "Direct link to How the signing works") The signing uses the Jubjub elliptic curve (Midnight's native internal curve). Here is the Schnorr signing flow, step by step: 1. Normalize the secret key into the Jubjub scalar field: `sk = ((sk % JUBJUB_ORDER) + JUBJUB_ORDER) % JUBJUB_ORDER`. 2. Generate a random nonce `k`. 3. Compute the announcement `R = G * k` (where G is the curve generator). 4. Compute the challenge hash using `pureCircuits.schnorrChallenge()` — this is the same hash function the smart contract uses, which is critical for the signature to verify on-chain. 5. Truncate the challenge to 248 bits: `c = cFull % 2^248`. 6. Compute the response: `s = (k + c * sk) mod JUBJUB_ORDER`. The resulting signature is `(R, s)`. The smart contract verifies it by checking: `G * s == R + publicKey * c`. Step 1 matters more than it looks: `ecMulGenerator` only accepts scalars below the Jubjub curve order and throws an "out of bounds for prime field" error otherwise. Both `sign` and `getPublicKey` reduce the key modulo `JUBJUB_ORDER` first, so a key loaded from an arbitrary 32-byte value (which is usually larger than the \~252-bit curve order) still works. The critical detail is step 4. The `pureCircuits.schnorrChallenge()` function is generated from the Compact smart contract's `pure circuit schnorrChallenge` covered in [Part 1](/tutorials/zk-loan/smart-contract.md). Because both the off-chain signer and the on-chain verifier use the same hash function, the signatures produced here verify inside the ZK circuit. If a different hash were used, then every signature would fail verification. The `signCreditData` function is a convenience wrapper. It takes the four credit data fields (credit score, monthly income, months as customer, and the user public key hash). It converts them to `bigint` and passes them to the generic `sign` function. ### REST server[​](#rest-server "Direct link to REST server") The server exposes the three endpoints and wires them to the signing logic. Create `zkloan-credit-scorer-attestation-api/src/server.ts`: ``` import restify from 'restify'; import { signCreditData, getPublicKey } from './signing.js'; import type { AttestationRequest, AttestationResponse, ProviderInfoResponse, HealthResponse } from './types.js'; import type { JubjubPoint } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; export function createServer(providerSk: bigint, providerId: number): restify.Server { const server = restify.createServer({ name: 'zkloan-attestation-api' }); server.use(restify.plugins.bodyParser()); // CORS support for browser-based UI server.pre((req: restify.Request, res: restify.Response, next: restify.Next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') { res.send(204); return next(false); } return next(); }); const providerPk: JubjubPoint = getPublicKey(providerSk); server.post('/attest', (req: restify.Request, res: restify.Response, next: restify.Next) => { try { const body = req.body as AttestationRequest; if (body.creditScore == null || body.monthlyIncome == null || body.monthsAsCustomer == null || body.userPubKeyHash == null) { res.send(400, { error: 'Missing required fields: creditScore, monthlyIncome, monthsAsCustomer, userPubKeyHash' }); return next(); } const userPubKeyHash = BigInt(body.userPubKeyHash); const signature = signCreditData( providerSk, body.creditScore, body.monthlyIncome, body.monthsAsCustomer, userPubKeyHash, ); const response: AttestationResponse = { signature: { announcement: { x: signature.announcement.x.toString(), y: signature.announcement.y.toString(), }, response: signature.response.toString(), }, message: { creditScore: body.creditScore.toString(), monthlyIncome: body.monthlyIncome.toString(), monthsAsCustomer: body.monthsAsCustomer.toString(), userPubKeyHash: userPubKeyHash.toString(), }, }; res.send(200, response); } catch (err: any) { res.send(500, { error: err.message }); } return next(); }); server.get('/provider-info', (_req: restify.Request, res: restify.Response, next: restify.Next) => { const response: ProviderInfoResponse = { providerId, publicKey: { x: providerPk.x.toString(), y: providerPk.y.toString(), }, }; res.send(200, response); return next(); }); server.get('/health', (_req: restify.Request, res: restify.Response, next: restify.Next) => { const response: HealthResponse = { status: 'ok', providerId, }; res.send(200, response); return next(); }); return server; } ``` Here is what each endpoint does: * `POST /attest` is the core endpoint. It receives credit data and a user public key hash, signs the data with the provider's secret key, and returns the Schnorr signature. The `userPubKeyHash` is included in the signed message — this binds the attestation to a specific user identity, preventing one user from replaying another user's attestation. * `GET /provider-info` returns the provider's ID and public key coordinates. The CLI uses this endpoint to get the values needed for on-chain provider registration. * `GET /health` is a standard health check. ### Entry point[​](#entry-point "Direct link to Entry point") The entry point handles key management and starts the server. Create a file `index.ts` inside the `zkloan-credit-scorer-attestation-api/src` folder and add the following code snippet: ``` import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; import { createServer } from './server.js'; import { generateKeyPair, getPublicKey } from './signing.js'; setNetworkId(process.env.NETWORK_ID || 'undeployed'); const PORT = parseInt(process.env.PORT || '4000', 10); const PROVIDER_ID = parseInt(process.env.PROVIDER_ID || '1', 10); // Jubjub scalar field order — the generator's scalar must be reduced mod this // or ecMulGenerator throws "out of bounds for prime field". const JUBJUB_ORDER = 6554484396890773809930967563523245729705921265872317281365359162392183254199n; let providerSk: bigint; if (process.env.PROVIDER_SECRET_KEY) { const raw = BigInt('0x' + process.env.PROVIDER_SECRET_KEY); providerSk = raw % JUBJUB_ORDER; console.log('Loaded provider secret key from environment'); } else { const keyPair = generateKeyPair(); providerSk = keyPair.sk; console.log('Generated ephemeral provider key pair'); } const pk = getPublicKey(providerSk); console.log(`Provider ID: ${PROVIDER_ID}`); console.log(`Provider public key:`); console.log(` x: ${pk.x}`); console.log(` y: ${pk.y}`); console.log(`Register this provider on-chain with: registerProvider(${PROVIDER_ID}, {x: ${pk.x}n, y: ${pk.y}n})`); const server = createServer(providerSk, PROVIDER_ID); server.listen(PORT, () => { console.log(`Attestation API listening on port ${PORT}`); }); ``` The entry point supports two modes: * **Ephemeral mode** (default): Generates a fresh key pair on startup. This is useful for development and testing, but the key changes every time you restart the server. You need to re-register the provider on-chain after each restart. * **Persistent mode**: Set the `PROVIDER_SECRET_KEY` environment variable to a hex-encoded secret key. The server loads this key on startup, so the public key stays the same across restarts. The raw value is reduced modulo `JUBJUB_ORDER` before use — most random 32-byte keys are larger than the \~252-bit curve order, and `ecMulGenerator` would throw on an un-reduced scalar. The network ID defaults to `undeployed` (a local network). Set the `NETWORK_ID` environment variable when targeting another network such as Preprod. When the server starts, it prints the provider's public key coordinates and a ready-made `registerProvider` command. Copy these values — you need them in [Part 3](/tutorials/zk-loan/cli.md) when registering the provider through the CLI. ### Package configuration[​](#package-configuration "Direct link to Package configuration") Create a `package.json` file inside the root `zkloan-credit-scorer-attestation-api` folder and add the following code snippet: ``` { "name": "zkloan-credit-scorer-attestation-api", "version": "0.1.0", "private": true, "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "tsx src/index.ts", "test": "vitest run" }, "dependencies": { "zkloan-credit-scorer-contract": "0.1.0", "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "restify": "^11.1.0" }, "devDependencies": { "@types/restify": "^8.5.12", "tsx": "^4.19.0", "vitest": "^4.0.15" } } ``` The attestation API pulls `ecMulGenerator` and the `JubjubPoint` type from `@midnight-ntwrk/midnight-js-protocol/compact-runtime`, so `midnight-js-protocol` is a direct dep here. Note there is no direct `@midnight-ntwrk/compact-runtime` dependency: the generated contract code needs it at runtime, but it is declared by the `contract` package and resolved through `zkloan-credit-scorer-contract`, so this package does not declare it again. Next, create `zkloan-credit-scorer-attestation-api/tsconfig.json` with the following code snippet: ``` { "compilerOptions": { "rootDir": "src", "outDir": "dist", "declaration": true, "lib": ["ESNext"], "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "allowJs": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "strict": true, "isolatedModules": true, "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*.ts"] } ``` `moduleResolution` is `bundler` (rather than the legacy `node`) so TypeScript can read the `exports` subpath map that `@midnight-ntwrk/midnight-js-protocol` uses to publish `/compact-runtime`, `/ledger`, and `/compact-js`. `node16` and `nodenext` work too. ## Understanding the attestation flow[​](#understanding-the-attestation-flow "Direct link to Understanding the attestation flow") With the API built, here is how attestation works end-to-end across all three components: ``` ┌──────────┐ ┌────────────────┐ ┌───────────────┐ │ User │ │ Attestation │ │ Midnight │ │ (CLI) │ │ API │ │ Network │ └────┬─────┘ └───────┬────────┘ └───────┬───────┘ │ │ │ │ 1. Admin registers provider PK on-chain │ │──────────────────────────────────────────>│ │ │ │ │ 2. POST /attest │ │ │ {creditScore, │ │ │ monthlyIncome, │ │ │ monthsAsCustomer│ │ │ userPubKeyHash} │ │ │──────────────────>│ │ │ │ │ │ 3. Returns signed│ │ │ Schnorr signature│ │ │<──────────────────│ │ │ │ │ │ 4. Submit loan request with signature │ │ (signature in private state, never │ │ visible on-chain) │ │──────────────────────────────────────────>│ │ │ │ │ │ 5. ZK circuit │ │ │ verifies signature │ │ │ against registered │ │ │ PK (all in zero- │ │ │ knowledge) │ │ │ │ │ 6. Only loan status + amount on ledger │ │<─────────────────────────────────────────│ ``` Here is a walkthrough of each step, matching the numbers in the diagram above: 1. **Register the provider.** The admin calls `registerProvider` on-chain, storing the attestation API's Jubjub public key in the smart contract's `providers` map. This is the only setup step that touches the blockchain. 2. **Request attestation.** The CLI sends the user's credit data and the derived public-key hash to the attestation API. The CLI computes the public key hash from the user's local 32-byte secret key (held in private state — the wallet key is never used for identity) and secret PIN using the `deriveUserPublicKey` pure circuit from [Part 1](/tutorials/zk-loan/smart-contract.md), then hashes the resulting public key. 3. **Sign and return.** The attestation API signs all four fields (credit score, monthly income, months as a customer, and user public key hash) as a single Schnorr signature. Including the public key hash in the signed message binds the attestation to a specific user; a different user cannot reuse this signature. 4. **Submit the loan request.** The CLI stores the signature in the user's private state and calls `requestLoan`. The signature is sent to the proof server as part of the ZK witness. It never appears in the transaction data that reaches the blockchain. 5. **Verify in ZK.** Inside the circuit, `evaluateApplicant` retrieves the signature from the witness, looks up the provider's public key from the ledger, and runs `schnorrVerify`. Verification fails if the data was tampered with, the wrong provider signed it, or the attestation belongs to a different user. When that happens, the assertion fails and the transaction reverts. 6. **Record the outcome.** Only the loan status (Approved, Proposed, or Rejected) and the authorized amount are written to the ledger via [`disclose()`](/compact/reference/explicit-disclosure.md). The credit score, income, tenure, PIN, and attestation signature remain private. This creates a two-sided privacy guarantee: * **The user cannot lie**: The smart contract verifies the attestation provider's signature inside the circuit, so fabricated credit data fails verification. * **The provider cannot see the outcome**: The ZK proof treats the signed data as a private input, so the attestation API has no visibility into on-chain activity. ## Set up Docker for the proof server[​](#set-up-docker-for-the-proof-server "Direct link to Set up Docker for the proof server") note If you are testing with [Midnight Local Dev](/guides/networks-and-environments.md#running-a-local-network) instead of Preprod, then skip this step. The local dev environment already includes a proof server on port `6300`. The [proof server](/guides/run-proof-server.md) generates ZK proofs for every transaction that interacts with the smart contract. For Preprod, you run it locally via Docker while the blockchain node and indexer are remote (hosted by Midnight Network). Create `zkloan-credit-scorer-cli/proof-server.yml`: ``` services: proof-server: image: "midnightntwrk/proof-server:8.1.0" ports: - "6300:6300" environment: RUST_BACKTRACE: "full" ``` note Make sure you are using the latest version of the proof server. Check the [compatibility matrix](/relnotes/support-matrix.md) to verify the correct version for your SDK. Start the proof server: ``` cd zkloan-credit-scorer-cli docker compose -f proof-server.yml up -d ``` Verify it is running: ``` docker compose -f proof-server.yml ps ``` You should see the `proof-server` container running on port `6300`. To confirm the server responds, run `curl http://localhost:6300/version` from your host. Do not add a curl-based `healthcheck` to the compose file — the proof-server image does not ship `curl`, so an in-container healthcheck fails even when the server is healthy. The proof server is the most compute-intensive component in the stack. When you submit a transaction through the CLI in [Part 3](/tutorials/zk-loan/cli.md), the proof server receives the circuit definition, the public inputs (ledger state), and the private inputs (witness data). It then produces a ZK proof, which is submitted to the Midnight Network. This proof demonstrates that the computation was performed correctly without revealing the private inputs. For development, running it locally via Docker is sufficient. In production, the proof server would run on dedicated infrastructure with more compute resources. ## Next steps[​](#next-steps "Direct link to Next steps") The final part builds the CLI and executes the full end-to-end flow: * *[CLI](/tutorials/zk-loan/cli.md)*: An interactive command-line tool for creating wallets, deploying the smart contract, registering attestation providers, requesting loans, and inspecting on-chain state on Midnight's Preprod network. * *End-to-end testing*: Wallet creation and funding with tNIGHT, smart contract deployment, provider registration, loan requests across different eligibility tiers, and verification that only the loan outcome appears on-chain. --- > For the complete documentation index, see [llms.txt](/llms.txt) # CLI and end-to-end testing The smart contract is compiled. The attestation API can sign credit data. The proof server can generate zero-knowledge (ZK) proofs. Now you need a way to talk to all three. In [Part 1](/tutorials/zk-loan/smart-contract.md), you built the Compact smart contract and witness layer. In [Part 2](/tutorials/zk-loan/attestation-api.md), you built the attestation API and set up the proof server. This final part builds the CLI that ties everything together, then runs the full flow end-to-end on a local Midnight network. The same CLI can target Midnight's Preprod network by running a different entry-point script. You will build two things: 1. **CLI**: An interactive command-line tool that handles wallet creation, smart contract deployment, attestation provider registration, loan requests, and on-chain state inspection. 2. **End-to-end test**: A walkthrough that exercises the complete system: build a funded wallet, deploy the smart contract, register a provider, request a loan with private credit data, and verify that only the outcome appears on-chain. ### Prerequisites[​](#prerequisites "Direct link to Prerequisites") * Complete [Part 1](/tutorials/zk-loan/smart-contract.md) and [Part 2](/tutorials/zk-loan/attestation-api.md) * The compiled smart contract package should be in `contract/dist/` * The attestation API should be ready to start * The Docker proof server should be running on port `6300` * Node.js v22 or newer — on Node 20 the wallet appears to start but crashes during sync with `TypeError: state.pendingOutputs.values.map is not a function` (see the caution in [Part 1](/tutorials/zk-loan/smart-contract.md)) ## Build the CLI[​](#build-the-cli "Direct link to Build the CLI") The CLI is a TypeScript application that orchestrates wallet operations, smart contract interactions, and attestation requests. It consists of nine source files, each with a distinct responsibility. ### Configuration[​](#configuration "Direct link to Configuration") The CLI needs to know where to find the indexer, the blockchain node, and the proof server for whichever network it targets — Midnight's remote Preprod infrastructure or a local dev network. It also needs a path to the compiled circuit artifacts from [Part 1](/tutorials/zk-loan/smart-contract.md). This configuration file centralizes all of those endpoints and paths in one place. Create `zkloan-credit-scorer-cli/src/config.ts`: ``` import path from "node:path"; import { setNetworkId } from "@midnight-ntwrk/midnight-js-network-id"; export const currentDir = path.resolve(new URL(import.meta.url).pathname, ".."); export const contractConfig = { privateStateStoreName: "zkloan-credit-scorer-private-state", zkConfigPath: path.resolve( currentDir, "..", "..", "contract", "src", "managed", "zkloan-credit-scorer", ), }; export interface Config { readonly logDir: string; readonly indexer: string; readonly indexerWS: string; readonly node: string; readonly proofServer: string; readonly networkId: string; } export class PreprodConfig implements Config { logDir = path.resolve( currentDir, "..", "logs", "preprod", `${new Date().toISOString()}.log`, ); indexer = "https://indexer.preprod.midnight.network/api/v4/graphql"; indexerWS = "wss://indexer.preprod.midnight.network/api/v4/graphql/ws"; node = "wss://rpc.preprod.midnight.network"; proofServer = "http://127.0.0.1:6300"; networkId = "preprod"; } export class StandaloneConfig implements Config { logDir = path.resolve( currentDir, "..", "logs", "standalone", `${new Date().toISOString()}.log`, ); indexer = "http://127.0.0.1:8088/api/v4/graphql"; indexerWS = "ws://127.0.0.1:8088/api/v4/graphql/ws"; node = "http://127.0.0.1:9944"; proofServer = "http://127.0.0.1:6300"; networkId = "undeployed"; constructor() { setNetworkId("undeployed"); } } ``` This file covers both networks: `PreprodConfig` points the indexer and node at Midnight's remote infrastructure, while `StandaloneConfig` points them at a local stack. In both cases the proof server runs locally on port `6300` — the Docker container you started in [Part 2](/tutorials/zk-loan/attestation-api.md) for Preprod, or the one bundled with [Midnight Local Dev](/guides/networks-and-environments.md#running-a-local-network). Key details: * `zkConfigPath` points to the compiled circuit artifacts (proving keys, verifying keys, and ZKIR files) generated by the Compact compiler in [Part 1](/tutorials/zk-loan/smart-contract.md). * `privateStateStoreName` is the LevelDB store name where the user's private state (credit data and attestation signature) persists locally between CLI sessions. * The indexer provides two connections: HTTP for queries and WebSocket for real-time subscription to ledger state changes. * `StandaloneConfig` connects to [Midnight Local Dev](/guides/networks-and-environments.md#running-a-local-network), a standalone Docker-based development environment that runs the Midnight node, indexer, and proof server locally. It uses the `undeployed` network ID, and all services run on `localhost`. Its constructor calls `setNetworkId('undeployed')` immediately, so address derivation uses the right network ID as soon as the config is instantiated. ### Type definitions[​](#type-definitions "Direct link to Type definitions") The Midnight JS SDK is heavily typed; every smart contract interaction requires specific type parameters for circuits, private state, and provider bundles. Rather than repeating these types across files, this module defines them once and exports them for use throughout the CLI. Create `zkloan-credit-scorer-cli/src/common-types.ts`: ``` import { ZKLoanCreditScorer, type ZKLoanCreditScorerPrivateState, } from 'zkloan-credit-scorer-contract'; import type { MidnightProviders } from '@midnight-ntwrk/midnight-js-types'; import type { DeployedContract, FoundContract, } from '@midnight-ntwrk/midnight-js-contracts'; export type ZKLoanCreditScorerCircuits = | 'requestLoan' | 'changePin' | 'blacklistUser' | 'removeBlacklistUser' | 'rotateAdmin' | 'respondToLoan' | 'registerProvider' | 'removeProvider'; export const ZKLoanCreditScorerPrivateStateId = 'zkLoanCreditScorerPrivateState'; export type ZKLoanCreditScorerProviders = MidnightProviders< ZKLoanCreditScorerCircuits, typeof ZKLoanCreditScorerPrivateStateId, ZKLoanCreditScorerPrivateState >; export type ZKLoanCreditScorerContract = ZKLoanCreditScorer.Contract; export type DeployedZKLoanCreditScorerContract = | DeployedContract | FoundContract; ``` * `ZKLoanCreditScorerCircuits` is a union type of all the circuit names the CLI can call. This type is used by the proof provider and ZK config provider to load the correct proving keys for each transaction. * `ZKLoanCreditScorerProviders` bundles all six provider types required by the Midnight JS SDK: wallet, midnight (transaction submission), proof, ZK config, public data (indexer), and private state (LevelDB). * `DeployedZKLoanCreditScorerContract` is a union because you can either deploy a new smart contract (returning `DeployedContract`) or join an existing one (returning `FoundContract`). Both expose the same `callTx` interface. ### Mock user profiles[​](#mock-user-profiles "Direct link to Mock user profiles") When the CLI requests a loan, it needs a credit profile (credit score, monthly income, and employment tenure) to send to the attestation API for signing. In production, this data would come from a real credit bureau or banking provider. For this tutorial, the CLI uses a set of mock profiles spanning all four eligibility tiers, from Tier 1 approval to outright rejection, so you can test each outcome without real financial data. Create `zkloan-credit-scorer-cli/src/state.utils.ts`: ``` import { type ZKLoanCreditScorerPrivateState } from "zkloan-credit-scorer-contract"; export const userProfiles = [ { applicantId: "user-001", creditScore: 720, monthlyIncome: 2500, monthsAsCustomer: 24, }, { applicantId: "user-002", creditScore: 650, monthlyIncome: 1800, monthsAsCustomer: 11, }, { applicantId: "user-003", creditScore: 580, monthlyIncome: 2200, monthsAsCustomer: 36, }, { applicantId: "user-004", creditScore: 710, monthlyIncome: 1900, monthsAsCustomer: 5, }, { applicantId: "user-005", creditScore: 520, monthlyIncome: 3000, monthsAsCustomer: 48, }, { applicantId: "user-006", creditScore: 810, monthlyIncome: 4500, monthsAsCustomer: 60, }, { applicantId: "user-007", creditScore: 639, monthlyIncome: 2100, monthsAsCustomer: 18, }, { applicantId: "user-008", creditScore: 680, monthlyIncome: 1450, monthsAsCustomer: 30, }, { applicantId: "user-009", creditScore: 750, monthlyIncome: 2100, monthsAsCustomer: 23, }, { applicantId: "user-010", creditScore: 579, monthlyIncome: 1900, monthsAsCustomer: 12, }, ]; import { webcrypto } from 'node:crypto'; // Generate a fresh 32-byte user secret. This single value drives all identity // in the contract: per-user PIN-bound identity (`deriveUserPublicKey(secret, pin)`) // and the admin role (`deriveAdminPublicKey(secret)`). It is the only // authoritative caller identity — `ownPublicKey()` is prover-supplied and // unused. function generateUserSecret(): Uint8Array { const bytes = new Uint8Array(32); webcrypto.getRandomValues(bytes); return bytes; } export function getUserProfile( index?: number, userSecretKey: Uint8Array = generateUserSecret(), ): ZKLoanCreditScorerPrivateState { let profile; if (index !== undefined) { if (index < 0 || index >= userProfiles.length) { throw new Error( `Index ${index} is out of bounds. Must be between 0 and ${userProfiles.length - 1}.`, ); } profile = userProfiles[index]; } else { const randomIndex = Math.floor(Math.random() * userProfiles.length); profile = userProfiles[randomIndex]; } return { creditScore: BigInt(profile.creditScore), monthlyIncome: BigInt(profile.monthlyIncome), monthsAsCustomer: BigInt(profile.monthsAsCustomer), attestationSignature: { announcement: { x: 0n, y: 0n }, response: 0n, }, attestationProviderId: 0n, userSecretKey, }; } ``` The `userSecretKey` field is the 32-byte preimage of both the caller's per-user pubkey (with PIN) and the admin pubkey (without PIN). Whoever deploys becomes admin by virtue of holding this secret; rotating the admin role requires the next admin to generate their own secret and share only its derived admin public key. These profiles map to the eligibility tiers defined in the smart contract from [Part 1](/tutorials/zk-loan/smart-contract.md): | Profile | Credit score | Income | Tenure | Expected tier | | -------- | ------------ | ------ | --------- | ---------------------------------- | | user-001 | 720 | $2,500 | 24 months | Tier 1 ($10,000) | | user-002 | 650 | $1,800 | 11 months | Tier 2 ($7,000) | | user-003 | 580 | $2,200 | 36 months | Tier 3 ($3,000) | | user-005 | 520 | $3,000 | 48 months | Rejected | | user-010 | 579 | $1,900 | 12 months | Rejected (1 point short of Tier 3) | The `getUserProfile` function returns a `ZKLoanCreditScorerPrivateState` with the attestation fields initialized to zero. These fields get populated later when the CLI fetches a real attestation from the API before submitting a loan request. ### Logger utility[​](#logger-utility "Direct link to Logger utility") Midnight transactions can take over a minute to finalize while the proof server generates ZK proofs. Without logging, you have no visibility into what the CLI is doing during those waits. This utility creates a logger that writes to both the console (with color formatting) and a timestamped file, so you can monitor progress in real time and debug issues after the fact. Create `zkloan-credit-scorer-cli/src/logger-utils.ts`: ``` import * as path from 'node:path'; import * as fs from 'node:fs/promises'; import pinoPretty from 'pino-pretty'; import pino from 'pino'; import { createWriteStream } from 'node:fs'; export const createLogger = async ( logPath: string, ): Promise => { await fs.mkdir(path.dirname(logPath), { recursive: true }); const pretty: pinoPretty.PrettyStream = pinoPretty({ colorize: true, sync: true, }); const level = process.env.DEBUG_LEVEL !== undefined && process.env.DEBUG_LEVEL !== null && process.env.DEBUG_LEVEL !== '' ? process.env.DEBUG_LEVEL : 'info'; return pino( { level, depthLimit: 20, }, pino.multistream([ { stream: pretty, level }, { stream: createWriteStream(logPath), level }, ]), ); }; ``` Set `DEBUG_LEVEL=debug` in your environment for verbose output during development. ### Core API implementation[​](#core-api-implementation "Direct link to Core API implementation") This is the core module that connects the CLI to the Midnight SDK. It handles four responsibilities: creating and funding wallets from BIP-39 mnemonics or a hex seed, deploying or joining smart contracts on the configured network, fetching Schnorr attestations from the API you built in [Part 2](/tutorials/zk-loan/attestation-api.md), and wrapping each smart contract circuit call (loan requests, PIN changes, admin operations) in a function the interactive CLI can invoke. Because of its size, this page presents it in logical sections with explanations between each block. Create `zkloan-credit-scorer-cli/src/api.ts` and add the following sections in order. #### Imports and global setup[​](#imports-and-global-setup "Direct link to Imports and global setup") This block imports the Midnight SDK modules, wallet libraries, and project-specific types. It also patches the global `WebSocket` constructor for Node.js compatibility with the SDK's GraphQL subscriptions: ``` import 'dotenv/config'; import { type ContractAddress, transientHash, CompactTypeBytes, } from '@midnight-ntwrk/midnight-js-protocol/compact-runtime'; import { ZKLoanCreditScorer, type ZKLoanCreditScorerPrivateState, witnesses, } from 'zkloan-credit-scorer-contract'; import * as ledger from '@midnight-ntwrk/midnight-js-protocol/ledger'; import { CompiledContract } from '@midnight-ntwrk/midnight-js-protocol/compact-js'; import { deployContract, findDeployedContract, } from '@midnight-ntwrk/midnight-js-contracts'; import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { type FinalizedTxData, type MidnightProvider, type WalletProvider, type UnboundTransaction, } from '@midnight-ntwrk/midnight-js-types'; import { assertIsContractAddress } from '@midnight-ntwrk/midnight-js-utils'; import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; // Wallet SDK imports are consolidated under the @midnight-ntwrk/wallet-sdk // barrel (introduced in wallet-sdk 1.1.0, alongside Midnight JS 4.1.x). import { HDWallet, Roles, WalletFacade, ShieldedWallet, DustWallet, UnshieldedWallet, createKeystore, InMemoryTransactionHistoryStorage, WalletEntrySchema, PublicKey as UnshieldedPublicKey, type UnshieldedKeystore, } from '@midnight-ntwrk/wallet-sdk'; import * as bip39 from '@scure/bip39'; import { wordlist as english } from '@scure/bip39/wordlists/english.js'; import { webcrypto } from 'crypto'; import { type Logger } from 'pino'; import * as Rx from 'rxjs'; import { WebSocket } from 'ws'; import { Buffer } from 'buffer'; import { type ZKLoanCreditScorerContract, type ZKLoanCreditScorerPrivateStateId, type ZKLoanCreditScorerProviders, type DeployedZKLoanCreditScorerContract, type ZKLoanCreditScorerCircuits, } from './common-types'; import { type Config, contractConfig } from './config'; import { getUserProfile } from './state.utils'; let logger: Logger; // @ts-expect-error: Needed to enable WebSocket usage through Apollo globalThis.WebSocket = WebSocket; ``` The `WebSocket` assignment is required because the Midnight SDK's GraphQL subscriptions (used by the indexer) expect a global WebSocket constructor. Node.js does not provide one by default. Two Midnight JS 4.1.x import changes * **Protocol packages go through the ACL package.** Hand-written imports for `ledger`, `compact-runtime`, `compact-js`, `onchain-runtime`, and `platform-js` are rewritten as subpath imports of the version-agnostic `@midnight-ntwrk/midnight-js-protocol` package (for example, `@midnight-ntwrk/midnight-js-protocol/compact-runtime`). Direct `@midnight-ntwrk/ledger-v8` and `@midnight-ntwrk/compact-js` imports no longer belong in application code. * **Wallet SDK collapses to a single barrel.** `wallet-sdk-facade`, `wallet-sdk-hd`, `wallet-sdk-shielded`, `wallet-sdk-dust-wallet`, and `wallet-sdk-unshielded-wallet` are re-exported from `@midnight-ntwrk/wallet-sdk` (introduced in `1.1.0`; the repo pins `1.2.0` exactly, because npm's `latest` tag still resolves to `1.1.0`). Import one place, not five. Both changes require `tsconfig.json` with `moduleResolution` set to `bundler`, `node16`, or `nodenext` — the legacy `node` resolver cannot read the protocol package's `exports` subpath map. See the tsconfig block later in this section. #### Wallet context and ledger state[​](#wallet-context-and-ledger-state "Direct link to Wallet context and ledger state") The `WalletContext` interface and `getZKLoanLedgerState` function define how the CLI interacts with wallet state and reads on-chain contract data: ``` export interface WalletContext { wallet: WalletFacade; shieldedSecretKeys: ledger.ZswapSecretKeys; dustSecretKey: ledger.DustSecretKey; unshieldedKeystore: UnshieldedKeystore; } export const getZKLoanLedgerState = async ( providers: ZKLoanCreditScorerProviders, contractAddress: ContractAddress, ): Promise => { assertIsContractAddress(contractAddress); logger.info('Checking contract ledger state...'); const state = await providers.publicDataProvider .queryContractState(contractAddress) .then((contractState) => contractState != null ? ZKLoanCreditScorer.ledger(contractState.data) : null, ); return state; }; ``` `WalletContext` bundles the four wallet components: * `wallet` — the facade that coordinates shielded, unshielded, and dust wallets. * `shieldedSecretKeys` — used for ZK transactions. * `dustSecretKey` — used for paying transaction fees. * `unshieldedKeystore` — used for transparent operations such as DUST registration. `getZKLoanLedgerState` queries the indexer for the current on-chain state of the smart contract. The `ZKLoanCreditScorer.ledger()` function deserializes the raw contract state into the typed `Ledger` object with fields like `contractAdmin`, `loans`, `providers`, and `blacklist`. #### Compiled smart contract and deploy/join[​](#compiled-smart-contract-and-deployjoin "Direct link to Compiled smart contract and deploy/join") This section combines the compiled contract artifacts with the witness implementations, then provides functions to deploy a new contract or join an existing one: ``` export const zkLoanCompiledContract = CompiledContract.make( 'ZKLoanCreditScorer', ZKLoanCreditScorer.Contract, ).pipe( CompiledContract.withWitnesses(witnesses), CompiledContract.withCompiledFileAssets(contractConfig.zkConfigPath), ); export const joinContract = async ( providers: ZKLoanCreditScorerProviders, contractAddress: string, ): Promise => { const contract = await findDeployedContract(providers as any, { contractAddress, compiledContract: zkLoanCompiledContract, privateStateId: 'zkLoanCreditScorerPrivateState', initialPrivateState: getUserProfile(), }); logger.info( `Joined contract at address: ${contract.deployTxData.public.contractAddress}`, ); return contract as any; }; export const deploy = async ( providers: ZKLoanCreditScorerProviders, privateState: ZKLoanCreditScorerPrivateState, ): Promise => { logger.info('Deploying ZKLoan Credit Scorer contract...'); const contract = await deployContract(providers as any, { compiledContract: zkLoanCompiledContract, privateStateId: 'zkLoanCreditScorerPrivateState', initialPrivateState: privateState, }); logger.info( `Deployed contract at address: ${contract.deployTxData.public.contractAddress}`, ); return contract as any; }; ``` The code above defines three key exports: * `zkLoanCompiledContract` combines three things: the generated TypeScript smart contract interface, the witness implementations from [Part 1](/tutorials/zk-loan/smart-contract.md), and the compiled circuit assets (proving keys and ZKIR files). * `deploy` creates a new instance of the smart contract on the configured network. This triggers a deployment transaction that includes a ZK proof — the proof server generates this, which takes about a minute. * `joinContract` connects to an existing deployed smart contract by address. This is how a second user (or the same user in a new session) interacts with a smart contract deployed by someone else. `args` is conditionally typed in 4.1.x `deployContract`'s `args` option is now conditionally typed on the contract's constructor signature. This contract's constructor takes no arguments, so `args` must be **omitted entirely** — passing `args: []` no longer type-checks. If your contract had a constructor with parameters, `args` would become required and typed to match those parameters. #### Attestation and loan request logic[​](#attestation-and-loan-request-logic "Direct link to Attestation and loan request logic") This section handles the core loan flow: computing the user's public key hash, fetching a Schnorr attestation from the API, storing it in private state, and submitting the loan request transaction: ``` const bytes32Type = new CompactTypeBytes(32); const { pureCircuits } = ZKLoanCreditScorer; // Derive the per-user public key off-chain from the local user secret and a // PIN, using the same pure circuit the contract uses on-chain. The user // secret comes from private state — it is the only authoritative identity // for the caller, since `ownPublicKey()` is prover-claimed and not used. export const deriveUserPublicKey = (userSecretKey: Uint8Array, pin: bigint): Uint8Array => { return pureCircuits.deriveUserPublicKey(userSecretKey, pin); }; // Compute the userPubKeyHash for an attestation message. Matches what the // contract computes inside `requestLoan` via // `transientHash(deriveUserPublicKey(secret, pin))`. export const computeUserPubKeyHash = ( userSecretKey: Uint8Array, pin: bigint, ): bigint => { const pubKey = deriveUserPublicKey(userSecretKey, pin); return transientHash(bytes32Type, pubKey); }; export const fetchAttestation = async ( attestationApiUrl: string, creditScore: number, monthlyIncome: number, monthsAsCustomer: number, userPubKeyHash: bigint, ): Promise<{ announcement: { x: bigint; y: bigint }; response: bigint; }> => { const res = await fetch(`${attestationApiUrl}/attest`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ creditScore, monthlyIncome, monthsAsCustomer, userPubKeyHash: userPubKeyHash.toString(), }), }); if (!res.ok) { throw new Error( `Attestation API error: ${res.status} ${await res.text()}`, ); } const data = (await res.json()) as { signature: { announcement: { x: string; y: string }; response: string; }; }; return { announcement: { x: BigInt(data.signature.announcement.x), y: BigInt(data.signature.announcement.y), }, response: BigInt(data.signature.response), }; }; export const requestLoan = async ( contract: DeployedZKLoanCreditScorerContract, providers: ZKLoanCreditScorerProviders, amountRequested: bigint, secretPin: bigint, attestationApiUrl: string, ): Promise => { // 1. Get current private state (must contain `userSecretKey`) const currentState = await providers.privateStateProvider.get( 'zkLoanCreditScorerPrivateState', ); if (!currentState) { throw new Error('No private state found'); } // 2. Compute user pub key hash from the user secret (same as the circuit) const userPubKeyHash = computeUserPubKeyHash( currentState.userSecretKey, secretPin, ); logger.info(`Computed userPubKeyHash for attestation`); // 3. Fetch attestation signature from API logger.info(`Fetching attestation from ${attestationApiUrl}...`); const signature = await fetchAttestation( attestationApiUrl, Number(currentState.creditScore), Number(currentState.monthlyIncome), Number(currentState.monthsAsCustomer), userPubKeyHash, ); // 4. Get provider info const providerRes = await fetch(`${attestationApiUrl}/provider-info`); const providerInfo = (await providerRes.json()) as { providerId: number; }; // 5. Update private state with attestation data const updatedState: ZKLoanCreditScorerPrivateState = { ...currentState, attestationSignature: signature, attestationProviderId: BigInt(providerInfo.providerId), }; await providers.privateStateProvider.set( 'zkLoanCreditScorerPrivateState', updatedState, ); logger.info( `Private state updated with attestation (provider ${providerInfo.providerId})`, ); // 6. Call the circuit logger.info( `Requesting loan for $${amountRequested} (USD) with PIN...`, ); const finalizedTxData = await contract.callTx.requestLoan( amountRequested, secretPin, ); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; ``` This is the core loan flow from the CLI's perspective. `requestLoan` does four things in sequence: 1. Reads `userSecretKey` from local private state and derives the user's public key hash with `computeUserPubKeyHash(userSecretKey, pin)`. The function no longer takes `zwapKeyBytes` — identity comes from the witness secret, not the wallet's coin public key. The wallet still pays for the transaction via the standard Zswap balancing flow, but does not *identify* the user. 2. Sends the credit data to the attestation API, which returns a Schnorr signature. 3. Stores the signature and provider ID in the local private state. 4. Calls `requestLoan` on the smart contract. The proof server reads private state (including the attestation and the user secret) and generates the ZK proof. The `computeUserPubKeyHash` function uses the same `deriveUserPublicKey` pure circuit the smart contract uses on-chain. Calling the generated `pureCircuits.deriveUserPublicKey` from TypeScript guarantees the off-chain hash and the in-circuit hash agree, so the attestation message and the in-proof identity match. #### Circuit call wrappers and state display[​](#circuit-call-wrappers-and-state-display "Direct link to Circuit call wrappers and state display") Each wrapper function below maps to a single smart contract circuit. They all follow the same pattern: log the action, call `contract.callTx.()`, and return the finalized transaction data. The `displayContractState` function queries the indexer for the current on-chain ledger state. ``` export const changePin = async ( contract: DeployedZKLoanCreditScorerContract, oldPin: bigint, newPin: bigint, ): Promise => { logger.info('Changing PIN...'); const finalizedTxData = await contract.callTx.changePin(oldPin, newPin); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; // Blacklist a user by their derived `UserPublicKey` (the value the contract // checks inside `assert(!blacklist.member(deriveUserPublicKey(...)))`). The // admin must obtain this 32-byte value out of band — typically by reading // the on-chain `loans` map keys for users who have already interacted, or // by asking the target to share their derived pubkey directly. Note that // admin cannot blacklist by wallet address, since `ownPublicKey()` is not // trusted by the contract. export const blacklistUser = async ( contract: DeployedZKLoanCreditScorerContract, userPublicKey: Uint8Array, ): Promise => { logger.info('Blacklisting user public key...'); const finalizedTxData = await contract.callTx.blacklistUser(userPublicKey); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; export const removeBlacklistUser = async ( contract: DeployedZKLoanCreditScorerContract, userPublicKey: Uint8Array, ): Promise => { logger.info('Removing user public key from blacklist...'); const finalizedTxData = await contract.callTx.removeBlacklistUser(userPublicKey); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; // Hand the admin role over by writing the new admin's derived public key to // the ledger. The new admin generates their secret locally and computes // `deriveAdminPublicKey(userSecret)` off-chain; only the resulting 32-byte // public key crosses the wire. No private key is ever transmitted. export const rotateAdmin = async ( contract: DeployedZKLoanCreditScorerContract, newAdminPublicKey: Uint8Array, ): Promise => { logger.info('Rotating admin role to new derived public key...'); const finalizedTxData = await contract.callTx.rotateAdmin(newAdminPublicKey); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; // Compute the AdminPublicKey for a given user secret. Run by a prospective // new admin to obtain the 32-byte public key they hand to the current admin. // Same `userSecretKey` is used for both per-user identity (PIN-bound) and // the admin role (no PIN) — different domain separators inside the contract // keep them logically independent. export const deriveAdminPublicKey = (userSecretKey: Uint8Array): Uint8Array => { return pureCircuits.deriveAdminPublicKey(userSecretKey); }; export const registerProvider = async ( contract: DeployedZKLoanCreditScorerContract, providerId: bigint, providerPk: { x: bigint; y: bigint }, ): Promise => { logger.info(`Registering attestation provider ${providerId}...`); const finalizedTxData = await contract.callTx.registerProvider( providerId, providerPk, ); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; export const removeProvider = async ( contract: DeployedZKLoanCreditScorerContract, providerId: bigint, ): Promise => { logger.info(`Removing attestation provider ${providerId}...`); const finalizedTxData = await contract.callTx.removeProvider(providerId); logger.info( `Transaction ${finalizedTxData.public.txId} added in block ${finalizedTxData.public.blockHeight}`, ); return finalizedTxData.public; }; export const displayContractState = async ( providers: ZKLoanCreditScorerProviders, contract: DeployedZKLoanCreditScorerContract, ): Promise<{ ledgerState: ZKLoanCreditScorer.Ledger | null; contractAddress: string; }> => { const contractAddress = contract.deployTxData.public.contractAddress; const ledgerState = await getZKLoanLedgerState( providers, contractAddress, ); if (ledgerState === null) { logger.info( `There is no ZKLoan contract deployed at ${contractAddress}.`, ); } else { logger.info(`Contract address: ${contractAddress}`); logger.info( `Admin public key: ${Buffer.from(ledgerState.contractAdmin).toString('hex')}`, ); logger.info(`Blacklist size: ${ledgerState.blacklist.size()}`); } return { contractAddress, ledgerState }; }; ``` Each circuit call wrapper follows the same pattern: 1. Log the action. 2. Call `contract.callTx.()`. 3. Log the transaction ID and block height. 4. Return the finalized transaction data. The SDK handles proof generation, transaction balancing, and submission behind the scenes. #### Wallet and provider infrastructure[​](#wallet-and-provider-infrastructure "Direct link to Wallet and provider infrastructure") The code block below defines `createWalletAndMidnightProvider`. It waits for the wallet to sync with the indexer, then returns a combined wallet and Midnight provider that the SDK uses to balance and submit transactions. The wider wallet setup (polling for funds and registering tNIGHT UTXOs for tDUST generation) is covered in the sections that follow. ``` export const createWalletAndMidnightProvider = async ( walletContext: WalletContext, ): Promise => { await Rx.firstValueFrom( walletContext.wallet.state().pipe(Rx.filter((s) => s.isSynced)), ); return { getCoinPublicKey(): ledger.CoinPublicKey { return walletContext.shieldedSecretKeys.coinPublicKey; }, getEncryptionPublicKey(): ledger.EncPublicKey { return walletContext.shieldedSecretKeys.encryptionPublicKey; }, async balanceTx( tx: UnboundTransaction, ttl?: Date, ): Promise { const txTtl = ttl ?? new Date(Date.now() + 30 * 60 * 1000); const recipe = await walletContext.wallet.balanceUnboundTransaction( tx, { shieldedSecretKeys: walletContext.shieldedSecretKeys, dustSecretKey: walletContext.dustSecretKey, }, { ttl: txTtl }, ); const finalizedTx = await walletContext.wallet.finalizeRecipe(recipe); return finalizedTx; }, async submitTx( tx: ledger.FinalizedTransaction, ): Promise { return await walletContext.wallet.submitTransaction(tx); }, }; }; export const waitForSync = (wallet: WalletFacade) => Rx.firstValueFrom( wallet.state().pipe( Rx.throttleTime(5_000), Rx.tap((state) => { logger.info(`Waiting for wallet sync. Synced: ${state.isSynced}`); }), Rx.filter((state) => state.isSynced), ), ); export const waitForFunds = (wallet: WalletFacade) => Rx.firstValueFrom( wallet.state().pipe( Rx.throttleTime(10_000), Rx.tap((state) => { const unshielded = state.unshielded?.balances[ledger.nativeToken().raw] ?? 0n; const shielded = state.shielded?.balances[ledger.nativeToken().raw] ?? 0n; logger.info( `Waiting for NIGHT funds. Synced: ${state.isSynced}, Unshielded: ${unshielded}, Shielded: ${shielded}`, ); }), Rx.filter((state) => state.isSynced), Rx.map( (s) => (s.unshielded?.balances[ledger.nativeToken().raw] ?? 0n) + (s.shielded?.balances[ledger.nativeToken().raw] ?? 0n), ), Rx.filter((balance) => balance > 0n), ), ); export const displayWalletBalances = async ( wallet: WalletFacade, ): Promise<{ unshielded: bigint; shielded: bigint; total: bigint; dust: bigint; }> => { const state = await Rx.firstValueFrom(wallet.state()); const unshielded = state.unshielded?.balances[ledger.nativeToken().raw] ?? 0n; const shielded = state.shielded?.balances[ledger.nativeToken().raw] ?? 0n; const total = unshielded + shielded; const dust = state.dust?.balance(new Date()) ?? 0n; logger.info(`Unshielded NIGHT balance: ${unshielded}`); logger.info(`Shielded NIGHT balance: ${shielded}`); logger.info(`Total NIGHT balance: ${total}`); logger.info(`DUST balance (for fees): ${dust}`); return { unshielded, shielded, total, dust }; }; export const registerNightForDust = async ( walletContext: WalletContext, ): Promise => { const state = await Rx.firstValueFrom( walletContext.wallet.state().pipe(Rx.filter((s) => s.isSynced)), ); const unregisteredNightUtxos = state.unshielded?.availableCoins.filter( (coin) => coin.meta.registeredForDustGeneration === false, ) ?? []; if (unregisteredNightUtxos.length === 0) { logger.info( 'No unshielded Night UTXOs available for dust registration, or all are already registered', ); const dustBalance = state.dust?.balance(new Date()) ?? 0n; logger.info(`Current dust balance: ${dustBalance}`); return dustBalance > 0n; } logger.info( `Found ${unregisteredNightUtxos.length} unshielded Night UTXOs not registered for dust generation`, ); logger.info('Registering Night UTXOs for dust generation...'); try { const recipe = await walletContext.wallet.registerNightUtxosForDustGeneration( unregisteredNightUtxos, walletContext.unshieldedKeystore.getPublicKey(), (payload) => walletContext.unshieldedKeystore.signData(payload), ); logger.info('Finalizing dust registration transaction...'); const finalizedTx = await walletContext.wallet.finalizeRecipe(recipe); logger.info('Submitting dust registration transaction...'); const txId = await walletContext.wallet.submitTransaction(finalizedTx); logger.info(`Dust registration submitted with tx id: ${txId}`); logger.info('Waiting for dust to be generated...'); await Rx.firstValueFrom( walletContext.wallet.state().pipe( Rx.throttleTime(5_000), Rx.tap((s) => { const dustBalance = s.dust?.balance(new Date()) ?? 0n; logger.info(`Dust balance: ${dustBalance}`); }), Rx.filter( (s) => (s.dust?.balance(new Date()) ?? 0n) > 0n, ), ), ); logger.info('Dust registration complete!'); return true; } catch (e) { logger.error(`Failed to register Night UTXOs for dust: ${e}`); return false; } }; ``` The wallet infrastructure handles three concerns: * **Syncing**: `waitForSync` polls the wallet state every 5 seconds until it is synchronized with the indexer. * **Funding**: `waitForFunds` polls every 10 seconds until the wallet has a non-zero balance (shielded + unshielded). * **Dust registration**: `registerNightForDust` registers unshielded tNIGHT UTXOs for tDUST generation. On Midnight, **NIGHT is the user-facing token** and **DUST is the fee resource generated from registered NIGHT UTXOs** (testnet variants are tNIGHT and tDUST). DUST tokens are required to pay [transaction fees](/concepts/how-midnight-works/midnight-combined-model.md) on Midnight Network. Without DUST, no transactions can be submitted. #### Wallet initialization[​](#wallet-initialization "Direct link to Wallet initialization") The code block below derives three key roles (Zswap, NightExternal, Dust) from a single seed — produced from a BIP-39 mnemonic, or supplied directly as a hex string — initializes the corresponding wallets, and waits for synchronization and funding before returning a ready-to-use wallet context. ``` // Validate a BIP-39 mnemonic and convert it to a seed buffer export const mnemonicToSeed = async ( mnemonic: string, ): Promise => { const words = mnemonic.trim().split(/\s+/); if (!bip39.validateMnemonic(words.join(' '), english)) { throw new Error('Invalid mnemonic phrase'); } const seed = await bip39.mnemonicToSeed(words.join(' ')); return Buffer.from(seed); }; // Derive wallet keys from a seed and initialize all three wallet types export const initWalletWithSeed = async ( seed: Buffer, config: Config, ): Promise => { const hdWallet = HDWallet.fromSeed(seed); if (hdWallet.type !== 'seedOk') { throw new Error('Failed to initialize HDWallet'); } const derivationResult = hdWallet.hdWallet .selectAccount(0) .selectRoles([Roles.Zswap, Roles.NightExternal, Roles.Dust]) .deriveKeysAt(0); if (derivationResult.type !== 'keysDerived') { throw new Error('Failed to derive keys'); } hdWallet.hdWallet.clear(); // Create secret keys for each wallet role const shieldedSecretKeys = ledger.ZswapSecretKeys.fromSeed( derivationResult.keys[Roles.Zswap], ); const dustSecretKey = ledger.DustSecretKey.fromSeed( derivationResult.keys[Roles.Dust], ); const unshieldedKeystore = createKeystore( derivationResult.keys[Roles.NightExternal], config.networkId as any, ); const relayURL = new URL(config.node.replace(/^http/, 'ws')); const shieldedConfig = { networkId: config.networkId, indexerClientConnection: { indexerHttpUrl: config.indexer, indexerWsUrl: config.indexerWS, }, provingServerUrl: new URL(config.proofServer), relayURL, // As of wallet-sdk 1.x, every wallet variant's default configuration // (shielded / unshielded / dust) requires its own transaction-history // storage. `InMemoryTransactionHistoryStorage` now takes a schema — // the barrel re-exports `WalletEntrySchema` for exactly this use. txHistoryStorage: new InMemoryTransactionHistoryStorage(WalletEntrySchema), }; const unshieldedConfig = { networkId: config.networkId, indexerClientConnection: { indexerHttpUrl: config.indexer, indexerWsUrl: config.indexerWS, }, txHistoryStorage: new InMemoryTransactionHistoryStorage(WalletEntrySchema), }; const dustConfig = { networkId: config.networkId, costParameters: { additionalFeeOverhead: 300_000_000_000_000n, feeBlocksMargin: 5, }, indexerClientConnection: { indexerHttpUrl: config.indexer, indexerWsUrl: config.indexerWS, }, provingServerUrl: new URL(config.proofServer), relayURL, txHistoryStorage: new InMemoryTransactionHistoryStorage(WalletEntrySchema), }; // Combine the per-wallet configs into a single configuration the facade // can use to initialize all three wallets, then build them through the // unified factory. `WalletFacade`'s constructor is private in v3 — use // `WalletFacade.init({ configuration, shielded, unshielded, dust })`. const unifiedConfig = { ...shieldedConfig, ...unshieldedConfig, ...dustConfig }; const facade = await WalletFacade.init({ configuration: unifiedConfig, shielded: () => ShieldedWallet(shieldedConfig).startWithSecretKeys(shieldedSecretKeys), unshielded: () => UnshieldedWallet(unshieldedConfig).startWithPublicKey( UnshieldedPublicKey.fromKeyStore(unshieldedKeystore), ), dust: () => DustWallet(dustConfig).startWithSecretKey( dustSecretKey, ledger.LedgerParameters.initialParameters().dust, ), }); await facade.start(shieldedSecretKeys, dustSecretKey); return { wallet: facade, shieldedSecretKeys, dustSecretKey, unshieldedKeystore, }; }; // High-level: Create wallet from mnemonic, sync, wait for funds, register dust export const buildWalletAndWaitForFunds = async ( config: Config, mnemonic: string, ): Promise => { logger.info('Building wallet from mnemonic...'); const seed = await mnemonicToSeed(mnemonic); const walletContext = await initWalletWithSeed(seed, config); logger.info( `Your wallet address: ${walletContext.unshieldedKeystore.getBech32Address().asString()}`, ); logger.info('Waiting for wallet to sync...'); await waitForSync(walletContext.wallet); const { total } = await displayWalletBalances(walletContext.wallet); if (total === 0n) { logger.info('Waiting to receive tokens...'); await waitForFunds(walletContext.wallet); await displayWalletBalances(walletContext.wallet); } await registerNightForDust(walletContext); return walletContext; }; // Generate a new BIP-39 mnemonic and build a wallet from it export const buildFreshWallet = async ( config: Config, ): Promise => { const mnemonic = bip39.generateMnemonic(english, 256); logger.info(`Generated new wallet mnemonic: ${mnemonic}`); return await buildWalletAndWaitForFunds(config, mnemonic); }; // Build wallet from a hex seed (for the genesis wallet on the local network) export const buildWalletFromHexSeed = async ( config: Config, hexSeed: string, ): Promise => { logger.info('Building wallet from hex seed...'); const seed = Buffer.from(hexSeed, 'hex'); const walletContext = await initWalletWithSeed(seed, config); logger.info( `Your wallet address: ${walletContext.unshieldedKeystore.getBech32Address().asString()}`, ); logger.info('Waiting for wallet to sync...'); await waitForSync(walletContext.wallet); const { total } = await displayWalletBalances(walletContext.wallet); if (total === 0n) { logger.info('Waiting to receive tokens...'); await waitForFunds(walletContext.wallet); await displayWalletBalances(walletContext.wallet); } await registerNightForDust(walletContext); return walletContext; }; ``` The wallet initialization derives three key roles from a single BIP-39 mnemonic: * **Zswap**: Used for shielded (private) transactions and ZK proof generation * **NightExternal**: Used for unshielded (transparent) operations like receiving tNIGHT from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/) * **DUST**: Used for generating DUST tokens that pay transaction fees `buildWalletAndWaitForFunds` is the high-level function the CLI calls when targeting Preprod. It converts the mnemonic to a seed, initializes all three wallet types, waits for synchronization, checks the balance, and registers NIGHT UTXOs for DUST generation. `buildWalletFromHexSeed` follows the same steps but starts from a raw hex seed instead of a mnemonic — on the local standalone network the CLI uses it with the well-known genesis seed, whose funds already exist in the genesis block. #### Provider configuration and utilities[​](#provider-configuration-and-utilities "Direct link to Provider configuration and utilities") `configureProviders` assembles the six SDK providers (wallet, Midnight, proof, ZK config, public data, and private state) into a single bundle. The `setLogger` and `closeWallet` utilities manage the module-level logger and clean up wallet resources on exit. ``` export const configureProviders = async ( walletContext: WalletContext, config: Config, ): Promise => { setNetworkId(config.networkId); const walletAndMidnightProvider = await createWalletAndMidnightProvider(walletContext); const storagePassword = process.env.MIDNIGHT_STORAGE_PASSWORD; if (!storagePassword) { throw new Error( 'MIDNIGHT_STORAGE_PASSWORD is not set. Set it in zkloan-credit-scorer-cli/.env (see .env.example). ' + 'The level-private-state-provider requires it to encrypt private state on disk.', ); } const zkConfigProvider = new NodeZkConfigProvider( contractConfig.zkConfigPath, ); return { privateStateProvider: levelPrivateStateProvider< typeof ZKLoanCreditScorerPrivateStateId >({ privateStateStoreName: contractConfig.privateStateStoreName, privateStoragePasswordProvider: () => storagePassword, accountId: walletContext.unshieldedKeystore.getBech32Address().asString(), }), publicDataProvider: indexerPublicDataProvider( config.indexer, config.indexerWS, ), zkConfigProvider, proofProvider: httpClientProofProvider( config.proofServer, zkConfigProvider, ), walletProvider: walletAndMidnightProvider, midnightProvider: walletAndMidnightProvider, }; }; export function setLogger(_logger: Logger) { logger = _logger; } export const closeWallet = async ( walletContext: WalletContext, ): Promise => { try { await walletContext.wallet.stop(); } catch (e) { logger.error(`Error closing wallet: ${e}`); } }; ``` `configureProviders` assembles all six providers the SDK requires. The private state provider stores sensitive data (credit profiles and attestation signatures) in an encrypted LevelDB database on disk. The proof provider sends proving requests to the local Docker proof server on port `6300`. Storage password is mandatory The `levelPrivateStateProvider` (Midnight JS `4.x`) refuses to run without a strong `MIDNIGHT_STORAGE_PASSWORD`. There is no longer a default fallback. The password must: * Be at least 16 characters long. * Contain characters from at least three of these groups: uppercase, lowercase, digits, special characters. * Avoid four or more identical characters in a row, such as `aaaa`. * Avoid four or more sequential character codes, such as `abcd` or `1234`. Losing the password means losing access to the encrypted private state on disk — there is no recovery. The provider is also scoped per `accountId` (the wallet's Bech32 address). If you run more than one wallet against the same store without scoping, the operations fail. ### Interactive CLI[​](#interactive-cli "Direct link to Interactive CLI") With the API module handling all the SDK interactions, the CLI module is responsible for the user-facing layer: prompting for input, routing choices to the correct API function, and handling errors without crashing. It uses Node's built-in `readline/promises` for interactive terminal input. Create `zkloan-credit-scorer-cli/src/cli.ts` and add the following sections in order. #### Imports and menu prompts[​](#imports-and-menu-prompts "Direct link to Imports and menu prompts") The code block below sets up the CLI's foundation. It imports the API module, the shared type definitions, the `testcontainers` types (used when the test suite drives the CLI against Docker containers), and Node's `readline` for interactive terminal input. It then declares the genesis wallet seed and two menu prompt strings: * `GENESIS_MINT_WALLET_SEED`: the well-known seed that owns the tokens minted in a local development node's genesis block — used only on standalone networks to build a pre-funded wallet. * `DEPLOY_OR_JOIN_QUESTION`: the first menu, shown after wallet setup, asking whether to deploy a new contract or join an existing one. * `MAIN_LOOP_QUESTION`: the main menu, shown after a contract is deployed or joined, listing the loan and admin actions. ``` import { stdin as input, stdout as output } from "node:process"; import { createInterface, type Interface } from "node:readline/promises"; import { type Logger } from "pino"; import { type StartedDockerComposeEnvironment, type DockerComposeEnvironment, } from "testcontainers"; import { type ZKLoanCreditScorerProviders, type DeployedZKLoanCreditScorerContract, } from "./common-types"; import { type Config, StandaloneConfig } from "./config"; import * as api from "./api"; import type { WalletContext } from "./api"; import { getUserProfile } from "./state.utils"; import "dotenv/config"; let logger: Logger; /** * This seed gives access to tokens minted in the genesis block of a local development node - only * used in standalone networks to build a wallet with initial funds. */ const GENESIS_MINT_WALLET_SEED = "0000000000000000000000000000000000000000000000000000000000000001"; // Menu prompt shown after wallet setup const DEPLOY_OR_JOIN_QUESTION = ` You can do one of the following: 1. Deploy a new ZKLoan Credit Scorer contract 2. Join an existing ZKLoan Credit Scorer contract 3. Exit Which would you like to do? `; // Menu prompt shown after contract deploy/join const MAIN_LOOP_QUESTION = ` You can do one of the following: 1. Request a loan 2. Change PIN 3. Display contract state 4. Display wallet balances 5. [Admin] Blacklist a user 6. [Admin] Remove user from blacklist 7. [Admin] Rotate admin role to new derived public key 8. [Admin] Register attestation provider 9. [Admin] Remove attestation provider 10. Exit Which would you like to do? `; ``` #### Deploy or join helpers[​](#deploy-or-join-helpers "Direct link to Deploy or join helpers") These functions prompt the user to deploy a new contract or connect to an existing one by address: ``` // Connect to an existing deployed contract by address const join = async ( providers: ZKLoanCreditScorerProviders, rli: Interface, ): Promise => { const contractAddress = await rli.question( "What is the contract address (in hex)? ", ); return await api.joinContract(providers, contractAddress); }; // Present the deploy/join/exit menu and handle the user's choice const deployOrJoin = async ( providers: ZKLoanCreditScorerProviders, rli: Interface, ): Promise => { while (true) { const choice = await rli.question(DEPLOY_OR_JOIN_QUESTION); switch (choice) { case "1": return await api.deploy(providers, getUserProfile()); case "2": return await join(providers, rli); case "3": logger.info("Exiting..."); return null; default: logger.error(`Invalid choice: ${choice}`); } } }; ``` #### Loan and PIN flow functions[​](#loan-and-pin-flow-functions "Direct link to Loan and PIN flow functions") These functions handle the two user-facing operations: requesting a loan (which involves fetching an attestation) and changing a PIN (which triggers batched loan migration): ``` // Prompt for amount and PIN, fetch attestation, and submit loan request const requestLoan = async ( contract: DeployedZKLoanCreditScorerContract, providers: ZKLoanCreditScorerProviders, _walletContext: WalletContext, rli: Interface, ): Promise => { const amountStr = await rli.question( "Enter the loan amount (USD, 1-65535 — the contract caps approvals at $10,000 / $7,000 / $3,000 per tier): ", ); const pinStr = await rli.question("Enter your secret PIN: "); const amount = BigInt(amountStr); const pin = BigInt(pinStr); const attestationApiUrl = process.env.ATTESTATION_API_URL || "http://localhost:4000"; await api.requestLoan( contract, providers, amount, pin, attestationApiUrl, ); logger.info("Loan request submitted successfully!"); }; // Prompt for old and new PIN, then submit the PIN change transaction const changePinFlow = async ( contract: DeployedZKLoanCreditScorerContract, rli: Interface, ): Promise => { const oldPinStr = await rli.question("Enter your old PIN: "); const newPinStr = await rli.question("Enter your new PIN: "); await api.changePin(contract, BigInt(oldPinStr), BigInt(newPinStr)); logger.info("PIN change submitted successfully!"); logger.info( "Note: If you have many loans, you may need to call this multiple times to complete the migration.", ); }; ``` #### Admin flow functions[​](#admin-flow-functions "Direct link to Admin flow functions") All five admin operations — blacklist, unblock, register/remove provider, and rotate — use the **witness-derived keypair pattern**. Each circuit's first assertion forces the caller, inside the ZK proof, to demonstrate knowledge of the 32-byte secret whose admin-derivation is stored in `contractAdmin`. Only the deploying admin holds that secret; for everyone else the circuit fails to satisfy its constraints and the transaction reverts. Rotation is the only way to change who holds admin authority, and it works by the new admin generating their own user secret locally and sharing only the resulting admin public key. The blacklist flows take a derived `UserPublicKey` (64 hex chars), not a wallet address. Admin obtains this value either by reading the on-chain `loans` map (where it appears as the key for any user who has interacted) or out-of-band from the target. Admin cannot preemptively blacklist a user who has not yet touched the contract — that's a deliberate trade-off for unforgeable caller identity. Each admin function prompts for the required input and delegates to the corresponding API wrapper. Only the deployer (admin) can execute these operations: ``` const USER_PUBKEY_PROMPT_HINT = '(64-char hex of the user\'s derived UserPublicKey — e.g. read from the on-chain `loans` map key, or shared by the target)'; const parseUserPublicKeyHex = (input: string): Uint8Array => { const hex = input.trim().toLowerCase().replace(/^0x/, ''); if (!/^[0-9a-f]{64}$/.test(hex)) { throw new Error('User public key must be exactly 64 hex chars (32 bytes).'); } return Uint8Array.from(Buffer.from(hex, 'hex')); }; const blacklistUserFlow = async ( contract: DeployedZKLoanCreditScorerContract, rli: Interface, ): Promise => { const input = await rli.question( `Enter the user public key to blacklist ${USER_PUBKEY_PROMPT_HINT}: `, ); await api.blacklistUser(contract, parseUserPublicKeyHex(input)); logger.info('User public key blacklisted successfully!'); }; const removeBlacklistUserFlow = async ( contract: DeployedZKLoanCreditScorerContract, rli: Interface, ): Promise => { const input = await rli.question( `Enter the user public key to remove from blacklist ${USER_PUBKEY_PROMPT_HINT}: `, ); await api.removeBlacklistUser(contract, parseUserPublicKeyHex(input)); logger.info('User public key removed from blacklist successfully!'); }; // Rotate the admin role to a public key the new admin already derived // locally. The new admin runs `deriveAdminPublicKey(userSecret)` against // their own 32-byte user secret and hands the resulting public key (64 hex // chars) to the current admin. No private key is exchanged. const rotateAdminFlow = async ( contract: DeployedZKLoanCreditScorerContract, rli: Interface, ): Promise => { const input = await rli.question( 'Enter the new admin derived public key (64 hex chars). ' + 'The new admin generates this with `deriveAdminPublicKey(userSecret)` and shares only the result: ', ); await api.rotateAdmin(contract, parseUserPublicKeyHex(input)); logger.info('Admin role rotated successfully!'); }; // Register an attestation provider's public key on-chain const registerProviderFlow = async ( contract: DeployedZKLoanCreditScorerContract, rli: Interface, ): Promise => { const providerIdStr = await rli.question("Enter the provider ID (number): "); const pkXStr = await rli.question( "Enter the provider public key X coordinate (bigint): ", ); const pkYStr = await rli.question( "Enter the provider public key Y coordinate (bigint): ", ); await api.registerProvider(contract, BigInt(providerIdStr), { x: BigInt(pkXStr), y: BigInt(pkYStr), }); logger.info("Attestation provider registered successfully!"); }; // Remove an attestation provider by ID const removeProviderFlow = async ( contract: DeployedZKLoanCreditScorerContract, rli: Interface, ): Promise => { const providerIdStr = await rli.question( "Enter the provider ID to remove (number): ", ); await api.removeProvider(contract, BigInt(providerIdStr)); logger.info("Attestation provider removed successfully!"); }; ``` #### Main loop and wallet selection[​](#main-loop-and-wallet-selection "Direct link to Main loop and wallet selection") The main loop presents the ten-option menu and routes each choice to the corresponding flow function. Wallet selection depends on the network: on the local standalone network the CLI skips the menu entirely and builds a pre-funded wallet from the genesis seed, while on Preprod it prompts the user to create or restore a wallet before entering the main loop: ``` // Main interaction loop — routes menu choices to flow functions const mainLoop = async ( providers: ZKLoanCreditScorerProviders, walletContext: WalletContext, rli: Interface, ): Promise => { const contract = await deployOrJoin(providers, rli); if (contract === null) return; while (true) { const choice = await rli.question(MAIN_LOOP_QUESTION); try { switch (choice) { case "1": await requestLoan(contract, providers, walletContext, rli); break; case "2": await changePinFlow(contract, rli); break; case "3": await api.displayContractState(providers, contract); break; case "4": await api.displayWalletBalances(walletContext.wallet); break; case "5": await blacklistUserFlow(contract, rli); break; case "6": await removeBlacklistUserFlow(contract, rli); break; case "7": await rotateAdminFlow(contract, rli); break; case "8": await registerProviderFlow(contract, rli); break; case "9": await removeProviderFlow(contract, rli); break; case "10": logger.info("Exiting..."); return; default: logger.error(`Invalid choice: ${choice}`); } } catch (e) { if (e instanceof Error) { logger.error(`Operation failed: ${e.message}`); } else { logger.error(`Operation failed: ${e}`); } } } }; // Wallet creation/restore menu const WALLET_LOOP_QUESTION = ` You can do one of the following: 1. Build a fresh wallet 2. Build wallet from a mnemonic 3. Use mnemonic from .env file 4. Exit Which would you like to do? `; // Return the initialized wallet context. On the standalone (local) network // the menu is skipped and the genesis wallet is built from its hex seed; // otherwise the wallet options menu is presented. const buildWallet = async ( config: Config, rli: Interface, ): Promise => { if (config instanceof StandaloneConfig) { // For standalone, use genesis wallet with hex seed return await api.buildWalletFromHexSeed(config, GENESIS_MINT_WALLET_SEED); } // Check if mnemonic is available in environment const envMnemonic = process.env.WALLET_MNEMONIC; while (true) { const choice = await rli.question(WALLET_LOOP_QUESTION); switch (choice) { case "1": return await api.buildFreshWallet(config); case "2": { const mnemonic = await rli.question( "Enter your wallet mnemonic (24 words): ", ); return await api.buildWalletAndWaitForFunds(config, mnemonic); } case "3": if (envMnemonic) { logger.info("Using mnemonic from .env file..."); return await api.buildWalletAndWaitForFunds(config, envMnemonic); } else { logger.error("No WALLET_MNEMONIC found in .env file"); } break; case "4": logger.info("Exiting..."); return null; default: logger.error(`Invalid choice: ${choice}`); } } }; // Rewrite a config URL so its port matches the host port that // testcontainers mapped for the named container const mapContainerPort = ( env: StartedDockerComposeEnvironment, url: string, containerName: string, ) => { const mappedUrl = new URL(url); const container = env.getContainer(containerName); mappedUrl.port = String(container.getFirstMappedPort()); return mappedUrl.toString().replace(/\/+$/, ""); }; // Entry point — build wallet, configure providers, enter main loop export const run = async ( config: Config, _logger: Logger, dockerEnv?: DockerComposeEnvironment, ): Promise => { logger = _logger; api.setLogger(_logger); const rli = createInterface({ input, output, terminal: true }); let env; let walletContext: WalletContext | null = null; if (dockerEnv !== undefined) { env = await dockerEnv.up(); if (config instanceof StandaloneConfig) { config.indexer = mapContainerPort(env, config.indexer, "zkloan-indexer"); config.indexerWS = mapContainerPort(env, config.indexerWS, "zkloan-indexer"); config.node = mapContainerPort(env, config.node, "zkloan-node"); config.proofServer = mapContainerPort( env, config.proofServer, "zkloan-proof-server", ); } } try { walletContext = await buildWallet(config, rli); if (walletContext !== null) { const providers = await api.configureProviders(walletContext, config); await mainLoop(providers, walletContext, rli); } } catch (e) { if (e instanceof Error) { logger.error(`Found error '${e.message}'`); logger.info("Exiting..."); logger.debug(`${e.stack}`); } else { throw e; } } finally { try { rli.close(); rli.removeAllListeners(); } catch (e) { logger.error(`Error closing readline interface: ${e}`); } finally { try { if (walletContext !== null) { await api.closeWallet(walletContext); } } catch (e) { logger.error(`Error closing wallet: ${e}`); } finally { try { if (env !== undefined) { await env.down(); logger.info("Goodbye"); } } catch (e) { logger.error(`Error shutting down docker environment: ${e}`); } } } } }; ``` The CLI has three layers of interaction: * **Wallet selection**: On the local standalone network this is automatic — the CLI builds the genesis wallet from `GENESIS_MINT_WALLET_SEED`, which already holds funds. On Preprod a menu offers to generate a fresh wallet, restore from a mnemonic, or load the mnemonic from the `.env` file. * **Deploy or join**: Deploy a new smart contract or connect to an existing one by address. * **Main loop**: The ten-option menu for loan requests, admin operations, and state inspection. Each menu option maps to a flow function that prompts for input and calls the corresponding API function. Errors are caught and logged without crashing the CLI, so you can retry operations. The optional third parameter of `run`, `dockerEnv`, is used by the test suite: it passes a testcontainers `DockerComposeEnvironment`, which `run` starts and tears down itself, rewriting the standalone config's URLs to the dynamically mapped container ports via `mapContainerPort`. When you run the CLI interactively, this parameter is omitted and the CLI connects to whatever network is already running. ### Entry points[​](#entry-points "Direct link to Entry points") Rather than one entry file that switches on an environment variable, the CLI ships a small entry file per network — each hardcodes its network configuration, creates the logger, and hands both to the CLI runner. A separate barrel module re-exports the API and CLI functions for consumers such as the test suite. Create `zkloan-credit-scorer-cli/src/index.ts` — the barrel: ``` export * from './api'; export * from './cli'; ``` Create `zkloan-credit-scorer-cli/src/standalone.ts` — the local-network entry point: ``` import { createLogger } from './logger-utils.js'; import { run } from './cli.js'; import { StandaloneConfig } from './config.js'; // Connects to an already-running local Midnight network (managed by midnight-local-network). // No docker containers are started here — the network must be running at the default ports: // Node: http://127.0.0.1:9944 // Indexer: http://127.0.0.1:8088 // Proof Server: http://127.0.0.1:6300 const config = new StandaloneConfig(); const logger = await createLogger(config.logDir); await run(config, logger); ``` Create `zkloan-credit-scorer-cli/src/preprod-remote.ts` — the Preprod entry point: ``` import { createLogger } from './logger-utils.js'; import { run } from './cli.js'; import { PreprodConfig } from './config.js'; const config = new PreprodConfig(); const logger = await createLogger(config.logDir); await run(config, logger); ``` The entry file you run decides the network — there is no environment variable to set. `standalone.ts` expects the local node, indexer, and proof server to already be running at the default ports; it does not start any Docker containers itself. ### Package configuration[​](#package-configuration "Direct link to Package configuration") Create `zkloan-credit-scorer-cli/package.json`: ``` { "name": "zkloan-credit-scorer-cli", "version": "0.1.0", "private": true, "type": "module", "scripts": { "preprod-remote": "node --experimental-specifier-resolution=node --loader ts-node/esm src/preprod-remote.ts", "standalone": "node --experimental-specifier-resolution=node --loader ts-node/esm src/standalone.ts", "test-api": "docker compose -f standalone.yml pull && DEBUG='testcontainers' vitest run", "test-against-preprod": "RUN_ENV_TESTS=true TEST_ENV=preprod TEST_WALLET_SEED=1dec0dd58fbe4d3206ef960aebff95a77e09dffbd19f3e9439d23fe6de4fcdd1 vitest run", "build": "rm -rf dist && tsc --project tsconfig.build.json", "lint": "eslint src", "typecheck": "tsc -p tsconfig.json --noEmit", "start-preprod-remote": "npm run build && npm run preprod-remote" }, "dependencies": { "zkloan-credit-scorer-contract": "*" } } ``` `standalone` and `preprod-remote` run the two entry points directly through ts-node — one per network. `test-api` drives the automated end-to-end suite against Docker containers (using the `standalone.yml` compose file via testcontainers), and `test-against-preprod` runs the same suite against the live Preprod network. Create `zkloan-credit-scorer-cli/tsconfig.json`: ``` { "include": ["src/**/*.ts"], "compilerOptions": { "outDir": "dist", "declaration": true, "lib": ["ESNext"], "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "allowJs": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "strict": true, "isolatedModules": true, "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true, "baseUrl": ".", "paths": { "@contract/*": ["../../contract/src/*"] } } } ``` `moduleResolution` must be `bundler` (or `node16`/`nodenext`) so TypeScript can read the `exports` subpath map published by `@midnight-ntwrk/midnight-js-protocol`. The legacy `node` resolver silently fails to find `/compact-runtime`, `/ledger`, and `/compact-js`. Create `zkloan-credit-scorer-cli/tsconfig.build.json`: ``` { "extends": "./tsconfig.json", "exclude": ["src/**/*.test.ts"], "compilerOptions": {} } ``` The CLI uses `dotenv` to load environment variables from a `.env` file in the `zkloan-credit-scorer-cli` directory. Create both a checked-in template (`.env.example`) and a local `.env`: ``` cat > zkloan-credit-scorer-cli/.env.example << 'EOF' # Password used to encrypt the contract's private state on disk via the # midnight-js-level-private-state-provider. Required. # # Rules enforced by the provider (v4+): # - At least 16 characters # - Mix of at least 3 of: uppercase, lowercase, digits, special chars # - No 4+ identical chars in a row # - No 4+ sequential char codes (e.g. 'abcd', '1234') # # Losing this password = losing access to the local encrypted private state. # The provider has no recovery mechanism. MIDNIGHT_STORAGE_PASSWORD="" # Optional BIP39 mnemonic for the wallet. If unset, the CLI uses a hex seed. # Needed when running `npm run preprod-remote` — the wallet must hold tDUST. # WALLET_MNEMONIC="" EOF cp zkloan-credit-scorer-cli/.env.example zkloan-credit-scorer-cli/.env ``` Edit `zkloan-credit-scorer-cli/.env` and set `MIDNIGHT_STORAGE_PASSWORD` to a value that satisfies the rules above. Leave `WALLET_MNEMONIC` commented out — the local standalone flow does not use it, because the CLI builds its wallet from the genesis hex seed automatically. It matters only when you target Preprod with `npm run preprod-remote`: uncomment it and paste the 24-word mnemonic of a funded wallet so you can restore it with option 3 in the CLI's wallet menu. ## Run the CLI[​](#run-the-cli "Direct link to Run the CLI") The final part brings everything together by testing the complete flow using [Midnight Local Dev](/guides/networks-and-environments.md#running-a-local-network), a standalone Docker environment that runs the Midnight node, indexer, and proof server locally. On this network the ZKLoan CLI builds its wallet from the well-known genesis seed — which already owns the tokens minted in the genesis block — and registers that NIGHT for DUST automatically, so the wallet is ready to submit transactions without any manual funding. You need three terminal windows. ### Install dependencies[​](#install-dependencies "Direct link to Install dependencies") From the project root, run: ``` npm install ``` ### Compile and build the smart contract[​](#compile-and-build-the-smart-contract "Direct link to Compile and build the smart contract") If you have not already done so in [Part 1](/tutorials/zk-loan/smart-contract.md): ``` cd contract npm run compact npm run build cd .. ``` ### Start Midnight local dev[​](#start-midnight-local-dev "Direct link to Start Midnight local dev") In your first terminal, clone the [Midnight Local Dev](https://github.com/midnightntwrk/midnight-local-dev) repo, install its dependencies, and start the network: ``` git clone https://github.com/midnightntwrk/midnight-local-dev.git cd midnight-local-dev npm install npm start ``` This pulls the Docker images and starts the node, indexer, and proof server on ports `9944`, `8088`, and `6300`. It then initializes a genesis master wallet and shows an interactive menu. If a network is already running, then the wizard first prompts you to reuse it or restart with fresh images — choose either. Leave this terminal at the main menu — the network keeps running while it is open. Closing the menu or pressing `Ctrl+C` shuts the network down. You do not need the wizard's funding options for this tutorial: the ZKLoan CLI funds itself from the genesis wallet. Containers-only alternative If you only want the bare containers without the interactive wizard, then you can use `docker compose -f standalone.yml up -d` from the same folder instead. The ZKLoan CLI still funds itself from the genesis wallet and handles DUST registration either way. ### Start the attestation API[​](#start-the-attestation-api "Direct link to Start the attestation API") In your second terminal, from the project root: ``` cd zkloan-credit-scorer-attestation-api NETWORK_ID=undeployed npm run dev ``` You should see output like: ``` Generated ephemeral provider key pair Provider ID: 1 Provider public key: x: 1234567890... y: 9876543210... Register this provider on-chain with: registerProvider(1, {x: 1234...n, y: 9876...n}) Attestation API listening on port 4000 ``` Copy the provider public key coordinates — you need them in the next step. ### Run the CLI[​](#run-the-cli-1 "Direct link to Run the CLI") In your third terminal, start the CLI from the project root: ``` cd zkloan-credit-scorer-cli npm run standalone ``` The `standalone` script runs `src/standalone.ts`, which targets the local network you started in the first terminal — there is no environment variable to set. The CLI walks you through five phases: 1. Build the wallet (automatic). 2. Deploy the contract. 3. Register the attestation provider. 4. Request a loan. 5. Inspect the on-chain state. #### 1. Build the wallet (automatic)[​](#1-build-the-wallet-automatic "Direct link to 1. Build the wallet (automatic)") On the local network there is no wallet menu and no manual funding step. The CLI detects the standalone configuration and builds its wallet from the well-known genesis seed, which owns the tokens minted in the local network's genesis block: ``` Building wallet from hex seed... Your wallet address: mn_addr_undeployed1h3ssm5ru… Waiting for wallet to sync... ``` Once the wallet syncs, the balance check finds the genesis funds and calls `registerNightForDust` automatically. When you see `Dust registration complete!`, the wallet has both NIGHT (value) and DUST (fees) and is ready to transact. Funding on Preprod The wallet menu — fresh wallet, mnemonic, or `.env` mnemonic — only appears when you target Preprod with `npm run preprod-remote`. There the CLI prints the wallet's unshielded address (`mn_addr_preprod1q…`) and waits for funds: send tNIGHT to that address from the [Preprod faucet](https://midnight-tmnight-preprod.nethermind.dev/), and store the mnemonic in `WALLET_MNEMONIC` in `zkloan-credit-scorer-cli/.env` so **option 3 (Use mnemonic from .env file)** restores the same funded wallet on later runs. #### 2. Deploy the contract[​](#2-deploy-the-contract "Direct link to 2. Deploy the contract") The CLI now shows the deploy/join menu. Pick **option 1 (Deploy a new ZKLoan Credit Scorer contract)**. The proof server generates the deployment proof — this takes about a minute. When it finishes, the CLI logs `Deployed contract at address: …` — a 64-character hex string, different on every deploy — and drops you into the main 10-option menu. #### 3. Register the attestation provider[​](#3-register-the-attestation-provider "Direct link to 3. Register the attestation provider") This step is one-time per contract. Without it, every loan request will revert because the circuit asserts the provider is registered. 1. Pick **option 8 (Register attestation provider)**. 2. Enter provider ID: `1`. 3. Paste the `x` and `y` coordinates printed by the attestation API in your second terminal. The provider's public key is now in the contract's `providers` map. #### 4. Request a loan[​](#4-request-a-loan "Direct link to 4. Request a loan") 1. Pick **option 1 (Request a loan)**. 2. Enter a loan amount in USD — for example, `5000`. Approvals are capped at $10,000 / $7,000 / $3,000 per credit tier; anything above your tier becomes a `Proposed` offer. 3. Enter a **4-digit** secret PIN — for example, `1234`. The PIN is constrained to `Uint<16>`, so longer values would overflow the circuit. The CLI fetches an attestation from the API, stores it in the local private state, and submits the loan request. After about a minute the proof completes and the transaction is finalized. #### 5. Inspect the on-chain state[​](#5-inspect-the-on-chain-state "Direct link to 5. Inspect the on-chain state") Pick **option 3 (Display contract state)**. The CLI logs the contract address, the admin public key (the hash of the deploying admin's user secret), and the blacklist size. Loan records live in the on-chain `loans` map, keyed by your derived user public key — they just aren't part of this display command's output. Notice what is **not** on-chain: your credit score, income, employment tenure, attestation signature, or PIN. The transaction proved your eligibility without revealing any of those — only the outcome was disclosed. --- > For the complete documentation index, see [llms.txt](/llms.txt) # ZK Loan smart contract This tutorial builds a zero-knowledge (ZK) loan application from scratch on [Midnight Network](/concepts/network-architecture/onchain-logic.md). The app privately evaluates a user's credit data (credit score, income, and employment tenure) using [ZK proofs](/concepts/zero-knowledge-proofs.md) and records only the loan outcome on-chain. The sensitive financial data never leaves your machine. Traditional lending requires sharing sensitive financial data with lenders, brokers, and underwriters. That data gets stored, shared, and inevitably leaked. In 2024 alone, financial data breaches exposed hundreds of millions of records. ZK proofs flip this model. Instead of showing your data, you prove a statement about it: "My credit score is above 700, and my income exceeds $2,000/month," and the verifier learns nothing else. Midnight Network makes this practical — it is a blockchain purpose-built for [data protection](/concepts/how-midnight-works/keeping-data-private.md), where smart contracts can process private inputs and commit only the results on-chain. The tutorial is split into three parts: 1. **Smart contract**: Written in [Compact](/compact.md) (Midnight's ZK language). It defines the loan logic, eligibility tiers, and on-chain state. 2. **Attestation API**: A server that signs credit data with [Schnorr signatures](https://en.wikipedia.org/wiki/Schnorr_signature) so the smart contract can verify the data came from a trusted source. 3. **CLI**: A command-line tool to deploy the smart contract, register the attestation provider, request loans, and interact with the system — all pointing at Midnight's local network. ## Project setup[​](#project-setup "Direct link to Project setup") This section covers the tools and directory structure needed before writing any code. ### Install prerequisites[​](#install-prerequisites "Direct link to Install prerequisites") Make sure you have **Node.js v22 or newer** installed: ``` node --version # Should print v22.x.x or higher ``` Node 20 will crash mid-sync This DApp uses the `@midnight-ntwrk/wallet-sdk` barrel (re-exports the shielded wallet), which calls `Map.prototype.values().map(...)` on the shielded wallet state. That requires the [Iterator helpers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) added in Node 22. On Node 20 the wallet appears to start, then crashes on the first sync update with `state.pendingOutputs.values.map is not a function`. If you use [nvm](https://github.com/nvm-sh/nvm), add a `.nvmrc` file containing `22` (or your preferred 22+ release) to the repo root so `nvm use` picks it up automatically. Install the Midnight Compact compiler. Follow the instructions in the [installation guide](/getting-started/installation.md) to install the Compact toolchain on your system. Verify it is available: ``` compact compile --version ``` Run `compact update` to install the latest Compact toolchain. The workspace `package.json` declares `@midnight-ntwrk/compact-runtime: ^0.16.0`, which matches what the latest `compact compile` emits. Midnight JS 4.1.x protocol ACL As of Midnight JS **4.1.x**, hand-written code no longer imports the protocol packages (`ledger`, `compact-runtime`, `compact-js`, `onchain-runtime`, `platform-js`) directly. They are consumed through the version-agnostic **`@midnight-ntwrk/midnight-js-protocol`** ACL package via subpath imports — for example, `@midnight-ntwrk/midnight-js-protocol/compact-runtime`. `@midnight-ntwrk/compact-runtime` is still declared as a direct dependency because the compiler-generated contract code imports it directly, but every hand-written import points at the protocol subpath instead. This decouples your code from a specific ledger major version. Also, Docker is required to run the Midnight proof server, which generates the ZK proofs for your transactions locally. Install it from [docker.com/get-docker](https://www.docker.com/get-docker) if you have not already, and make sure the Docker daemon is running. ### Create the project structure[​](#create-the-project-structure "Direct link to Create the project structure") Create the root project directory and initialize the monorepo configuration: ``` mkdir zkloan-credit-scorer cd zkloan-credit-scorer ``` Initialize the root `package.json` with the following code snippet by pasting directly into your terminal. This is a monorepo with three workspaces: ``` cat > package.json << 'EOF' { "name": "zkloan-credit-scorer", "version": "3.0.0", "private": true, "type": "module", "engines": { "node": ">=22.0.0" }, "workspaces": [ "contract", "zkloan-credit-scorer-cli", "zkloan-credit-scorer-attestation-api" ], "devDependencies": { "@types/node": "^25.0.1", "@types/ws": "^8.18.1", "ts-node": "^10.9.2", "typescript": "^5.9.3", "vitest": "^4.0.15" }, "dependencies": { "@midnight-ntwrk/compact-runtime": "^0.16.0", "@midnight-ntwrk/midnight-js-contracts": "4.1.1", "@midnight-ntwrk/midnight-js-http-client-proof-provider": "4.1.1", "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "4.1.1", "@midnight-ntwrk/midnight-js-level-private-state-provider": "4.1.1", "@midnight-ntwrk/midnight-js-network-id": "4.1.1", "@midnight-ntwrk/midnight-js-node-zk-config-provider": "4.1.1", "@midnight-ntwrk/midnight-js-protocol": "4.1.1", "@midnight-ntwrk/midnight-js-types": "4.1.1", "@midnight-ntwrk/midnight-js-utils": "4.1.1", "@midnight-ntwrk/wallet-sdk": "1.2.0", "@midnight-ntwrk/wallet-sdk-address-format": "3.1.2", "@scure/bip39": "^2.0.1", "dotenv": "^17.2.3", "pino": "^10.1.0", "pino-pretty": "^13.1.3", "rxjs": "^7.8.1", "ws": "^8.18.3" }, "overrides": { "smoldot": "npm:empty-npm-package@1.0.0", "@midnight-ntwrk/ledger-v8": "8.1.0", "@midnight-ntwrk/midnight-js-network-id": "4.1.1" }, "resolutions": { "@midnight-ntwrk/ledger-v8": "8.1.0", "@midnight-ntwrk/midnight-js-network-id": "4.1.1" } } EOF ``` What changed vs. 4.0.x * Direct `@midnight-ntwrk/compact-js` and `@midnight-ntwrk/ledger-v8` deps are gone — both are consumed through `@midnight-ntwrk/midnight-js-protocol` (added). * The five individual wallet-sdk subpackages (`-facade`, `-hd`, `-shielded`, `-dust-wallet`, `-unshielded-wallet`) collapse to the single `@midnight-ntwrk/wallet-sdk` barrel. Pin the barrel exactly (`1.2.0`) — npm's `latest` dist-tag still points at `1.1.0`, so a caret range would silently resolve to the older release. * All `@midnight-ntwrk/midnight-js-*` packages step to `4.1.1`; the wrapped ledger pinned via `overrides`/`resolutions` moves to `8.1.0`. * `@midnight-ntwrk/compact-runtime` stays as a direct dep because the compiler-generated contract code imports it directly. Next, create the `.gitignore` with the following command: ``` cat > .gitignore << 'EOF' node_modules/ **/dist/ .vite/ *.tsbuildinfo logs *.log midnight-level-db coverage **/reports .npm .eslintcache .env **/.DS_Store .vscode/ managed/ EOF ``` Create the three workspace directories: ``` mkdir -p contract/src mkdir -p zkloan-credit-scorer-cli/src mkdir -p zkloan-credit-scorer-attestation-api/src ``` ## Write the Schnorr signature module[​](#write-the-schnorr-signature-module "Direct link to Write the Schnorr signature module") Before writing the main smart contract, you need a module for verifying Schnorr signatures. This is how the smart contract verifies that credit data was signed by a trusted attestation provider. This signature is important because of a fundamental problem: the witness's data cannot be trusted on its own. The witness runs on your machine, which means you could feed in any credit score you want. A user claiming a 750 credit score with $5,000 monthly income? Nothing stops them from lying. That is why the attestation solution exists. A trusted provider (a bank, credit bureau, or scoring service) signs your real data with a cryptographic signature. The smart contract then verifies that signature within the ZK circuit. If the data was tampered with, the signature check fails, and the transaction reverts. For this, the smart contract uses *Schnorr signatures on the Jubjub elliptic curve*, Midnight's native internal curve. info The Schnorr verification module below is a *temporary polyfill*. The Midnight team is building `jubjubSchnorrVerify` directly into the [Compact Standard Library](/compact/standard-library/exports.md). Once that ships, this entire module gets replaced by a single built-in function call. For now, implementing it manually is a useful exercise in understanding how signature verification works inside a ZK circuit. Now, create a file called `schnorr.compact` inside `contract/src/` and add the following code snippet: ``` module schnorr { import CompactStandardLibrary; export struct SchnorrSignature { announcement: JubjubPoint; response: Field; } struct SchnorrHashInput<#n> { ann_x: Field; ann_y: Field; pk_x: Field; pk_y: Field; msg: Vector; } witness getSchnorrReduction(challengeHash: Field): [Uint<7>, Uint<248>]; export circuit schnorrVerify<#n>(msg: Vector, signature: SchnorrSignature, pk: JubjubPoint): [] { const {announcement, response} = signature; const cFull: Field = transientHash>(SchnorrHashInput{ ann_x: jubjubPointX(announcement), ann_y: jubjubPointY(announcement), pk_x: jubjubPointX(pk), pk_y: jubjubPointY(pk), msg: msg }); const TWO_248: Field = 452312848583266388373324160190187140051835877600158453279131187530910662656 as Field; const [q, cTruncated] = getSchnorrReduction(cFull); assert(disclose(q) < 116, "Schnorr quotient out of range"); assert(disclose(q) * TWO_248 + (disclose(cTruncated) as Field) == cFull, "Invalid challenge reduction"); const c: Field = disclose(cTruncated) as Field; const lhs: JubjubPoint = ecMulGenerator(response); const rhs: JubjubPoint = ecAdd(announcement, ecMul(pk, c)); assert(jubjubPointX(lhs) == jubjubPointX(rhs) && jubjubPointY(lhs) == jubjubPointY(rhs), "Invalid attestation signature"); } export pure circuit schnorrChallenge( ann_x: Field, ann_y: Field, pk_x: Field, pk_y: Field, msg: Vector<4, Field> ): Field { const cFull: Field = transientHash>(SchnorrHashInput<4>{ ann_x: ann_x, ann_y: ann_y, pk_x: pk_x, pk_y: pk_y, msg: msg }); return cFull; } } ``` In the Schnorr code above: `SchnorrSignature` is a struct with two fields: * `announcement`: A point on the Jubjub elliptic curve (the "R" in Schnorr signing) * `response`: A scalar field element (the "s" in Schnorr signing) `schnorrVerify` is the verification circuit. It: * Hashes the announcement coordinates, public key coordinates, and message into a challenge (`cFull`) * Truncates the challenge to 248 bits (because the Jubjub curve order is \~252 bits, and `transientHash` outputs values in BLS12-381's scalar field, which is \~255 bits) * Verifies the Schnorr equation: `G * response == announcement + publicKey * challenge` `JubjubPoint` equality Since Compact language version `0.22`, two `JubjubPoint` values can no longer be compared with `==`. The compiler emits JS reference equality for struct equality, which is always `false` for freshly constructed points and would make the assertion silently impossible to satisfy. Compare the `x` and `y` coordinates explicitly with `jubjubPointX()` / `jubjubPointY()`, as shown above. The truncation uses a *witness* (`getSchnorrReduction`). The TypeScript code provides the quotient and remainder of dividing by 2^248, and the circuit verifies `q * 2^248 + r == cFull`. This is a common pattern in ZK systems: let the prover compute something expensive off-chain, then verify the result cheaply on-chain. Constrain witness values fully The reduction equation alone is not enough. Circuit arithmetic is modulo the BLS12-381 scalar prime, and 2^248 is invertible in that field — so if the quotient were an unconstrained `Field`, a malicious prover could pick *any* truncated challenge `r` and solve for a matching `q`, satisfying the equation while decoupling the challenge from the hash. That would allow forging an attestation signature without the provider's secret key. Typing the quotient as `Uint<7>` and asserting `q < 116` (the largest honest quotient is `floor((p - 1) / 2^248) = 115`) forces the equation to hold over the *integers*, tying `r` to the hash instead of leaving it a free choice. The general lesson: witness values are prover-controlled inputs — constrain them until only honest values can satisfy the circuit. `schnorrChallenge` is a `pure` circuit (no side effects, no ledger access). It computes the same challenge hash that `schnorrVerify` uses. It is exported so the attestation API can compute the same hash off-chain when signing. Now that this is completed, you can write the actual loan smart contract in the following steps. ## Write the loan smart contract[​](#write-the-loan-smart-contract "Direct link to Write the loan smart contract") Create `zkloan-credit-scorer.compact` inside the `contract/src/` folder. ### The header, types, ledger state, and constructor[​](#the-header-types-ledger-state-and-constructor "Direct link to The header, types, ledger state, and constructor") This first block declares the language version, imports, data types, ledger state, the constructor (which derives the initial admin public key from a witness secret), and the two pure circuits that turn that secret into per-user and admin identities: ``` pragma language_version >= 0.22 && <= 0.23; import CompactStandardLibrary; import "schnorr" prefix Schnorr_; export { Schnorr_SchnorrSignature }; export enum LoanStatus { Approved, Rejected, Proposed, NotAccepted, } export struct LoanApplication { authorizedAmount: Uint<16>; status: LoanStatus; } struct Applicant { creditScore: Uint<16>; monthlyIncome: Uint<16>; monthsAsCustomer: Uint<16>; } // Every browser/CLI instance holds a single 32-byte secret in private state. // All identity in this contract — both the admin role and per-user loan // identity — derives from that one secret via domain-separated hashes. // `ownPublicKey()` is never used: it returns a prover-claimed value with no // cryptographic binding to the transaction signer, so any assertion that // depends on it is bypassable. export new type UserSecretKey = Bytes<32>; export new type UserPublicKey = Bytes<32>; export new type AdminPublicKey = Bytes<32>; constructor() { contractAdmin = disclose(deriveAdminPublicKey(getUserSecret())); } export ledger blacklist: Set; export ledger loans: Map, Map, LoanApplication>>; export ledger onGoingPinMigration: Map, Uint<16>>; export ledger contractAdmin: AdminPublicKey; export ledger providers: Map, JubjubPoint>; witness getAttestedScoringWitness(): [Applicant, Schnorr_SchnorrSignature, Uint<16>]; witness getUserSecret(): UserSecretKey; // Per-user identity, PIN-rotatable. Changing the PIN yields a new derived // public key, breaking linkability to the old identity. export pure circuit deriveUserPublicKey(sk: UserSecretKey, pin: Uint<16>): UserPublicKey { const pinBytes = persistentHash>(pin); return persistentHash<[Bytes<17>, Bytes<32>, UserSecretKey]>([ "zkloan:user:pk:v1", pinBytes, sk ]) as UserPublicKey; } // Admin identity. No PIN binding — the admin role is stable across the // admin's PIN rotations. The deployer's `deriveAdminPublicKey(secret)` is // frozen into `contractAdmin` at construction. export pure circuit deriveAdminPublicKey(sk: UserSecretKey): AdminPublicKey { return persistentHash<[Bytes<18>, UserSecretKey]>([ "zkloan:admin:pk:v1", sk ]) as AdminPublicKey; } ``` Every Compact smart contract starts with a pragma (the language version) and imports. The standard library and the Schnorr module are imported with a prefix so their names do not collide. Define the data types next. Note two key things: * `LoanApplication` and `LoanStatus` are *exported*. The `export` keyword does not make them public — it generates TypeScript bindings in the compiled artifacts so the DApp can read and construct these types. They are visible on-chain because they are the value and field types stored in the `loans` ledger map; all ledger state is public, so anyone can read a loan's status and authorized amount. * `Applicant` is *not exported*, so no TypeScript binding is generated for it. It stays private because it is only ever used as witness and circuit-internal data and is never written to ledger state — not because of the missing `export`. The credit score, income, and tenure never appear on-chain. `UserSecretKey`, `UserPublicKey`, and `AdminPublicKey` are each declared with `new type` — a *nominal* alias over `Bytes<32>`. The form is `new type X = T;`, which creates a distinct type with the same representation as `T`. The three share the same 32-byte layout, but the compiler treats them as distinct: it rejects passing a `UserPublicKey` where a circuit expects an `AdminPublicKey` (or a raw `Bytes<32>`), and vice versa. A bare `Bytes<32>` everywhere would compile too, but it would let callers swap a user key for an admin key — exactly the confusion this contract's security depends on avoiding. A `new type` is lighter than the single-field wrapper struct it replaces (`struct UserPublicKey { bytes: Bytes<32>; }`). It adds no object wrapper, so the value is a bare `Bytes<32>` in Compact and a plain `Uint8Array` in the generated TypeScript — not a `{ bytes: ... }` object. There is no `UserPublicKey { ... }` or `UserPublicKey(...)` constructor: you go *into* the type with `value as UserPublicKey` and *out* with `pk as Bytes<32>` to recover the underlying bytes. Add `export` to a `new type` whenever it appears in an exported circuit or ledger signature, so the compiler generates the TypeScript binding. The [ledger](/concepts/ledgers.md) declarations define what lives on the blockchain: * `loans` is a *nested map*: the outer key is the user's derived public key bytes (`Bytes<32>`), the inner key is a loan ID (`Uint<16>`), and the value is the `LoanApplication`. This lets each user have multiple loans. * `providers` maps a provider ID to a Jubjub curve point (the provider's public key). The smart contract verifies attestation signatures against these registered keys. * `contractAdmin` stores the *derived admin public key* of the deployer: `persistentHash("zkloan:admin:pk:v1" || userSecret)`. The deployer holds the 32-byte secret in private state; the ledger only ever sees the hash. Each admin circuit forces the caller, inside the ZK proof, to demonstrate knowledge of the preimage of this stored value. * `blacklist` stores derived `UserPublicKey` values, not wallet addresses. A user's `UserPublicKey` at a given PIN is `persistentHash("zkloan:user:pk:v1" || hash(pin) || userSecret)`. A malicious caller cannot bypass the blacklist check by claiming a different wallet pubkey — their identity in this contract is whatever their witness secret hashes to. * `onGoingPinMigration` tracks progress when a user changes their PIN (more on this in the identity section). * `deriveUserPublicKey(sk, pin)` is the per-user identity derivation; `deriveAdminPublicKey(sk)` is the admin derivation. Both consume the same 32-byte witness secret. Different domain-separator strings keep the two derivations uncorrelated. Two details about how these hashes are built. First, `persistentHash` hashes *any* type, not just a `Vector` — here it takes a heterogeneous tuple (`[Bytes<17>, Bytes<32>, UserSecretKey]`) and hashes the `UserSecretKey` value directly, with no `.bytes` field to extract. Second, a domain-separator string literal goes straight into the tuple at its real byte length; there is no `pad()`. Count the bytes exactly: `"zkloan:user:pk:v1"` is **17 bytes** (`Bytes<17>`), while `"zkloan:admin:pk:v1"` is **18 bytes** (`Bytes<18>`) — the longer `admin` segment makes it one byte longer, so always count rather than copying a length from elsewhere. Each circuit ends with `... as UserPublicKey` / `... as AdminPublicKey` to tag the resulting `Bytes<32>` as the nominal type the signature promises. note These circuits stay exported because the off-chain code derives keys through them: the CLI/UI calls `pureCircuits.deriveUserPublicKey` for the per-user key and `pureCircuits.deriveAdminPublicKey` for the admin key. `export` on a circuit is a choice, not a requirement — if a contract derives keys only on-chain, the derivation circuit can stay unexported. Note also that dropping `pad()` changes the hash preimage (a raw 17/18-byte string instead of a 32-byte zero-padded one), so a given secret now derives a *different* public key than the earlier struct-based code did. Every consumer derives through this one compiled circuit, so they all agree; but an already-deployed instance built from the old code derives different identities, so treat it as a fresh deploy. Two witnesses. `getAttestedScoringWitness` returns the applicant's credit profile and the Schnorr-signed attestation. `getUserSecret` returns the 32-byte secret that drives all identity in the contract — the admin role and per-user PIN-bound identity. The TypeScript implementation is covered in the next section. note Do not close the file yet — the remaining blocks get appended to it. ### Core loan circuits[​](#core-loan-circuits "Direct link to Core loan circuits") Now add the heart of the smart contract: the circuits that handle loan requests. Use the following code snippet: ``` export circuit requestLoan(amountRequested: Uint<16>, secretPin: Uint<16>): [] { assert(amountRequested > 0, "Loan amount must be greater than zero"); const requesterPubKey = deriveUserPublicKey(getUserSecret(), secretPin); const disclosedRequesterPubKey = disclose(requesterPubKey); assert(!blacklist.member(disclosedRequesterPubKey), "Requester is blacklisted"); assert(!onGoingPinMigration.member(disclosedRequesterPubKey as Bytes<32>), "PIN migration is in progress for this user"); const userPubKeyHash = transientHash>(disclosedRequesterPubKey as Bytes<32>); const [topTierAmount, status] = evaluateApplicant(userPubKeyHash); const disclosedTopTierAmount = disclose(topTierAmount); const disclosedStatus = disclose(status); createLoan(disclosedRequesterPubKey as Bytes<32>, amountRequested, disclosedTopTierAmount, disclosedStatus); } export circuit respondToLoan(loanId: Uint<16>, secretPin: Uint<16>, accept: Boolean): [] { const requesterPubKey = deriveUserPublicKey(getUserSecret(), secretPin); const disclosedRequesterPubKey = disclose(requesterPubKey); const disclosedPubKey = disclosedRequesterPubKey as Bytes<32>; const disclosedLoanId = disclose(loanId); assert(!blacklist.member(disclosedRequesterPubKey), "User is blacklisted"); assert(loans.member(disclosedPubKey), "No loans found for this user"); assert(loans.lookup(disclosedPubKey).member(disclosedLoanId), "Loan not found"); const existingLoan = loans.lookup(disclosedPubKey).lookup(disclosedLoanId); assert(existingLoan.status == LoanStatus.Proposed, "Loan is not in Proposed status"); const updatedLoan = accept ? LoanApplication { authorizedAmount: existingLoan.authorizedAmount, status: LoanStatus.Approved } : LoanApplication { authorizedAmount: 0, status: LoanStatus.NotAccepted }; loans.lookup(disclosedPubKey).insert(disclosedLoanId, disclose(updatedLoan)); } circuit evaluateApplicant(userPubKeyHash: Field): [Uint<16>, LoanStatus] { const [profile, signature, providerId] = getAttestedScoringWitness(); assert(providers.member(disclose(providerId)), "Attestation provider not registered"); const providerPk = providers.lookup(disclose(providerId)); const msg: Vector<4, Field> = [ profile.creditScore as Field, profile.monthlyIncome as Field, profile.monthsAsCustomer as Field, userPubKeyHash ]; Schnorr_schnorrVerify<4>(msg, signature, providerPk); if (profile.creditScore >= 700 && profile.monthlyIncome >= 2000 && profile.monthsAsCustomer >= 24) { return [10000, LoanStatus.Approved]; } else if (profile.creditScore >= 600 && profile.monthlyIncome >= 1500) { return [7000, LoanStatus.Approved]; } else if (profile.creditScore >= 580) { return [3000, LoanStatus.Approved]; } else { return [0, LoanStatus.Rejected]; } } circuit createLoan(requester: Bytes<32>, amountRequested: Uint<16>, topTierAmount: Uint<16>, status: LoanStatus): [] { const authorizedAmount = amountRequested > topTierAmount ? topTierAmount : amountRequested; const finalStatus = status == LoanStatus.Rejected ? LoanStatus.Rejected : (amountRequested > topTierAmount ? LoanStatus.Proposed : LoanStatus.Approved); const loan = LoanApplication { authorizedAmount: authorizedAmount, status: finalStatus, }; if(!loans.member(requester)) { loans.insert(requester, default, LoanApplication>>); } const totalLoans = loans.lookup(requester).size(); assert(totalLoans < 65535, "Maximum number of loans reached"); const loanNumber = (totalLoans + 1) as Uint<16>; loans.lookup(requester).insert(loanNumber, disclose(loan)); } ``` `requestLoan` is the main entry point that users call. Here is the flow: 1. Derive the caller's per-user identity with `deriveUserPublicKey(getUserSecret(), secretPin)`. The witness secret is the only authoritative caller identity in this contract. 2. `disclose()` the derived pubkey so the compiler will let the value flow into ledger reads (`blacklist.member`, `onGoingPinMigration.member`). The value is witness-derived, so explicit disclosure is required. 3. Check the user is not on the blacklist or mid-PIN-change. 4. Call `evaluateApplicant()` — this is where the private credit scoring happens. The `transientHash` of the disclosed pubkey becomes the `userPubKeyHash` that the attestation message is signed against, binding the off-chain attestation to this specific in-circuit identity. 5. [`disclose()`](/compact/reference/explicit-disclosure.md) only the results (amount and status), and write the loan record to the ledger. important `evaluateApplicant` runs entirely in the ZK circuit. It reads the user's credit data from the witness, verifies the attestation signature, and returns the eligibility tier. `disclose()` does not itself make anything public — it is a compile-time annotation that marks a witness-derived value as safe to leave the private domain. A value only *becomes* public when it crosses a public boundary: written to a ledger field, or returned from an exported circuit. The credit score, income, and tenure are never disclosed and never cross such a boundary, so they stay private; only the eligibility *outcome* (amount and status) is disclosed and then written to the ledger, which is what actually publishes it. Also, `evaluateApplicant` is an internal circuit (not exported, cannot be called from outside). It: * Gets the user's credit profile, Schnorr signature, and provider ID from the witness * Verifies the provider is registered on-chain * Verifies the Schnorr signature — this proves the data came from a trusted provider and was not fabricated by the user * Evaluates the credit profile against three tiers: | Tier | Credit Score | Monthly Income | Tenure | Max Amount | | -------- | ------------ | -------------- | ------------ | ---------- | | 1 | >= 700 | >= $2,000 | >= 24 months | $10,000 | | 2 | >= 600 | >= $1,500 | any | $7,000 | | 3 | >= 580 | any | any | $3,000 | | Rejected | < 580 | any | any | $0 | `createLoan` handles the status logic. Three outcomes are possible: * **Approved**: The user asked for less than or equal to their max eligible amount. They get exactly what they asked for. * **Proposed**: The user asked for more than they qualify for. The smart contract offers the max eligible amount and waits for the user to accept or decline. * **Rejected**: The credit score is too low. Amount = 0. `respondToLoan` lets users accept or decline a *Proposed* loan. If they accept, the status changes to Approved. If they decline, it changes to NotAccepted and the authorized amount is zeroed out. ### Admin circuits[​](#admin-circuits "Direct link to Admin circuits") These access-controlled operations use the **witness-derived keypair pattern**. Every admin circuit starts with the same guard: ``` assert(contractAdmin == deriveAdminPublicKey(getUserSecret()), "Only admin can ..."); ``` Inside the ZK proof, this enforces that the caller knows the 32-byte preimage of the public value stored in `contractAdmin`. The ledger value alone is useless to an attacker: they could copy it into their proof input, but they cannot supply a witness whose hash matches without knowing the secret. Why not `ownPublicKey()`? An older version of this contract used `assert(ownPublicKey() == admin, "...")`. That pattern is bypassable. `ownPublicKey()` is supplied by the prover to the circuit context — the protocol does not cross-check it against the wallet that signed the transaction. A caller can put any 32-byte value in that slot and the assertion will hold. The same bypass applies to any other check that depends on `ownPublicKey()`: blacklist membership, PIN-bound identity derivation, anything where the result of `ownPublicKey()` flows into a security-relevant decision. The strict rule is: **if your contract is not routing shielded tokens to a target wallet, do not call `ownPublicKey()`.** Use witness-derived secrets for caller identity. The five admin circuits are: * `blacklistUser` / `removeBlacklistUser`: Add or remove a derived `UserPublicKey` from the blacklist. The admin obtains the target's `UserPublicKey` from the on-chain `loans` map keys (where it appears whenever the target has interacted) or from the target out-of-band. An admin cannot blacklist by wallet address — `ownPublicKey()` is not trusted by the contract. * `registerProvider` / `removeProvider`: Add or remove an attestation provider's public key. * `rotateAdmin`: Hand over the admin role to a new derived public key. The new admin generates their own secret locally, computes `deriveAdminPublicKey` off-chain, and shares only the resulting 32-byte value with the current admin. No private key crosses the wire. Add the following code snippet: ``` export circuit blacklistUser(account: UserPublicKey): [] { assert(contractAdmin == deriveAdminPublicKey(getUserSecret()), "Only admin can blacklist users"); blacklist.insert(disclose(account)); } export circuit removeBlacklistUser(account: UserPublicKey): [] { assert(contractAdmin == deriveAdminPublicKey(getUserSecret()), "Only admin can remove from blacklist"); blacklist.remove(disclose(account)); } export circuit registerProvider(providerId: Uint<16>, providerPk: JubjubPoint): [] { assert(contractAdmin == deriveAdminPublicKey(getUserSecret()), "Only admin can register providers"); providers.insert(disclose(providerId), disclose(providerPk)); } export circuit removeProvider(providerId: Uint<16>): [] { assert(contractAdmin == deriveAdminPublicKey(getUserSecret()), "Only admin can remove providers"); assert(providers.member(disclose(providerId)), "Provider not found"); providers.remove(disclose(providerId)); } export circuit rotateAdmin(newAdmin: AdminPublicKey): [] { assert(contractAdmin == deriveAdminPublicKey(getUserSecret()), "Only admin can rotate admin role"); contractAdmin = disclose(newAdmin); } ``` ### PIN migration and Schnorr re-export[​](#pin-migration-and-schnorr-re-export "Direct link to PIN migration and Schnorr re-export") This final block has two circuits: PIN migration and the Schnorr challenge re-export. Per-user identity is `deriveUserPublicKey(getUserSecret(), pin)`, defined in the header block above. The witness secret plus the PIN produces a deterministic `UserPublicKey` whose bytes appear on-chain. Without knowing both the secret and the PIN, you cannot link a wallet address to a loan record — giving users an extra layer of privacy. `changePin` is the most complex circuit. When a user changes their PIN, the derivation yields a new on-chain identity. But their existing loans are tied to the old identity. All loans need to migrate from the old `UserPublicKey` to the new one. The catch: ZK circuits cannot loop over variable-length data. If a user has 12 loans, you cannot write `for i in 0..loans.size()`. The loop bound must be known at compile time. The solution is batched migration: * Process exactly 5 loans per transaction (fixed at compile time with `for (const i of 0..5)`). * Track progress in `onGoingPinMigration` — it stores how far the migration has gotten. * The user calls `changePin` repeatedly until all loans are migrated. * Once done, the migration state is cleaned up. For a user with 12 loans: * Call 1: Migrates loans 1–5, records progress * Call 2: Migrates loans 6–10, records progress * Call 3: Migrates loans 11–12, finds slots 13–15 empty, cleans up While migration is in progress, `requestLoan` is blocked for that user (the `onGoingPinMigration` check). Append this final code snippet: ``` export circuit changePin(oldPin: Uint<16>, newPin: Uint<16>): [] { const oldUserPk = deriveUserPublicKey(getUserSecret(), oldPin); const newUserPk = deriveUserPublicKey(getUserSecret(), newPin); const disclosedOldUserPk = disclose(oldUserPk); const disclosedNewUserPk = disclose(newUserPk); assert(!blacklist.member(disclosedOldUserPk), "User is blacklisted"); assert(oldPin != newPin, "New PIN must be different from old PIN"); const disclosedOldPk = disclosedOldUserPk as Bytes<32>; const disclosedNewPk = disclosedNewUserPk as Bytes<32>; assert(loans.member(disclosedOldPk), "Old PIN does not match any user"); if (!onGoingPinMigration.member(disclosedOldPk)) { onGoingPinMigration.insert(disclosedOldPk, 0); } if (!loans.member(disclosedNewPk)) { loans.insert(disclosedNewPk, default, LoanApplication>>); } const lastMigratedSourceId: Uint<16> = onGoingPinMigration.lookup(disclosedOldPk); const lastDestinationId: Uint<16> = loans.lookup(disclosedNewPk).size() as Uint<16>; for (const i of 0..5) { if (onGoingPinMigration.member(disclosedOldPk)) { const sourceId = (lastMigratedSourceId + i + 1) as Uint<16>; const destinationId = (lastDestinationId + i + 1) as Uint<16>; if (loans.lookup(disclosedOldPk).member(sourceId)) { const loan = loans.lookup(disclosedOldPk).lookup(sourceId); loans.lookup(disclosedNewPk).insert(destinationId, disclose(loan)); loans.lookup(disclosedOldPk).remove(sourceId); onGoingPinMigration.insert(disclosedOldPk, sourceId); } else { onGoingPinMigration.remove(disclosedOldPk); if (loans.lookup(disclosedOldPk).size() == 0) { loans.remove(disclosedOldPk); } } } } } export pure circuit schnorrChallenge( ann_x: Field, ann_y: Field, pk_x: Field, pk_y: Field, msg: Vector<4, Field> ): Field { return Schnorr_schnorrChallenge(ann_x, ann_y, pk_x, pk_y, msg); } ``` `schnorrChallenge` re-exports the Schnorr challenge hash function as a `pure` circuit (no side effects, no ledger access). This must be available in the generated TypeScript so the attestation API can compute the same hash off-chain when signing. Your smart contract file is now complete. Before moving on, here is a summary of what is private versus public: | **Data** | **Visibility** | **Why** | | -------------------------------------- | ------------------------ | ---------------------------------------------------------------- | | 32-byte user secret | Private (witness only) | Authoritative caller identity; never leaves the user's machine | | Credit score, income, and tenure | Private (witness only) | Never leaves the user's machine | | Secret PIN | Private (circuit input) | Hashed with the user secret into per-user identity, never stored | | Attestation signature | Private (ZK proof input) | Verified inside the circuit | | Derived `UserPublicKey` (loan map key) | Public (ledger) | Unlinkable without both the user secret and the PIN | | Loan status and amount | Public (ledger) | The on-chain outcome | | `contractAdmin`, blacklist | Public (ledger) | Smart contract governance | ## Create the witness function (private data provider)[​](#create-the-witness-function-private-data-provider "Direct link to Create the witness function (private data provider)") The witness is the TypeScript code that provides private data to the ZK circuit at proving time. It runs on your machine, never on-chain. Create `contract/src/witnesses.ts`: ``` import { Ledger } from "./managed/zkloan-credit-scorer/contract/index.js"; import { WitnessContext } from "@midnight-ntwrk/midnight-js-protocol/compact-runtime"; export type SchnorrSignature = { announcement: { x: bigint; y: bigint }; response: bigint; }; export type ZKLoanCreditScorerPrivateState = { creditScore: bigint; monthlyIncome: bigint; monthsAsCustomer: bigint; attestationSignature: SchnorrSignature; attestationProviderId: bigint; userSecretKey: Uint8Array; // 32 bytes — the caller's authentic identity }; const TWO_248 = 452312848583266388373324160190187140051835877600158453279131187530910662656n; export const witnesses = { getAttestedScoringWitness: ({ privateState }: WitnessContext): [ ZKLoanCreditScorerPrivateState, [ { creditScore: bigint; monthlyIncome: bigint; monthsAsCustomer: bigint }, SchnorrSignature, bigint, ], ] => [ privateState, [ { creditScore: privateState.creditScore, monthlyIncome: privateState.monthlyIncome, monthsAsCustomer: privateState.monthsAsCustomer, }, privateState.attestationSignature, privateState.attestationProviderId, ], ], getSchnorrReduction: ({ privateState }: WitnessContext, challengeHash: bigint, ): [ZKLoanCreditScorerPrivateState, [bigint, bigint]] => { const q = challengeHash / TWO_248; const r = challengeHash % TWO_248; return [privateState, [q, r]]; }, getUserSecret: ({ privateState, }: WitnessContext): [ ZKLoanCreditScorerPrivateState, Uint8Array, ] => { if (!privateState.userSecretKey || privateState.userSecretKey.length !== 32) { throw new Error("getUserSecret: userSecretKey is missing or wrong length"); } return [privateState, privateState.userSecretKey]; }, }; ``` In the code above, each witness function receives a `WitnessContext` containing the current `privateState` and must return: * The (possibly updated) private state * The values the circuit requested - `getAttestedScoringWitness`: extracts the credit profile, attestation signature, and provider ID from private state. - `getSchnorrReduction`: computes the quotient and remainder of dividing the challenge hash by 2^248 (Jubjub scalar field truncation). The circuit declares the quotient as `Uint<7>` and asserts it is below 116, so the reduction is checked over the integers rather than modulo the field prime — the honest quotient is always in \[0, 115], so the TypeScript implementation needs no special handling. - `getUserSecret`: returns the 32-byte secret that drives all caller identity in this contract. Because `UserSecretKey` is now a `new type` over `Bytes<32>`, its generated TypeScript type is a plain `Uint8Array` — the witness returns the bare secret, with no `{ bytes: ... }` wrapper. The contract feeds it into two pure circuits — `deriveUserPublicKey(secret, pin)` for per-user PIN-bound identity, and `deriveAdminPublicKey(secret)` for the admin role. Only the deploying admin's secret hashes to the value stored in `contractAdmin`; everyone else's `getUserSecret` returns a value whose admin-derivation does not match, so admin assertions fail for them. Domain-separator strings (`"zkloan:admin:pk:v1"` vs `"zkloan:user:pk:v1"`) keep the two derivations from the same secret uncorrelated. The runtime length check rejects malformed witnesses at proof time. ## Create the smart contract TypeScript exports[​](#create-the-smart-contract-typescript-exports "Direct link to Create the smart contract TypeScript exports") Create `contract/src/index.ts`: ``` cat > contract/src/index.ts << 'EOF' export * as ZKLoanCreditScorer from "./managed/zkloan-credit-scorer/contract/index.js"; export * from "./witnesses.js"; EOF ``` This re-exports both the generated smart contract code (from the Compact compiler) and the witness implementations. Now create the smart contract's `package.json` using the following command in your terminal: ``` cat > contract/package.json << 'EOF' { "name": "zkloan-credit-scorer-contract", "version": "0.1.0", "private": true, "type": "module", "main": "dist/index.js", "module": "dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "require": "./dist/index.js", "import": "./dist/index.js", "default": "./dist/index.js" }, "./managed/zkloan-credit-scorer/contract": { "types": "./dist/managed/zkloan-credit-scorer/contract/index.d.ts", "import": "./dist/managed/zkloan-credit-scorer/contract/index.js", "default": "./dist/managed/zkloan-credit-scorer/contract/index.js" } }, "scripts": { "compact": "compact compile src/zkloan-credit-scorer.compact src/managed/zkloan-credit-scorer", "test": "vitest run", "test:compile": "npm run compact && vitest run", "build": "rm -rf dist && tsc --project tsconfig.build.json && cp -Rf ./src/managed ./dist/managed && cp ./src/zkloan-credit-scorer.compact ./src/schnorr.compact ./dist" } } EOF ``` Create `contract/tsconfig.json`: ``` cat > contract/tsconfig.json << 'EOF' { "include": ["src/**/*.ts"], "compilerOptions": { "rootDir": "src", "outDir": "dist", "declaration": true, "lib": ["ESNext"], "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "allowJs": true, "forceConsistentCasingInFileNames": true, "noImplicitAny": true, "strict": true, "isolatedModules": true, "sourceMap": true, "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true } } EOF ``` `moduleResolution: bundler` is required Midnight JS 4.1.x uses the protocol package's `exports` subpath map (`@midnight-ntwrk/midnight-js-protocol/compact-runtime`, `/ledger`, `/compact-js`, etc.). The legacy `moduleResolution: node` resolver cannot read that map. Use `bundler`, `node16`, or `nodenext` in every workspace that imports from a protocol subpath. Create `contract/tsconfig.build.json`: ``` cat > contract/tsconfig.build.json << 'EOF' { "extends": "./tsconfig.json", "exclude": ["src/test/**/*.ts"], "compilerOptions": {} } EOF ``` ## Compile the smart contract[​](#compile-the-smart-contract "Direct link to Compile the smart contract") Install all dependencies from the project root: ``` npm install ``` Compile the Compact smart contract: ``` cd contract npm run compact ``` This creates the `src/managed/zkloan-credit-scorer/` directory containing: * `contract/` — Generated TypeScript implementation of the smart contract * `keys/` — Proving and verifying keys for each circuit * `zkir/` — ZK intermediate representation files * `compiler/` — Compiler metadata Now build the TypeScript: ``` npm run build cd .. ``` At this point, the smart contract package is compiled and ready to be consumed by the CLI and attestation API. ## What you built in Part 1[​](#what-you-built-in-part-1 "Direct link to What you built in Part 1") This part covered the foundation of the ZK loan application: * **Schnorr signature module**: A Compact module that verifies cryptographic signatures inside a ZK circuit, ensuring credit data comes from a trusted source. * **Loan smart contract**: The full Compact smart contract with loan request logic, tiered eligibility evaluation, admin controls, PIN-based identity derivation, and batched PIN migration. * **Witness implementation**: TypeScript code that feeds private credit data into the ZK circuit at proving time, without exposing it on-chain. * **TypeScript exports and compilation**: Package configuration, compiler output, and the generated ZK circuits, keys, and bindings. The smart contract has been compiled and is ready. No credit data touches the blockchain; only the loan outcome does. ## Next steps[​](#next-steps "Direct link to Next steps") The next part builds the off-chain infrastructure that makes the smart contract functional: * [Attestation API](/tutorials/zk-loan/attestation-api.md): A REST server that signs credit data with Schnorr signatures, acting as the trusted data provider that the smart contract verifies against. * **Attestation flow**: A walkthrough of how the user, attestation API, and Midnight Network interact end-to-end. * **Docker setup for the proof server**: Configuring the local proof server that generates ZK proofs for your transactions. --- > For the complete documentation index, see [llms.txt](/llms.txt) # What is Midnight? Midnight is a data protection blockchain platform. It addresses a fundamental challenge in blockchain technology: how to use the benefits of distributed ledgers while maintaining the privacy required for sensitive data. Unlike traditional blockchains where every transaction is permanently visible to all participants, Midnight introduces selective disclosure - the ability to prove facts about data without revealing the data itself. This enables blockchain adoption in regulated industries like healthcare, finance, and government services where data protection is not just important, but legally required. ## Core concepts[​](#core-concepts "Direct link to Core concepts") ### Data protection blockchain[​](#data-protection-blockchain "Direct link to Data protection blockchain") Midnight maintains two parallel states: * **Public state**: Traditional blockchain data stored on-chain, visible to all network participants. This includes transaction proofs, contract code, and any intentionally public information. * **Private state**: Encrypted data stored locally by users, never exposed to the network. This includes personal information, business data, and any sensitive content that must remain confidential. ### Zero-knowledge proofs[​](#zero-knowledge-proofs "Direct link to Zero-knowledge proofs") The bridge between public and private states is zero-knowledge cryptography. Using zk-SNARKs (Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge), Midnight can: * Verify computations without seeing the input data * Prove statements are true without revealing why they're true * Generate compact proofs (128 bytes) regardless of computation complexity * Validate proofs in milliseconds on-chain For example, a healthcare application can prove a patient qualifies for treatment without revealing their medical history, or a financial system can verify sufficient account balance without exposing the actual amount. ### Compact programming language[​](#compact-programming-language "Direct link to Compact programming language") Midnight introduces Compact, a domain-specific language based on TypeScript that makes privacy-preserving smart contracts accessible to mainstream developers. Instead of requiring cryptographic expertise, developers write familiar code that automatically compiles to zero-knowledge circuits. ## Why Midnight[​](#why-midnight "Direct link to Why Midnight") ### Regulations require controlled data use Privacy laws demand strong data protection, but public blockchains make all on-chain activity visible by default. Click to learn more → ### Regulations require controlled data use Frameworks such as GDPR, CCPA, and HIPAA require tight control over personal data. Midnight helps by enabling controlled, provable disclosure so teams can share only the information that is necessary. ← Click to flip back ### Public chains expose too much Organizations need decentralization but cannot place sensitive information on fully open ledgers. Click to learn more → ### Public chains expose too much Public chains reveal balances, actions, and metadata on a shared ledger. Private chains improve confidentiality but reduce decentralization. Midnight combines public and private state, giving teams decentralization with programmable confidentiality. ← Click to flip back ### Privacy tooling is often inaccessible Most teams cannot build ZK systems because they require specialized cryptographic expertise. Click to learn more → ### Privacy tooling is often inaccessible Traditional ZK development demands circuit design and proof-system knowledge. Midnight’s Compact language lowers this barrier by compiling TypeScript-like code into circuits and proofs automatically. ← Click to flip back ### Private computation must still be verifiable Sensitive logic needs privacy, but it must still prove correctness to the network. Click to learn more → ### Private computation must still be verifiable Midnight lets users compute on private data locally and submit zero-knowledge proofs instead of raw inputs. Validators verify correctness without learning the underlying data, preserving both privacy and trust. ← Click to flip back ## How Midnight works[​](#how-midnight-works "Direct link to How Midnight works") ### Transaction flow[​](#transaction-flow "Direct link to Transaction flow") When a user initiates a transaction on Midnight, the process follows a specific sequence to maintain privacy while ensuring validity. First, users perform computations on their private data locally, never exposing it to the network. The Midnight runtime then generates a zero-knowledge proof of this computation, creating mathematical evidence that the computation was performed correctly without revealing the inputs. This proof, along with any intended public outputs, is submitted to the blockchain. Network validators verify the proof using the zk-SNARK verification algorithm, which takes only milliseconds despite the complexity of the original computation. Once verified, both public and private states update according to the proven computation - public state on the blockchain and private state in users' local storage. ### Network architecture[​](#network-architecture "Direct link to Network architecture") Midnight operates as a proof-of-stake blockchain. Validators can participate permissionlessly through stake delegation, contributing to network security while earning rewards. The platform maintains a native bridge to Cardano for asset transfers, enabling interoperability between the two chains. The network processes two types of transactions: standard public transactions that function like traditional blockchain operations, and shielded transactions that use zero-knowledge proofs to maintain privacy. Both transaction types are validated by the same set of validators, ensuring consistent security across the network. ### Privacy guarantees[​](#privacy-guarantees "Direct link to Privacy guarantees") Midnight implements several layers of privacy protection. The system follows data minimization principles, ensuring only essential data goes on-chain while sensitive information remains in local storage. Forward secrecy protects historical data - even if encryption keys are compromised in the future, past transactions remain private. Users maintain complete control through selective disclosure, choosing precisely what information to reveal and to whom. For regulated entities, Midnight provides optional compliance mechanisms that enable required reporting to authorities without compromising user privacy or exposing data to unauthorized parties. ## Use cases[​](#use-cases "Direct link to Use cases") ### AI and data analysis Run analysis or inference on sensitive data without exposing inputs or model details. Click to learn more → ### AI and data analysis Midnight supports private computation for analytics and AI workflows. Applications can process encrypted inputs locally, generate proofs of correctness, and share only verified outputs. Teams can prove fairness, compliance, or model behavior without revealing underlying datasets or parameters. ← Click to flip back ### Healthcare and regulated data Share or validate medical data while keeping personal information private. Click to learn more → ### Healthcare and regulated data Healthcare systems can exchange patient data using policy-based access rules. Smart contracts enforce who can see what, while zero-knowledge proofs confirm eligibility, participation, or compliance. Sensitive records never appear on-chain, but proofs verify required conditions. ← Click to flip back ### Governance and identity Enable voting, membership, and credentials without exposing user identities. Click to learn more → ### Governance and identity Midnight supports selective disclosure credentials and private voting. Users can prove membership, eligibility, or participation without revealing their full identity or activity history. Final results remain publicly verifiable while individual actions stay private. ← Click to flip back ### Finance and compliant privacy Perform private transfers or interactions while meeting regulatory requirements. Click to learn more → ### Finance and compliant privacy Financial applications use zero-knowledge proofs to enforce rules like KYC, limits, or screening without exposing balances or transaction metadata. Smart contracts verify compliance while users keep sensitive financial information confidential. ← Click to flip back ---