Skip to main content

SnarkyJS

Table of contents

References

Namespaces

Classes

Interfaces

Type Aliases

Variables

Functions

References

PublicKey

Re-exports PublicKey

Type Aliases

DeployArgs

Ƭ DeployArgs: { verificationKey?: { data: string ; hash: string | Field } ; zkappKey?: PrivateKey } | undefined

Defined in

lib/zkapp.ts:1325


ProvableExtended

Ƭ ProvableExtended<T, TJson>: Provable<T> & ProvableExtension<T, TJson>

Type parameters

NameType
TT
TJsonany

Defined in

lib/circuit_value.ts:462


Reducer

Ƭ Reducer<Action>: Object

Type parameters

Name
Action

Type declaration

NameType
actionTypeProvablePure<Action>

Defined in

lib/zkapp.ts:1093

lib/zkapp.ts:1479


State

Ƭ State<A>: Object

Gettable and settable state that can be checked for equality.

Type parameters

Name
A

Type declaration

NameType
assertEquals(a: A) => void
assertNothing() => void
fetch() => Promise<undefined | A>
get() => A
set(a: A) => void

Defined in

lib/state.ts:25

lib/state.ts:18


ZkappPublicInput

Ƭ ZkappPublicInput: Object

The public input for zkApps consists of certain hashes of the proving AccountUpdate (and its child accountUpdates) which is constructed during method execution.

For SmartContract proving, a method is run twice: First outside the proof, to obtain the public input, and once in the prover, which takes the public input as input. The current transaction is hashed again inside the prover, which asserts that the result equals the input public input, as part of the snark circuit. The block producer will also hash the transaction they receive and pass it as a public input to the verifier. Thus, the transaction is fully constrained by the proof - the proof couldn't be used to attest to a different transaction.

Type declaration

NameType
accountUpdateField
callsField

Defined in

lib/account_update.ts:1677

lib/account_update.ts:1678

Variables

Permissions

Permissions: Object

Type declaration

NameType
default() => Permissions
dummy() => Permissions
fromJSON(permissions: { editSequenceState: AuthRequired ; editState: AuthRequired ; incrementNonce: AuthRequired ; receive: AuthRequired ; send: AuthRequired ; setDelegate: AuthRequired ; setPermissions: AuthRequired ; setTokenSymbol: AuthRequired ; setVerificationKey: AuthRequired ; setVotingFor: AuthRequired ; setZkappUri: AuthRequired }) => Permissions
fromString(permission: AuthRequired) => AuthRequired
impossible() => AuthRequired
initial() => Permissions
none() => AuthRequired
proof() => AuthRequired
proofOrSignature() => AuthRequired
signature() => AuthRequired

Defined in

lib/account_update.ts:156

lib/account_update.ts:220


Poseidon

Const Poseidon: Object

Type declaration

NameType
Spongetypeof Sponge
get initialState()[Field, Field, Field]
hash(input: Field[]) => Field
update(state: [Field, Field, Field], input: Field[]) => [Field, Field, Field]

Defined in

lib/hash.ts:36


ZkappPublicInput

ZkappPublicInput: ProvablePure<{ accountUpdate: Field = Field; calls: Field = Field }> & ProvableExtension<{ accountUpdate: Field = Field; calls: Field = Field }, { accountUpdate: string = Field; calls: string = Field }>

Defined in

lib/account_update.ts:1677

lib/account_update.ts:1678


isReady

isReady: Promise<undefined>

A Promise that resolves when SnarkyJS is ready to be used

Defined in

snarky.d.ts:1185

Functions

Account

Account(address, tokenId?): PreconditionClassType<AccountPrecondition>

Parameters

NameType
addressPublicKey
tokenId?Field

Returns

PreconditionClassType<AccountPrecondition>

Defined in

lib/zkapp.ts:1382


MerkleWitness

MerkleWitness(height): typeof BaseMerkleWitness

Returns a circuit-compatible Witness for a specific Tree height.

Parameters

NameTypeDescription
heightnumberHeight of the Merkle Tree that this Witness belongs to.

Returns

typeof BaseMerkleWitness

A circuit-compatible Merkle Witness.

Defined in

lib/merkle_tree.ts:215


Reducer

Reducer<T, A>(reducer): ReducerReturn<A>

Type parameters

NameType
Textends ProvablePure<any, T>
Aextends any

Parameters

NameType
reducerObject
reducer.actionTypeT

Returns

ReducerReturn<A>

Defined in

lib/zkapp.ts:1479


State

State<A>(): State<A>

Type parameters

Name
A

Returns

State<A>

Defined in

lib/state.ts:25


Struct

Struct<A, T, J, Pure>(type, options?): (value: T) => T & Pure extends true ? ProvablePure<T> : Provable<T> & { fromJSON: (x: J) => T ; toInput: (x: T) => { fields?: Field[] ; packed?: [Field, number][] } ; toJSON: (x: T) => J }

Struct lets you declare composite types for use in snarkyjs circuits.

These composite types can be passed in as arguments to smart contract methods, used for on-chain state variables or as event / action types.

Here's an example of creating a "Voter" struct, which holds a public key and a collection of votes on 3 different proposals:

let Vote = { hasVoted: Bool, inFavor: Bool };

class Voter extends Struct({
publicKey: PublicKey,
votes: [Vote, Vote, Vote]
}) {}

// use Voter as SmartContract input:
class VoterContract extends SmartContract {
\@method register(voter: Voter) {
// ...
}
}

In this example, there are no instance methods on the class. This makes Voter type-compatible with an anonymous object of the form { publicKey: PublicKey, votes: Vote[] }. This mean you don't have to create instances by using new Voter(...), you can operate with plain objects:

voterContract.register({ publicKey, votes });

On the other hand, you can also add your own methods:

class Voter extends Struct({
publicKey: PublicKey,
votes: [Vote, Vote, Vote]
}) {
vote(index: number, inFavor: Bool) {
let vote = this.votes[i];
vote.hasVoted = Bool(true);
vote.inFavor = inFavor;
}
}

In this case, you'll need the constructor to create instances of Voter. It always takes as input the plain object:

let emptyVote = { hasVoted: Bool(false), inFavor: Bool(false) };
let voter = new Voter({ publicKey, votes: Array(3).fill(emptyVote) });
voter.vote(1, Bool(true));

In addition to creating types composed of Field elements, you can also include auxiliary data which does not become part of the proof. This, for example, allows you to re-use the same type outside snarkyjs methods, where you might want to store additional metadata.

To declare non-proof values of type string, number, etc, you can use the built-in objects String, Number, etc. Here's how we could add the voter's name (a string) as auxiliary data:

class Voter extends Struct({
publicKey: PublicKey,
votes: [Vote, Vote, Vote],
fullName: String
}) {}

Again, it's important to note that this doesn't enable you to prove anything about the fullName string. From the circuit point of view, it simply doesn't exist!

Type parameters

NameType
AA
Textends unknown = InferCircuitValue<A>
Jextends unknown = InferJson<A>
Pureextends boolean = IsPure<A>

Parameters

NameTypeDescription
typeAObject specifying the layout of the Struct
optionsObjectAdvanced option which allows you to force a certain order of object keys
options.customObjectKeys?string[]-

Returns

(value: T) => T & Pure extends true ? ProvablePure<T> : Provable<T> & { fromJSON: (x: J) => T ; toInput: (x: T) => { fields?: Field[] ; packed?: [Field, number][] } ; toJSON: (x: T) => J }

Class which you can extend

Defined in

lib/circuit_value.ts:720


addCachedAccount

addCachedAccount(account, graphqlEndpoint?): void

Fetches an account from the GraphQL endpoint and adds it to the local cache.

Parameters

NameTypeDefault value
accountObjectundefined
account.balance?string | number | UInt64undefined
account.noncestring | number | UInt32undefined
account.publicKeystring | PublicKeyundefined
account.tokenIdstringundefined
account.zkapp?Objectundefined
account.zkapp.appState(string | number | Field)[]undefined
graphqlEndpointstringdefaultGraphqlEndpoint

Returns

void

Defined in

lib/fetch.ts:364


arrayProp

arrayProp<T>(elementType, length): (target: any, key: string) => void

Type parameters

Name
T

Parameters

NameType
elementTypeProvable<T>
lengthnumber

Returns

fn

▸ (target, key): void

Parameters
NameType
targetany
keystring
Returns

void

Defined in

lib/circuit_value.ts:338


circuitMain

circuitMain(target, propertyName, _descriptor?): any

Parameters

NameType
targetany
propertyNamestring
_descriptor?PropertyDescriptor

Returns

any

Defined in

lib/circuit_value.ts:411


declareMethods

declareMethods<T>(SmartContract, methodArguments): void

declareMethods can be used in place of the @method decorator to declare SmartContract methods along with their list of arguments. It should be placed after the class declaration. Here is an example of declaring a method update, which takes a single argument of type Field:

class MyContract extends SmartContract {
// ...
update(x: Field) {
// ...
}
}
declareMethods(MyContract, { update: [Field] }); // `[Field]` is the list of arguments!

Note that a method of the same name must still be defined on the class, just without the decorator.

Type parameters

NameType
Textends typeof SmartContract

Parameters

NameType
SmartContractT
methodArgumentsRecord<string, Provable<unknown>[]>

Returns

void

Defined in

lib/zkapp.ts:1459


declareState

declareState<T>(SmartContract, states): void

declareState can be used in place of the @state decorator to declare on-chain state on a SmartContract. It should be placed after the class declaration. Here is an example of declaring a state property x of type Field.

class MyContract extends SmartContract {
x = State<Field>();
// ...
}
declareState(MyContract, { x: Field });

If you're using pure JS, it's not possible to use the built-in class field syntax, i.e. the following will not work:

// THIS IS WRONG IN JS!
class MyContract extends SmartContract {
x = State();
}
declareState(MyContract, { x: Field });

Instead, add a constructor where you assign the property:

class MyContract extends SmartContract {
constructor(x) {
super();
this.x = State();
}
}
declareState(MyContract, { x: Field });

Type parameters

NameType
Textends typeof SmartContract

Parameters

NameType
SmartContractT
statesRecord<string, ProvablePure<unknown>>

Returns

void

Defined in

lib/state.ts:115


deploy

deploy<S>(SmartContract, __namedParameters): Promise<string>

Type parameters

NameType
Sextends typeof SmartContract

Parameters

NameType
SmartContractS
__namedParametersObject
__namedParameters.feePayer?FeePayerSpec
__namedParameters.initialBalance?string | number
__namedParameters.tokenId?Field
__namedParameters.verificationKeyObject
__namedParameters.verificationKey.datastring
__namedParameters.verificationKey.hashstring | Field
__namedParameters.zkappKeyPrivateKey

Returns

Promise<string>

Defined in

lib/zkapp.ts:1334


fetchAccount

fetchAccount(accountInfo, graphqlEndpoint?, config?): Promise<{ account: Account ; error: undefined } | { account: undefined ; error: FetchError }>

Gets account information on the specified publicKey by performing a GraphQL query to the specified endpoint. This will call the 'GetAccountInfo' query which fetches zkapp related account information.

If an error is returned by the specified endpoint, an error is thrown. Otherwise, the data is returned.

Parameters

NameTypeDefault valueDescription
accountInfoObjectundefined-
accountInfo.publicKeystring | PublicKeyundefined-
accountInfo.tokenId?stringundefined-
graphqlEndpointstringdefaultGraphqlEndpointThe graphql endpoint to fetch from
configObject{}An object that exposes an additional timeout option
config.timeoutundefined | numberundefined-

Returns

Promise<{ account: Account ; error: undefined } | { account: undefined ; error: FetchError }>

zkapp information on the specified account or an error is thrown

Defined in

lib/fetch.ts:50


fetchLastBlock

fetchLastBlock(graphqlEndpoint?): Promise<PreconditionBaseTypes<{ blockchainLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; globalSlotSinceGenesis: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; globalSlotSinceHardFork: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; minWindowDensity: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; nextEpochData: { epochLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; ledger: { hash: { isSome: Bool ; value: Field } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } } ; lockCheckpoint: { isSome: Bool ; value: Field } ; seed: { isSome: Bool ; value: Field } ; startCheckpoint: { isSome: Bool ; value: Field } } ; snarkedLedgerHash: { isSome: Bool ; value: Field } ; stakingEpochData: { epochLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; ledger: { hash: { isSome: Bool ; value: Field } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } } ; lockCheckpoint: { isSome: Bool ; value: Field } ; seed: { isSome: Bool ; value: Field } ; startCheckpoint: { isSome: Bool ; value: Field } } ; timestamp: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } }>>

Fetches the last block on the Mina network.

Parameters

NameTypeDefault value
graphqlEndpointstringdefaultGraphqlEndpoint

Returns

Promise<PreconditionBaseTypes<{ blockchainLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; globalSlotSinceGenesis: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; globalSlotSinceHardFork: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; minWindowDensity: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; nextEpochData: { epochLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; ledger: { hash: { isSome: Bool ; value: Field } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } } ; lockCheckpoint: { isSome: Bool ; value: Field } ; seed: { isSome: Bool ; value: Field } ; startCheckpoint: { isSome: Bool ; value: Field } } ; snarkedLedgerHash: { isSome: Bool ; value: Field } ; stakingEpochData: { epochLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; ledger: { hash: { isSome: Bool ; value: Field } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } } ; lockCheckpoint: { isSome: Bool ; value: Field } ; seed: { isSome: Bool ; value: Field } ; startCheckpoint: { isSome: Bool ; value: Field } } ; timestamp: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } }>>

Defined in

lib/fetch.ts:393


getSrs

getSrs(keypair): any

Parameters

NameTypeDescription
keypairanySNARK keypair, as returned by Circuit.generateKeypair

Returns

any

The SRS (structured reference string), needed to reconstruct the keypair later

Defined in

snarky/addons.js:18


matrixProp

matrixProp<T>(elementType, nRows, nColumns): (target: any, key: string) => void

Type parameters

Name
T

Parameters

NameType
elementTypeProvable<T>
nRowsnumber
nColumnsnumber

Returns

fn

▸ (target, key): void

Parameters
NameType
targetany
keystring
Returns

void

Defined in

lib/circuit_value.ts:347


method

method<T>(target, methodName, descriptor): void

A decorator to use in a zkApp to mark a method as callable by anyone. You can use inside your zkApp class as:

\@method myMethod(someArg: Field) {
// your code here
}

Type parameters

NameType
Textends SmartContract<T>

Parameters

NameType
targetT & { constructor: any }
methodNamekeyof T & string
descriptorPropertyDescriptor

Returns

void

Defined in

lib/zkapp.ts:93


prop

prop(this, target, key): void

Parameters

NameType
thisany
targetany
keystring

Returns

void

Defined in

lib/circuit_value.ts:241


provable

provable<A>(typeObj, options?): ProvableExtended<InferCircuitValue<A>, InferJson<A>>

Type parameters

Name
A

Parameters

NameType
typeObjA
options?Object
options.customObjectKeys?string[]
options.isPure?boolean

Returns

ProvableExtended<InferCircuitValue<A>, InferJson<A>>

Defined in

lib/circuit_value.ts:465


provablePure

provablePure<A>(typeObj, options?): ProvablePure<InferCircuitValue<A>> & ProvableExtension<InferCircuitValue<A>, InferJson<A>>

Type parameters

Name
A

Parameters

NameType
typeObjA
optionsObject
options.customObjectKeys?string[]

Returns

ProvablePure<InferCircuitValue<A>> & ProvableExtension<InferCircuitValue<A>, InferJson<A>>

Defined in

lib/circuit_value.ts:642


public_

public_(target, _key, index): void

Parameters

NameType
targetany
_keystring | symbol
indexnumber

Returns

void

Defined in

lib/circuit_value.ts:363


recoverVerificationKey

recoverVerificationKey(srs, serializedVk): any

Parameters

NameTypeDescription
srsanythe "structured reference string", a set of precomputed values needed for verifying proofs
serializedVkstringstring representation of a Circuit verification key

Returns

any

the recovered verification key

Defined in

snarky/addons.js:49


sendZkapp

sendZkapp(json, graphqlEndpoint?, __namedParameters?): Promise<[FetchResponse, undefined] | [undefined, FetchError]>

Sends a zkApp command (transaction) to the specified GraphQL endpoint.

Parameters

NameTypeDefault value
jsonstringundefined
graphqlEndpointstringdefaultGraphqlEndpoint
__namedParametersObject{}
__namedParameters.timeoutundefined | numberundefined

Returns

Promise<[FetchResponse, undefined] | [undefined, FetchError]>

Defined in

lib/fetch.ts:540


serializeVerificationKey

serializeVerificationKey(verificationKey): string

Parameters

NameTypeDescription
verificationKeyanythe verification key of a Circuit

Returns

string

string representation of the verification key

Defined in

snarky/addons.js:27


setGraphqlEndpoint

setGraphqlEndpoint(graphqlEndpoint): void

Specifies the default GraphQL endpoint.

Parameters

NameType
graphqlEndpointstring

Returns

void

Defined in

lib/fetch.ts:33


shutdown

shutdown(): Promise<undefined>

This function must be called at the end of a nodejs program, otherwise the worker threads will continue running and the program will never terminate. From web applications, this function is a no-op.

Returns

Promise<undefined>

Defined in

snarky.d.ts:1180


signFeePayer

signFeePayer(transactionJson, feePayerKey, __namedParameters): string

Parameters

NameType
transactionJsonstring
feePayerKeystring | PrivateKey
__namedParametersObject

Returns

string

Defined in

lib/zkapp.ts:1416


state

state<A>(stateType): (target: SmartContract & { constructor: any }, key: string, _descriptor?: PropertyDescriptor) => void

A decorator to use within a zkapp to indicate what will be stored on-chain. For example, if you want to store a field element some_state in a zkapp, you can use the following in the declaration of your zkapp:

@state(Field) some_state = State<Field>();

Type parameters

Name
A

Parameters

NameType
stateTypeProvablePure<A>

Returns

fn

▸ (target, key, _descriptor?): void

Parameters
NameType
targetSmartContract & { constructor: any }
keystring
_descriptor?PropertyDescriptor
Returns

void

Defined in

lib/state.ts:39


verify

verify(proof, verificationKey): Promise<boolean>

Parameters

NameType
proofJsonProof | Proof<any>
verificationKeystring

Returns

Promise<boolean>

Defined in

lib/proof_system.ts:112


zkappCommandToJson

zkappCommandToJson(__namedParameters): ZkappCommand

Parameters

NameType
__namedParametersZkappCommand

Returns

ZkappCommand

Defined in

lib/account_update.ts:1564