Skip to main content

modules

o1js / Modules

o1js

Table of contents

Namespaces

Enumerations

Classes

Interfaces

Type Aliases

Variables

Functions

Type Aliases

Bool

Ƭ Bool: Bool

Defined in

lib/core.ts:70

lib/core.ts:71


BoolVar

Ƭ BoolVar: FieldVar

Defined in

lib/bool.ts:17


Bytes

Ƭ Bytes: InternalBytes

Defined in

lib/provable-types/provable-types.ts:16

lib/provable-types/provable-types.ts:5

lib/provable-types/provable-types.ts:19

lib/provable-types/provable-types.ts:20

lib/provable-types/provable-types.ts:21


Cache

Ƭ Cache: Object

Interface for storing and retrieving values, for caching. read() and write() can just throw errors on failure.

The data that will be passed to the cache for writing is exhaustively described by the CacheHeader type. It represents one of the following:

  • The SRS. This is a deterministic lists of curve points (one per curve) that needs to be generated just once, to be used for polynomial commitments.
  • Lagrange basis commitments. Similar to the SRS, this will be created once for every power-of-2 circuit size.
  • Prover and verifier keys for every compiled circuit.

Per smart contract or ZkProgram, several different keys are created:

  • a step prover key (step-pk) and verification key (step-vk) for every method.
  • a wrap prover key (wrap-pk) and verification key (wrap-vk) for the entire contract.

Type declaration

NameTypeDescription
canWritebooleanIndicates whether the cache is writable.
debug?booleanIf debug is toggled, read() and write() errors are logged to the console. By default, cache errors are silent, because they don't necessarily represent an error condition, but could just be a cache miss, or file system permissions incompatible with writing data.
read(header: CacheHeader) => undefined | Uint8ArrayRead a value from the cache.
write(header: CacheHeader, value: Uint8Array) => voidWrite a value to the cache.

Defined in

lib/proof-system/cache.ts:31

lib/proof-system/cache.ts:199


CacheHeader

Ƭ CacheHeader: StepKeyHeader\<"step-pk"> | StepKeyHeader\<"step-vk"> | WrapKeyHeader\<"wrap-pk"> | WrapKeyHeader\<"wrap-vk"> | PlainHeader\<"srs"> | PlainHeader\<"lagrange-basis"> & CommonHeader

A header that is passed to the caching layer, to support rich caching strategies.

Both uniqueId and programId can safely be used as a file path.

Defined in

lib/proof-system/cache.ts:98


ConstantField

Ƭ ConstantField: Field & { value: ConstantFieldVar }

Defined in

lib/field.ts:109


DeployArgs

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

Defined in

lib/zkapp.ts:1497


Empty

Ƭ Empty: Undefined

Defined in

lib/proof_system.ts:78

lib/proof_system.ts:79


FeatureFlags

Ƭ FeatureFlags: Object

Type declaration

NameType
foreignFieldAddboolean
foreignFieldMulboolean
lookupboolean
rangeCheck0boolean
rangeCheck1boolean
rotboolean
runtimeTablesboolean
xorboolean

Defined in

snarky.d.ts:699


Field

Ƭ Field: Field

Defined in

lib/core.ts:42

lib/core.ts:43


FieldConst

Ƭ FieldConst: [0, bigint]

Defined in

lib/field.ts:27

lib/field.ts:36


FieldVar

Ƭ FieldVar: [Constant, FieldConst] | [Var, number] | [Add, FieldVar, FieldVar] | [Scale, FieldConst, FieldVar]

FieldVar is the core data type in snarky. It is eqivalent to Cvar.t in OCaml. It represents a field element that is part of provable code - either a constant or a variable.

Variables end up filling the witness columns of a constraint system. Think of a variable as a value that has to be provided by the prover, and that has to satisfy all the constraints it is involved in.

Constants end up being hard-coded into the constraint system as gate coefficients. Think of a constant as a value that is known publicly, at compile time, and that defines the constraint system.

Both constants and variables can be combined into an AST using the Add and Scale combinators.

Defined in

lib/field.ts:67

lib/field.ts:76


FlexibleProvable

Ƭ FlexibleProvable\<T>: Provable\<T> | Struct\<T>

Type parameters

Name
T

Defined in

lib/circuit_value.ts:68


FlexibleProvablePure

Ƭ FlexibleProvablePure\<T>: ProvablePure\<T> | StructPure\<T>

Type parameters

Name
T

Defined in

lib/circuit_value.ts:69


Gate

Ƭ Gate: Object

Type declaration

NameType
coeffsstring[]
typeGateType
wires{ col: number ; row: number }[]

Defined in

snarky.d.ts:568


GateType

Ƭ GateType: "Zero" | "Generic" | "Poseidon" | "CompleteAdd" | "VarbaseMul" | "EndoMul" | "EndoMulScalar" | "Lookup" | "RangeCheck0" | "RangeCheck1" | "ForeignFieldAdd" | "ForeignFieldMul" | "Xor16" | "Rot64"

Defined in

snarky.d.ts:545


Group

Ƭ Group: Group

Defined in

lib/core.ts:76

lib/core.ts:77


InferProvable

Ƭ InferProvable\<T>: GenericInferProvable\<T, Field>

Type parameters

Name
T

Defined in

bindings/lib/provable-snarky.ts:46


JsonGate

Ƭ JsonGate: Object

Type declaration

NameType
coeffsstring[]
typGateType
wires{ col: number ; row: number }[]

Defined in

snarky.d.ts:561


JsonProof

Ƭ JsonProof: Object

Type declaration

NameType
maxProofsVerified0 | 1 | 2
proofstring
publicInputstring[]
publicOutputstring[]

Defined in

lib/proof_system.ts:227


MlFeatureFlags

Ƭ MlFeatureFlags: [_: 0, rangeCheck0: MlBool, rangeCheck1: MlBool, foreignFieldAdd: MlBool, foreignFieldMul: MlBool, xor: MlBool, rot: MlBool, lookup: MlBool, runtimeTables: MlBool]

Defined in

snarky.d.ts:710


MlPublicKey

Ƭ MlPublicKey: [_: 0, x: FieldConst, isOdd: MlBool]

Defined in

snarky.d.ts:581


MlPublicKeyVar

Ƭ MlPublicKeyVar: [_: 0, x: FieldVar, isOdd: BoolVar]

Defined in

snarky.d.ts:582


Provable

Ƭ Provable\<T>: Provable\<T>

Provable<T> is the general circuit type interface. It describes how a type T is made up of field elements and auxiliary (non-field element) data.

You will find this as the required input type in a few places in o1js. One convenient way to create a Provable<T> is using Struct.

Type parameters

Name
T

Defined in

lib/provable.ts:43

lib/provable.ts:45


ProvableExtended

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

Type parameters

NameType
TT
TJsonany

Defined in

lib/circuit_value.ts:58


Reducer

Ƭ Reducer\<Action>: Object

Type parameters

Name
Action

Type declaration

NameType
actionTypeFlexibleProvablePure\<Action>

Defined in

lib/zkapp.ts:1232

lib/zkapp.ts:1544


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>
fromAppState(appState: Field[]) => A
get() => A
getAndAssertEquals() => A
getAndRequireEquals() => A
requireEquals(a: A) => void
requireNothing() => void
set(a: A) => void

Defined in

lib/state.ts:85

lib/state.ts:20


Struct

Ƭ Struct\<T>: ProvableExtended\<NonMethods\<T>> & Constructor\<T> & { _isStruct: true }

Type parameters

Name
T

Defined in

lib/circuit_value.ts:374

lib/circuit_value.ts:63


TransactionStatus

Ƭ TransactionStatus: "INCLUDED" | "PENDING" | "UNKNOWN"

INCLUDED: A transaction that is on the longest chain

PENDING: A transaction either in the transition frontier or in transaction pool but is not on the longest chain

UNKNOWN: The transaction has either been snarked, reached finality through consensus or has been dropped

Defined in

lib/fetch.ts:689


Undefined

Ƭ Undefined: undefined

Defined in

lib/proof_system.ts:75

lib/proof_system.ts:76


VarField

Ƭ VarField: Field & { value: VarFieldVar }

Defined in

lib/field.ts:1363

lib/field.ts:110


VarFieldVar

Ƭ VarFieldVar: [Var, number]

Defined in

lib/field.ts:74


Void

Ƭ Void: undefined

Defined in

lib/proof_system.ts:80

lib/proof_system.ts:81


ZkProgram

Ƭ ZkProgram\<S, T>: ReturnType\<typeof ZkProgram>

Type parameters

NameType
Sextends Object
Textends { [I in string]: Tuple\<PrivateInput> }

Defined in

lib/proof_system.ts:245

lib/proof_system.ts:475

lib/proof_system.ts:965


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:2001

lib/account_update.ts:2005

Variables

Cache

Cache: Object

Type declaration

NameType
FileSystem(cacheDirectory: string, debug?: boolean) => Cache
FileSystemDefaultCache
NoneCache

Defined in

lib/proof-system/cache.ts:31

lib/proof-system/cache.ts:199


Crypto

Const Crypto: Object

Type declaration

NameTypeDescription
CurveParams{ Pallas: CurveParams = pallasParams; Secp256k1: CurveParams = secp256k1Params; Vesta: CurveParams = vestaParams }Parameters defining an elliptic curve in short Weierstraß form y^2 = x^3 + ax + b
CurveParams.PallasCurveParams-
CurveParams.Secp256k1CurveParams-
CurveParams.VestaCurveParams-
createCurve(params: CurveParams) => { Field: { M: bigint = twoadicity; modulus: bigint = p; sizeInBits: number ; t: bigint = oddFactor; twoadicRoot: bigint ; add: (x: bigint, y: bigint) => bigint ; div: (x: bigint, y: bigint) => undefined | bigint ; dot: (x: bigint[], y: bigint[]) => bigint ; equal: (x: bigint, y: bigint) => boolean ; fromBigint: (x: bigint) => bigint ; fromNumber: (x: number) => bigint ; inverse: (x: bigint) => undefined | bigint ; isEven: (x: bigint) => boolean ; isSquare: (x: bigint) => boolean ; leftShift: (x: bigint, bits: number, maxBitSize: number) => bigint ; mod: (x: bigint) => bigint ; mul: (x: bigint, y: bigint) => bigint ; negate: (x: bigint) => bigint ; not: (x: bigint, bits: number) => bigint ; power: (x: bigint, n: bigint) => bigint ; random: () => bigint ; rightShift: (x: bigint, bits: number) => bigint ; rot: (x: bigint, bits: bigint, direction: "left" | "right", maxBits: bigint) => bigint ; sqrt: (x: bigint) => undefined | bigint ; square: (x: bigint) => bigint ; sub: (x: bigint, y: bigint) => bigint } ; Scalar: { M: bigint = twoadicity; modulus: bigint = p; sizeInBits: number ; t: bigint = oddFactor; twoadicRoot: bigint ; add: (x: bigint, y: bigint) => bigint ; div: (x: bigint, y: bigint) => undefined | bigint ; dot: (x: bigint[], y: bigint[]) => bigint ; equal: (x: bigint, y: bigint) => boolean ; fromBigint: (x: bigint) => bigint ; fromNumber: (x: number) => bigint ; inverse: (x: bigint) => undefined | bigint ; isEven: (x: bigint) => boolean ; isSquare: (x: bigint) => boolean ; leftShift: (x: bigint, bits: number, maxBitSize: number) => bigint ; mod: (x: bigint) => bigint ; mul: (x: bigint, y: bigint) => bigint ; negate: (x: bigint) => bigint ; not: (x: bigint, bits: number) => bigint ; power: (x: bigint, n: bigint) => bigint ; random: () => bigint ; rightShift: (x: bigint, bits: number) => bigint ; rot: (x: bigint, bits: bigint, direction: "left" | "right", maxBits: bigint) => bigint ; sqrt: (x: bigint) => undefined | bigint ; square: (x: bigint) => bigint ; sub: (x: bigint, y: bigint) => bigint } ; a: bigint ; b: bigint ; cofactor: undefined | bigint ; hasCofactor: boolean ; hasEndomorphism: boolean ; modulus: bigint = p; name: string ; one: { infinity: boolean = false; x: bigint ; y: bigint } ; order: bigint ; zero: GroupAffine = affineZero; Endo: ; add: (g: GroupAffine, h: GroupAffine) => GroupAffine ; double: (g: GroupAffine) => GroupAffine ; equal: (g: GroupAffine, h: GroupAffine) => boolean ; from: (g: { x: bigint ; y: bigint }) => GroupAffine ; fromNonzero: (g: { x: bigint ; y: bigint }) => GroupAffine ; isInSubgroup: (g: GroupAffine) => boolean ; isOnCurve: (g: GroupAffine) => boolean ; negate: (g: GroupAffine) => GroupAffine ; scale: (g: GroupAffine, s: bigint | boolean[]) => GroupAffine ; sub: (g: GroupAffine, h: GroupAffine) => GroupAffine }Create elliptic curve arithmetic methods.

Defined in

lib/crypto.ts:8

lib/crypto.ts:22


Empty

Empty: ProvablePureExtended\<undefined, null>

Defined in

lib/proof_system.ts:78

lib/proof_system.ts:79


FieldConst

FieldConst: Object

Type declaration

NameType
-1FieldConst
0FieldConst
1FieldConst
fromBigint(x: bigint) => FieldConst
toBigint(x: FieldConst) => Fp
equal(x: FieldConst, y: FieldConst) => boolean

Defined in

lib/field.ts:27

lib/field.ts:36


FieldVar

FieldVar: Object

Type declaration

NameType
-1[Constant, FieldConst]
0[Constant, FieldConst]
1[Constant, FieldConst]
add(x: FieldVar, y: FieldVar) => FieldVar
constant(x: bigint | FieldConst) => ConstantFieldVar
isConstant(x: FieldVar) => x is ConstantFieldVar
isVar(x: FieldVar) => x is VarFieldVar
scale(c: bigint | FieldConst, x: FieldVar) => FieldVar

Defined in

lib/field.ts:67

lib/field.ts:76


Gadgets

Const Gadgets: Object

Type declaration

NameTypeDescription
Field3{ provable: GenericProvableExtendedPure\<[Field, Field, Field], [string, string, string], Field> ; from: (x: bigint) => Field3 ; isConstant: (x: Field3) => boolean ; toBigint: (x: Field3) => bigint ; toBigints: \<T>(...xs: T) => [...{ [i in string | number | symbol]: bigint }[]] }-
Field3.provableGenericProvableExtendedPure\<[Field, Field, Field], [string, string, string], Field>Provable<T> interface for Field3 = [Field, Field, Field]. Note: Witnessing this creates a plain tuple of field elements without any implicit range checks.
Field3.from[object Object]Turn a bigint into a 3-tuple of Fields
Field3.isConstant[object Object]Check whether a 3-tuple of Fields is constant
Field3.toBigint[object Object]Turn a 3-tuple of Fields into a bigint
Field3.toBigints[object Object]Turn several 3-tuples of Fields into bigints
ForeignField{ Sum: (x: Field3) => Sum ; add: (x: Field3, y: Field3, f: bigint) => Field3 ; assertAlmostReduced: (xs: Field3[], f: bigint, __namedParameters: { skipMrc: undefined | boolean }) => void ; assertLessThan: (x: Field3, f: bigint) => void ; assertMul: (x: Field3 | Sum, y: Field3 | Sum, z: Field3 | Sum, f: bigint) => void ; div: (x: Field3, y: Field3, f: bigint) => Field3 ; inv: (x: Field3, f: bigint) => Field3 ; mul: (x: Field3, y: Field3, f: bigint) => Field3 ; neg: (x: Field3, f: bigint) => Field3 ; sub: (x: Field3, y: Field3, f: bigint) => Field3 ; sum: (xs: Field3[], signs: (1n | -1n)[], f: bigint) => Field3 }Gadgets for foreign field operations. A foreign field is a finite field different from the native field of the proof system. The ForeignField namespace exposes operations like modular addition and multiplication, which work for any finite field of size less than 2^259. Foreign field elements are represented as 3 limbs of native field elements. Each limb holds 88 bits of the total, in little-endian order. All ForeignField gadgets expect that their input limbs are constrained to the range [0, 2^88). Range checks on outputs are added by the gadget itself.
ForeignField.Sum[object Object]Lazy sum of Field3 elements, which can be used as input to assertMul.
ForeignField.add[object Object]Foreign field addition: x + y mod f The modulus f does not need to be prime. Inputs and outputs are 3-tuples of native Fields. Each input limb is assumed to be in the range [0, 2^88), and the gadget is invalid if this is not the case. The result limbs are guaranteed to be in the same range. Example ts let x = Provable.witness(Field3.provable, () => Field3.from(9n)); let y = Provable.witness(Field3.provable, () => Field3.from(10n)); // range check x and y Gadgets.multiRangeCheck(x); Gadgets.multiRangeCheck(y); // compute x + y mod 17 let z = ForeignField.add(x, y, 17n); Provable.log(z); // ['2', '0', '0'] = limb representation of 2 = 9 + 10 mod 17 Warning: The gadget does not assume that inputs are reduced modulo f, and does not prove that the result is reduced modulo f. It only guarantees that the result is in the correct residue class.
ForeignField.assertAlmostReduced[object Object]Prove that each of the given Field3 elements is "almost" reduced modulo f, i.e., satisfies the assumptions required by mul and other gadgets: - each limb is in the range [0, 2^88) - the most significant limb is less or equal than the modulus, x[2] <= f[2] Note: This method is most efficient when the number of input elements is a multiple of 3. Throws if any of the assumptions is violated. Example ts let x = Provable.witness(Field3.provable, () => Field3.from(4n)); let y = Provable.witness(Field3.provable, () => Field3.from(5n)); let z = Provable.witness(Field3.provable, () => Field3.from(10n)); ForeignField.assertAlmostReduced([x, y, z], f); // now we can use x, y, z as inputs to foreign field multiplication let xy = ForeignField.mul(x, y, f); let xyz = ForeignField.mul(xy, z, f); // since xy is an input to another multiplication, we need to prove that it is almost reduced again! ForeignField.assertAlmostReduced([xy], f); // TODO: would be more efficient to batch this with 2 other elements
ForeignField.assertLessThan[object Object]Prove that x < f for any constant f < 2^264. If f is a finite field modulus, this means that the given field element is fully reduced modulo f. This is a stronger statement than assertAlmostReduced and also uses more constraints; it should not be needed in most use cases. Note: This assumes that the limbs of x are in the range [0, 2^88), in contrast to assertAlmostReduced which adds that check itself. Throws if x is greater or equal to f. Example ts let x = Provable.witness(Field3.provable, () => Field3.from(0x1235n)); // range check limbs of x Gadgets.multiRangeCheck(x); // prove that x is fully reduced mod f Gadgets.ForeignField.assertLessThan(x, f);
ForeignField.assertMul[object Object]Optimized multiplication of sums in a foreign field, for example: (x - y)*z = a + b + c mod f Note: This is much more efficient than using add and sub separately to compute the multiplication inputs and outputs, and then using mul to constrain the result. The sums passed into this method are "lazy sums" created with Sum. You can also pass in plain Field3 elements. Assumptions: The assumptions on the summands are analogous to the assumptions described in mul: - each summand's limbs are in the range [0, 2^88) - summands that are part of a multiplication input satisfy x[2] <= f[2] Throws if the modulus is so large that the second assumption no longer suffices for validity of the multiplication. For small sums and moduli < 2^256, this will not fail. Throws if the provided multiplication result is not correct modulo f. Example ts // range-check x, y, z, a, b, c ForeignField.assertAlmostReduced([x, y, z], f); Gadgets.multiRangeCheck(a); Gadgets.multiRangeCheck(b); Gadgets.multiRangeCheck(c); // create lazy input sums let xMinusY = ForeignField.Sum(x).sub(y); let aPlusBPlusC = ForeignField.Sum(a).add(b).add(c); // assert that (x - y)*z = a + b + c mod f ForeignField.assertMul(xMinusY, z, aPlusBPlusC, f);
ForeignField.div[object Object]Foreign field division: x * y^(-1) mod f See mul for assumptions on inputs and usage examples. This gadget adds an extra bound check on the result, so it can be used directly in another foreign field multiplication. Throws Different than mul, this fails on unreduced input x, because it checks that x === (x/y)*y and the right side will be reduced.
ForeignField.inv[object Object]Foreign field inverse: x^(-1) mod f See mul for assumptions on inputs and usage examples. This gadget adds an extra bound check on the result, so it can be used directly in another foreign field multiplication.
ForeignField.mul[object Object]Foreign field multiplication: x * y mod f The modulus f does not need to be prime, but has to be smaller than 2^259. Assumptions: In addition to the assumption that input limbs are in the range [0, 2^88), as in all foreign field gadgets, this assumes an additional bound on the inputs: x * y < 2^264 * p, where p is the native modulus. We usually assert this bound by proving that x[2] < f[2] + 1, where x[2] is the most significant limb of x. To do this, we use an 88-bit range check on 2^88 - x[2] - (f[2] + 1), and same for y. The implication is that x and y are almost reduced modulo f. All of the above assumptions are checked by assertAlmostReduced. Warning: This gadget does not add the extra bound check on the result. So, to use the result in another foreign field multiplication, you have to add the bound check on it yourself, again. Example ts // example modulus: secp256k1 prime let f = (1n << 256n) - (1n << 32n) - 0b1111010001n; let x = Provable.witness(Field3.provable, () => Field3.from(f - 1n)); let y = Provable.witness(Field3.provable, () => Field3.from(f - 2n)); // range check x, y and prove additional bounds x[2] <= f[2] ForeignField.assertAlmostReduced([x, y], f); // compute x * y mod f let z = ForeignField.mul(x, y, f); Provable.log(z); // ['2', '0', '0'] = limb representation of 2 = (-1)*(-2) mod f
ForeignField.neg[object Object]Foreign field negation: -x mod f = f - x See add for assumptions and usage examples. Throws fails if x > f, where f - x < 0.
ForeignField.sub[object Object]Foreign field subtraction: x - y mod f See add for assumptions and usage examples. Throws fails if x - y < -f, where the result cannot be brought back to a positive number by adding f once.
ForeignField.sum[object Object]Foreign field sum: xs[0] + signs[0] * xs[1] + ... + signs[n-1] * xs[n] mod f This gadget takes a list of inputs and a list of signs (of size one less than the inputs), and computes a chain of additions or subtractions, depending on the sign. A sign is of type 1n \| -1n, where 1n represents addition and -1n represents subtraction. Note: For 3 or more inputs, sum() uses fewer constraints than a sequence of add() and sub() calls, because we can avoid range checks on intermediate results. See add for assumptions on inputs. Example ts let x = Provable.witness(Field3.provable, () => Field3.from(4n)); let y = Provable.witness(Field3.provable, () => Field3.from(5n)); let z = Provable.witness(Field3.provable, () => Field3.from(10n)); // range check x, y, z Gadgets.multiRangeCheck(x); Gadgets.multiRangeCheck(y); Gadgets.multiRangeCheck(z); // compute x + y - z mod 17 let sum = ForeignField.sum([x, y, z], [1n, -1n], 17n); Provable.log(sum); // ['16', '0', '0'] = limb representation of 16 = 4 + 5 - 10 mod 17
SHA256{ hash: (data: FlexibleBytes) => Bytes }Implementation of the SHA256 hash function. Hash function with 256bit output. Applies the SHA2-256 hash function to a list of byte-sized elements. The function accepts Bytes as the input message, which is a type that represents a static-length list of byte-sized field elements (range-checked using rangeCheck8). Alternatively, you can pass plain number[], bigint[] or Uint8Array to perform a hash outside provable code. Produces an output of Bytes that conforms to the chosen bit length. Param Bytes representing the message to hash. ts let preimage = Bytes.fromString("hello world"); let digest = Gadgets.SHA256.hash(preimage);
SHA256.hash[object Object]-
addMod32(x: Field, y: Field) => Field-
divMod32(n: Field, quotientBits: number) => { quotient: Field ; remainder: Field }-
and(a: Field, b: Field, length: number) => FieldBitwise AND gadget on Field elements. Equivalent to the bitwise AND & operator in JavaScript. The AND gate works by comparing two bits and returning 1 if both bits are 1, and 0 otherwise. It can be checked by a double generic gate that verifies the following relationship between the values below (in the process it also invokes the xor gadget which will create additional constraints depending on length). The generic gate verifies:\ a + b = sum and the conjunction equation 2 * and = sum - xor\ Where:\ a + b = sum\ a ^ b = xor\ a & b = and You can find more details about the implementation in the Mina book The length parameter lets you define how many bits should be compared. length is rounded to the nearest multiple of 16, paddedLength = ceil(length / 16) * 16, and both input values are constrained to fit into paddedLength bits. The output is guaranteed to have at most paddedLength bits as well. Note: Specifying a larger length parameter adds additional constraints. Note: Both Field elements need to fit into 2^paddedLength - 1. Otherwise, an error is thrown and no proof can be generated. For example, with length = 2 (paddedLength = 16), and() will fail for any input that is larger than 2**16. Example typescript let a = Field(3); // ... 000011 let b = Field(5); // ... 000101 let c = Gadgets.and(a, b, 2); // ... 000001 c.assertEquals(1);
compactMultiRangeCheck(xy: Field, z: Field) => [Field, Field, Field]Compact multi-range check This is a variant of multiRangeCheck where the first two variables are passed in combined form xy = x + 2^88y. The gadget - splits up xy into x and y - proves that xy = x + 2^88y - proves that x, y, z are all in the range [0, 2^88). The split form [x, y, z] is returned. Example ts let [x, y] = Gadgets.compactMultiRangeCheck([xy, z]); Throws Throws an error if xy exceeds 2*88 = 176 bits, or if z exceeds 88 bits.
isInRangeN(n: number, x: Field) => BoolChecks whether the input value is in the range [0, 2^n). n must be a multiple of 16. This function proves that the provided field element can be represented with n bits. If the field element exceeds n bits, Bool(false) is returned and Bool(true) otherwise. Example ts const x = Provable.witness(Field, () => Field(12345678n)); let inRange = Gadgets.isInRangeN(32, x); // return Bool(true)
leftShift32(field: Field, bits: number) => FieldPerforms a left shift operation on the provided Field element. This operation is similar to the << shift operation in JavaScript, where bits are shifted to the left, and the overflowing bits are discarded. It’s important to note that these operations are performed considering the big-endian 32-bit representation of the number, where the most significant (32th) bit is on the left end and the least significant bit is on the right end. Important: The gadgets assumes that its input is at most 32 bits in size. The output is range checked to 32 bits. Example ts const x = Provable.witness(Field, () => Field(0b001100)); // 12 in binary const y = Gadgets.leftShift32(x, 2); // left shift by 2 bits y.assertEquals(0b110000); // 48 in binary
leftShift64(field: Field, bits: number) => FieldPerforms a left shift operation on the provided Field element. This operation is similar to the << shift operation in JavaScript, where bits are shifted to the left, and the overflowing bits are discarded. It’s important to note that these operations are performed considering the big-endian 64-bit representation of the number, where the most significant (64th) bit is on the left end and the least significant bit is on the right end. Important: The gadgets assumes that its input is at most 64 bits in size. If the input exceeds 64 bits, the gadget is invalid and fails to prove correct execution of the shift. Therefore, to safely use leftShift(), you need to make sure that the values passed in are range checked to 64 bits. For example, this can be done with rangeCheck64. Throws Throws an error if the input value exceeds 64 bits. Example ts const x = Provable.witness(Field, () => Field(0b001100)); // 12 in binary const y = Gadgets.leftShift64(x, 2); // left shift by 2 bits y.assertEquals(0b110000); // 48 in binary const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); leftShift64(xLarge, 32); // throws an error since input exceeds 64 bits
multiRangeCheck(limbs: Field3) => voidMulti-range check. Proves that x, y, z are all in the range [0, 2^88). This takes 4 rows, so it checks 88*3/4 = 66 bits per row. This is slightly more efficient than 64-bit range checks, which can do 64 bits in 1 row. In particular, the 3x88-bit range check supports bigints up to 264 bits, which in turn is enough to support foreign field multiplication with moduli up to 2^259. Example ts Gadgets.multiRangeCheck([x, y, z]); Throws Throws an error if one of the input values exceeds 88 bits.
not(a: Field, length: number, checked: boolean) => FieldBitwise NOT gate on Field elements. Similar to the [bitwise NOT ~ operator in JavaScript](https://developer.mozilla.org/en-US/docs/ Web/JavaScript/Reference/Operators/Bitwise_NOT). Note: The NOT gate only operates over the amount of bits specified by the length parameter. A NOT gate works by returning 1 in each bit position if the corresponding bit of the operand is 0, and returning 0 if the corresponding bit of the operand is 1. The length parameter lets you define how many bits to NOT. Note: Specifying a larger length parameter adds additional constraints. The operation will fail if the length or the input value is larger than 254. NOT is implemented in two different ways. If the checked parameter is set to true the xor gadget is reused with a second argument to be an all one bitmask the same length. This approach needs as many rows as an XOR would need for a single negation. If the checked parameter is set to false, NOT is implemented as a subtraction of the input from the all one bitmask. This implementation is returned by default if no checked parameter is provided. You can find more details about the implementation in the Mina book Example ts // not-ing 4 bits with the unchecked version let a = Field(0b0101); let b = Gadgets.not(a,4,false); b.assertEquals(0b1010); // not-ing 4 bits with the checked version utilizing the xor gadget let a = Field(0b0101); let b = Gadgets.not(a,4,true); b.assertEquals(0b1010); Throws Throws an error if the input value exceeds 254 bits.
rangeCheck16(x: Field) => void-
rangeCheck32(x: Field) => voidAsserts that the input value is in the range [0, 2^32). This function proves that the provided field element can be represented with 32 bits. If the field element exceeds 32 bits, an error is thrown. Throws Throws an error if the input value exceeds 32 bits. Example ts const x = Provable.witness(Field, () => Field(12345678n)); Gadgets.rangeCheck32(x); // successfully proves 32-bit range const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); Gadgets.rangeCheck32(xLarge); // throws an error since input exceeds 32 bits Note: Small "negative" field element inputs are interpreted as large integers close to the field size, and don't pass the 32-bit check. If you want to prove that a value lies in the int32 range [-2^31, 2^31), you could use rangeCheck32(x.add(1n << 31n)).
rangeCheck64(x: Field) => voidAsserts that the input value is in the range [0, 2^64). This function proves that the provided field element can be represented with 64 bits. If the field element exceeds 64 bits, an error is thrown. Throws Throws an error if the input value exceeds 64 bits. Example ts const x = Provable.witness(Field, () => Field(12345678n)); Gadgets.rangeCheck64(x); // successfully proves 64-bit range const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); Gadgets.rangeCheck64(xLarge); // throws an error since input exceeds 64 bits Note: Small "negative" field element inputs are interpreted as large integers close to the field size, and don't pass the 64-bit check. If you want to prove that a value lies in the int64 range [-2^63, 2^63), you could use rangeCheck64(x.add(1n << 63n)).
rangeCheck8(x: Field) => voidAsserts that the input value is in the range [0, 2^8). See rangeCheck64 for analogous details and usage examples.
rangeCheckN(n: number, x: Field, message?: string) => voidAsserts that the input value is in the range [0, 2^n). n must be a multiple of 16. This function proves that the provided field element can be represented with n bits. If the field element exceeds n bits, an error is thrown. Throws Throws an error if the input value exceeds n bits. Example ts const x = Provable.witness(Field, () => Field(12345678n)); Gadgets.rangeCheckN(32, x); // successfully proves 32-bit range const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); Gadgets.rangeCheckN(32, xLarge); // throws an error since input exceeds 32 bits
rightShift64(field: Field, bits: number) => FieldPerforms a right shift operation on the provided Field element. This is similar to the >> shift operation in JavaScript, where bits are moved to the right. The rightShift64 function utilizes the rotation method internally to implement this operation. * It’s important to note that these operations are performed considering the big-endian 64-bit representation of the number, where the most significant (64th) bit is on the left end and the least significant bit is on the right end. Important: The gadgets assumes that its input is at most 64 bits in size. If the input exceeds 64 bits, the gadget is invalid and fails to prove correct execution of the shift. To safely use rightShift64(), you need to make sure that the value passed in is range-checked to 64 bits; for example, using rangeCheck64. Throws Throws an error if the input value exceeds 64 bits. Example ts const x = Provable.witness(Field, () => Field(0b001100)); // 12 in binary const y = Gadgets.rightShift64(x, 2); // right shift by 2 bits y.assertEquals(0b000011); // 3 in binary const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); rightShift64(xLarge, 32); // throws an error since input exceeds 64 bits
rotate32(field: Field, bits: number, direction: "left" | "right") => FieldA (left and right) rotation operates similarly to the shift operation (<< for left and >> for right) in JavaScript, with the distinction that the bits are circulated to the opposite end of a 32-bit representation rather than being discarded. For a left rotation, this means that bits shifted off the left end reappear at the right end. Conversely, for a right rotation, bits shifted off the right end reappear at the left end. It’s important to note that these operations are performed considering the big-endian 32-bit representation of the number, where the most significant (32th) bit is on the left end and the least significant bit is on the right end. The direction parameter is a string that accepts either 'left' or 'right', determining the direction of the rotation. Important: The gadget assumes that its input is at most 32 bits in size. If the input exceeds 32 bits, the gadget is invalid and fails to prove correct execution of the rotation. To safely use rotate32(), you need to make sure that the value passed in is range-checked to 32 bits; for example, using rangeCheck32. Throws Throws an error if the input value exceeds 32 bits. Example ts const x = Provable.witness(Field, () => Field(0b001100)); const y = Gadgets.rotate32(x, 2, 'left'); // left rotation by 2 bits const z = Gadgets.rotate32(x, 2, 'right'); // right rotation by 2 bits y.assertEquals(0b110000); z.assertEquals(0b000011); const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); Gadgets.rotate32(xLarge, 32, "left"); // throws an error since input exceeds 32 bits
rotate64(field: Field, bits: number, direction: "left" | "right") => FieldA (left and right) rotation operates similarly to the shift operation (<< for left and >> for right) in JavaScript, with the distinction that the bits are circulated to the opposite end of a 64-bit representation rather than being discarded. For a left rotation, this means that bits shifted off the left end reappear at the right end. Conversely, for a right rotation, bits shifted off the right end reappear at the left end. It’s important to note that these operations are performed considering the big-endian 64-bit representation of the number, where the most significant (64th) bit is on the left end and the least significant bit is on the right end. The direction parameter is a string that accepts either 'left' or 'right', determining the direction of the rotation. Important: The gadget assumes that its input is at most 64 bits in size. If the input exceeds 64 bits, the gadget is invalid and fails to prove correct execution of the rotation. To safely use rotate64(), you need to make sure that the value passed in is range-checked to 64 bits; for example, using rangeCheck64. You can find more details about the implementation in the Mina book Throws Throws an error if the input value exceeds 64 bits. Example ts const x = Provable.witness(Field, () => Field(0b001100)); const y = Gadgets.rotate64(x, 2, 'left'); // left rotation by 2 bits const z = Gadgets.rotate64(x, 2, 'right'); // right rotation by 2 bits y.assertEquals(0b110000); z.assertEquals(0b000011); const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); Gadgets.rotate64(xLarge, 32, "left"); // throws an error since input exceeds 64 bits
xor(a: Field, b: Field, length: number) => FieldBitwise XOR gadget on Field elements. Equivalent to the bitwise XOR ^ operator in JavaScript. A XOR gate works by comparing two bits and returning 1 if two bits differ, and 0 if two bits are equal. This gadget builds a chain of XOR gates recursively. Each XOR gate can verify 16 bit at most. If your input elements exceed 16 bit, another XOR gate will be added to the chain. The length parameter lets you define how many bits should be compared. length is rounded to the nearest multiple of 16, paddedLength = ceil(length / 16) * 16, and both input values are constrained to fit into paddedLength bits. The output is guaranteed to have at most paddedLength bits as well. Note: Specifying a larger length parameter adds additional constraints. It is also important to mention that specifying a smaller length allows the verifier to infer the length of the original input data (e.g. smaller than 16 bit if only one XOR gate has been used). A zkApp developer should consider these implications when choosing the length parameter and carefully weigh the trade-off between increased amount of constraints and security. Important: Both Field elements need to fit into 2^paddedLength - 1. Otherwise, an error is thrown and no proof can be generated. For example, with length = 2 (paddedLength = 16), xor() will fail for any input that is larger than 2**16. You can find more details about the implementation in the Mina book Throws Throws an error if the input values exceed 2^paddedLength - 1. Example ts let a = Field(0b0101); let b = Field(0b0011); let c = Gadgets.xor(a, b, 4); // xor-ing 4 bits c.assertEquals(0b0110);

Defined in

lib/gadgets/gadgets.ts:31

lib/gadgets/gadgets.ts:822


Hash

Const Hash: Object

A collection of hash functions which can be used in provable code.

Type declaration

NameTypeDescription
Keccak256{ hash: (bytes: Bytes) => Bytes }The pre-NIST Keccak hash function with an output length of 256 bits.
Keccak256.hash[object Object]Hashes the given bytes using Keccak-256. This is an alias for Keccak.preNist(256, bytes).\ See preNist for details and usage examples.
Keccak384{ hash: (bytes: Bytes) => Bytes }The pre-NIST Keccak hash function with an output length of 384 bits.
Keccak384.hash[object Object]Hashes the given bytes using Keccak-384. This is an alias for Keccak.preNist(384, bytes).\ See preNist for details and usage examples.
Keccak512{ hash: (bytes: Bytes) => Bytes }The pre-NIST Keccak hash function with an output length of 512 bits.
Keccak512.hash[object Object]Hashes the given bytes using Keccak-512. This is an alias for Keccak.preNist(512, bytes).\ See preNist for details and usage examples.
Poseidon{ Sponge: typeof Sponge ; hash: (input: Field[]) => Field ; hashPacked: \<T>(type: Hashable\<T>, value: T) => Field ; hashToGroup: (input: Field[]) => { x: Field ; y: { x0: Field ; x1: Field } } ; initialState: () => [Field, Field, Field] ; update: (state: [Field, Field, Field], input: Field[]) => [Field, Field, Field] }-
Poseidon.Spongetypeof Sponge-
Poseidon.hash[object Object]-
Poseidon.hashPacked[object Object]Hashes a provable type efficiently. ts let skHash = Poseidon.hashPacked(PrivateKey, secretKey); Note: Instead of just doing Poseidon.hash(value.toFields()), this uses the toInput() method on the provable type to pack the input into as few field elements as possible. This saves constraints because packing has a much lower per-field element cost than hashing.
Poseidon.hashToGroup[object Object]-
Poseidon.initialState[object Object]-
Poseidon.update[object Object]-
SHA2_256{ hash: (data: FlexibleBytes) => Bytes = Gadgets.SHA256.hash }The SHA2 hash function with an output length of 256 bits.
SHA2_256.hash(data: FlexibleBytes) => BytesHashes the given bytes using SHA2-256. This is an alias for Gadgets.SHA256.hash(bytes).\ See __type for details and usage examples.
SHA3_256{ hash: (bytes: Bytes) => Bytes }The SHA3 hash function with an output length of 256 bits.
SHA3_256.hash[object Object]Hashes the given bytes using SHA3-256. This is an alias for Keccak.nistSha3(256, bytes).\ See nistSha3 for details and usage examples.
SHA3_384{ hash: (bytes: Bytes) => Bytes }The SHA3 hash function with an output length of 384 bits.
SHA3_384.hash[object Object]Hashes the given bytes using SHA3-384. This is an alias for Keccak.nistSha3(384, bytes).\ See nistSha3 for details and usage examples.
SHA3_512{ hash: (bytes: Bytes) => Bytes }The SHA3 hash function with an output length of 512 bits.
SHA3_512.hash[object Object]Hashes the given bytes using SHA3-512. This is an alias for Keccak.nistSha3(512, bytes).\ See nistSha3 for details and usage examples.
hash(input: Field[]) => FieldHashes the given field elements using Poseidon. Alias for Poseidon.hash(). ts let hash = Hash.hash([a, b, c]); Important: This is by far the most efficient hash function o1js has available in provable code. Use it by default, if no compatibility concerns require you to use a different hash function. The Poseidon implementation operates over the native Pallas base field and uses parameters generated specifically for the Mina blockchain. We use a rate of 2, which means that 2 field elements are hashed per permutation. A permutation causes 11 rows in the constraint system. You can find the full set of Poseidon parameters here.

Defined in

lib/hashes-combined.ts:11


Keccak

Const Keccak: Object

Type declaration

NameType
ethereum(message: FlexibleBytes) => Bytes
nistSha3(len: 256 | 512 | 384, message: FlexibleBytes) => Bytes
preNist(len: 256 | 512 | 384, message: FlexibleBytes) => Bytes

Defined in

lib/keccak.ts:11


Permissions

Permissions: Object

Type declaration

NameType
allImpossible() => Permissions
default() => Permissions
dummy() => Permissions
fromJSON(permissions: { access: AuthRequired ; editActionState: AuthRequired ; editState: AuthRequired ; incrementNonce: AuthRequired ; receive: AuthRequired ; send: AuthRequired ; setDelegate: AuthRequired ; setPermissions: AuthRequired ; setTiming: 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:166

lib/account_update.ts:238


Pickles

Pickles: Object

Type declaration

NameType
compile(rules: MlArray\<Rule>, config: { overrideWrapDomain?: 0 | 2 | 1 ; publicInputSize: number ; publicOutputSize: number ; storable?: Cache }) => { getVerificationKey: () => [_: 0, data: string, hash: FieldConst] ; provers: MlArray\<Prover> ; tag: unknown ; verify: (statement: Statement\<FieldConst>, proof: unknown) => Promise\<boolean> }
decodeVerificationKey(vk: string) => MlWrapVerificationKey
dummyProof\<N>(maxProofsVerified: N, domainLog2: number) => [N, unknown]
dummyVerificationKey() => [_: 0, data: string, hash: FieldConst]
encodeVerificationKey(vk: MlWrapVerificationKey) => string
proofOfBase64\<N>(base64: string, maxProofsVerified: N) => [N, unknown]
proofToBase64(proof: [0 | 2 | 1, unknown]) => string
proofToBase64Transaction(proof: unknown) => string
util{ fromMlString: (s: MlBytes) => string ; toMlString: (s: string) => MlBytes }
util.fromMlString[object Object]
util.toMlString[object Object]
loadSrsFp() => WasmFpSrs
loadSrsFq() => WasmFqSrs
verify(statement: Statement\<FieldConst>, proof: unknown, verificationKey: string) => Promise\<boolean>

Defined in

snarky.d.ts:722

snarky.d.ts:769


Poseidon

Const Poseidon: Object

Type declaration

NameType
Spongetypeof Sponge
hash(input: Field[]) => Field
hashPacked\<T>(type: Hashable\<T>, value: T) => Field
hashToGroup(input: Field[]) => { x: Field ; y: { x0: Field ; x1: Field } }
initialState() => [Field, Field, Field]
update(state: [Field, Field, Field], input: Field[]) => [Field, Field, Field]

Defined in

lib/hash.ts:48


Provable

Provable: Object

Type declaration

NameType
Array\<A>(elementType: A, length: number) => InferredProvable\<A[]>
asProver(f: () => void) => void
assertEqual\<T>(type: FlexibleProvable\<T>, x: T, y: T) => void\<T>(x: T, y: T) => void
constraintSystem\<T>(f: () => T) => { digest: string ; gates: Gate[] ; publicInputSize: number ; result: T ; rows: number ; print: () => void ; summary: () => Partial\<Record\<GateType | "Total rows", number>> }
equal\<T>(type: FlexibleProvable\<T>, x: T, y: T) => Bool\<T>(x: T, y: T) => Bool
if\<T>(condition: Bool, type: FlexibleProvable\<T>, x: T, y: T) => T\<T>(condition: Bool, x: T, y: T) => T
inCheckedComputation() => boolean
inProver() => boolean
isConstant\<T>(type: Provable\<T>, x: T) => boolean
log(...args: any) => void
runAndCheck(f: () => void) => void
runUnchecked(f: () => void) => void
switch\<T, A>(mask: Bool[], type: A, values: T[]) => T
witness\<T, S>(type: S, compute: () => T) => T

Defined in

lib/provable.ts:43

lib/provable.ts:45


Snarky

Snarky: Object

Internal interface to snarky-ml

Note for devs: This module is intended to closely mirror snarky-ml's core, low-level APIs.

Type declaration

NameTypeDescription
bool{ and: (x: FieldVar, y: FieldVar) => FieldVar ; assertEqual: (x: FieldVar, y: FieldVar) => void ; equals: (x: FieldVar, y: FieldVar) => FieldVar ; not: (x: FieldVar) => FieldVar ; or: (x: FieldVar, y: FieldVar) => FieldVar }-
bool.and[object Object]-
bool.assertEqual[object Object]-
bool.equals[object Object]-
bool.not[object Object]-
bool.or[object Object]-
circuit{ keypair: { getConstraintSystemJSON: (keypair: unknown) => JsonConstraintSystem ; getVerificationKey: (keypair: unknown) => unknown } ; compile: (main: Main, publicInputSize: number) => unknown ; prove: (main: Main, publicInputSize: number, publicInput: MlArray\<FieldConst>, keypair: unknown) => unknown ; verify: (publicInput: MlArray\<FieldConst>, proof: unknown, verificationKey: unknown) => boolean }The circuit API is a low level interface to create zero-knowledge proofs
circuit.keypair{ getConstraintSystemJSON: (keypair: unknown) => JsonConstraintSystem ; getVerificationKey: (keypair: unknown) => unknown }-
circuit.keypair.getConstraintSystemJSON[object Object]Returns a low-level JSON representation of the circuit: a list of gates, each of which represents a row in a table, with certain coefficients and wires to other (row, column) pairs
circuit.keypair.getVerificationKey[object Object]-
circuit.compile[object Object]Generates a proving key and a verification key for the provable function main
circuit.prove[object Object]Proves a statement using the private input, public input and the keypair of the circuit.
circuit.verify[object Object]Verifies a proof using the public input, the proof and the verification key of the circuit.
field{ add: (x: FieldVar, y: FieldVar) => FieldVar ; assertBoolean: (x: FieldVar) => void ; assertEqual: (x: FieldVar, y: FieldVar) => void ; assertMul: (x: FieldVar, y: FieldVar, z: FieldVar) => void ; assertSquare: (x: FieldVar, y: FieldVar) => void ; compare: (bitLength: number, x: FieldVar, y: FieldVar) => [_: 0, less: FieldVar, lessOrEqual: FieldVar] ; fromBits: (bits: MlArray\<FieldVar>) => FieldVar ; mul: (x: FieldVar, y: FieldVar) => FieldVar ; readVar: (x: FieldVar) => FieldConst ; scale: (c: FieldConst, x: FieldVar) => FieldVar ; seal: (x: FieldVar) => VarFieldVar ; toBits: (length: number, x: FieldVar) => MlArray\<FieldVar> ; toConstantAndTerms: (x: FieldVar) => [_: 0, constant: MlOption\<FieldConst>, terms: MlList\<MlPair\<FieldConst, number>>] ; truncateToBits16: (lengthDiv16: number, x: FieldVar) => FieldVar }APIs to add constraints on field variables
field.add[object Object]add x, y to get a new AST node Add(x, y); handles if x, y are constants
field.assertBoolean[object Object]x*x === x without handling of constants
field.assertEqual[object Object]x === y without handling of constants
field.assertMul[object Object]x*y === z without handling of constants
field.assertSquare[object Object]x*x === y without handling of constants
field.compare[object Object]check x < y and x <= y
field.fromBits[object Object]
field.mul[object Object]witnesses z = x*y and constrains it with [assert_r1cs]; handles constants
field.readVar[object Object]evaluates a CVar by walking the AST and reading Vars from a list of public input + aux values
field.scale[object Object]scale x by a constant to get a new AST node Scale(c, x); handles if x is a constant
field.seal[object Object]returns a new witness from an AST (implemented with toConstantAndTerms)
field.toBits[object Object]
field.toConstantAndTerms[object Object]Unfolds AST to get x = c + c0*Var(i0) + ... + cn*Var(in), returns (c, [(c0, i0), ..., (cn, in)]); c is optional
field.truncateToBits16[object Object]returns x truncated to the lowest 16 * lengthDiv16 bits => can be used to assert that x fits in 16 * lengthDiv16 bits. more efficient than toBits() because it uses the EC_endoscalar gate; does 16 bits per row (vs 1 bits per row that you can do with generic gates).
gates{ addFixedLookupTable: (id: number, data: MlArray\<MlArray\<FieldConst>>) => void ; addRuntimeTableConfig: (id: number, firstColumn: MlArray\<FieldConst>) => void ; ecAdd: (p1: MlGroup, p2: MlGroup, p3: MlGroup, inf: FieldVar, same_x: FieldVar, slope: FieldVar, inf_z: FieldVar, x21_inv: FieldVar) => MlGroup ; ecEndoscalar: (state: MlArray\<[_: 0, n0: FieldVar, n8: FieldVar, a0: FieldVar, b0: FieldVar, a8: FieldVar, b8: FieldVar, x0: FieldVar, x1: FieldVar, x2: FieldVar, x3: FieldVar]>) => void ; ecEndoscale: (state: MlArray\<[_: 0, xt: FieldVar, yt: FieldVar, xp: FieldVar, yp: FieldVar, nAcc: FieldVar, xr: FieldVar, yr: FieldVar, s1: FieldVar, s3: FieldVar, b1: FieldVar]>, xs: FieldVar, ys: FieldVar, nAcc: FieldVar) => void ; ecScale: (state: MlArray\<[_: 0, accs: MlArray\<[0, FieldVar, FieldVar]>, bits: MlArray\<FieldVar>, ss: MlArray\<FieldVar>, base: MlGroup, nPrev: Field, nNext: Field]>) => void ; foreignFieldAdd: (left: [0, FieldVar, FieldVar, FieldVar], right: [0, FieldVar, FieldVar, FieldVar], fieldOverflow: FieldVar, carry: FieldVar, foreignFieldModulus: [0, FieldConst, FieldConst, FieldConst], sign: FieldConst) => void ; foreignFieldMul: (left: [0, FieldVar, FieldVar, FieldVar], right: [0, FieldVar, FieldVar, FieldVar], remainder: [0, FieldVar, FieldVar], quotient: [0, FieldVar, FieldVar, FieldVar], quotientHiBound: FieldVar, product1: [0, FieldVar, FieldVar, FieldVar], carry0: FieldVar, carry1p: [0, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar], carry1c: [0, FieldVar, FieldVar, FieldVar, FieldVar], foreignFieldModulus2: FieldConst, negForeignFieldModulus: [0, FieldConst, FieldConst, FieldConst]) => void ; generic: (sl: FieldConst, l: FieldVar, sr: FieldConst, r: FieldVar, so: FieldConst, o: FieldVar, sm: FieldConst, sc: FieldConst) => void ; lookup: (input: [0, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar]) => void ; poseidon: (state: MlArray\<[0, Field, Field, Field]>) => void ; rangeCheck0: (v0: FieldVar, v0p: [0, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar], v0c: [0, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar], compact: FieldConst) => void ; rangeCheck1: (v2: FieldVar, v12: FieldVar, vCurr: [0, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar], vNext: [0, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar, FieldVar]) => void ; raw: (kind: KimchiGateType, values: MlArray\<FieldVar>, coefficients: MlArray\<FieldConst>) => void ; rotate: (field: FieldVar, rotated: FieldVar, excess: FieldVar, limbs: MlArray\<FieldVar>, crumbs: MlArray\<FieldVar>, two_to_rot: FieldConst) => void ; xor: (in1: FieldVar, in2: FieldVar, out: FieldVar, in1_0: FieldVar, in1_1: FieldVar, in1_2: FieldVar, in1_3: FieldVar, in2_0: FieldVar, in2_1: FieldVar, in2_2: FieldVar, in2_3: FieldVar, out_0: FieldVar, out_1: FieldVar, out_2: FieldVar, out_3: FieldVar) => void ; zero: (in1: FieldVar, in2: FieldVar, out: FieldVar) => void }-
gates.addFixedLookupTable[object Object]-
gates.addRuntimeTableConfig[object Object]-
gates.ecAdd[object Object]Low-level Elliptic Curve Addition gate.
gates.ecEndoscalar[object Object]-
gates.ecEndoscale[object Object]-
gates.ecScale[object Object]-
gates.foreignFieldAdd[object Object]-
gates.foreignFieldMul[object Object]-
gates.generic[object Object]-
gates.lookup[object Object]-
gates.poseidon[object Object]-
gates.rangeCheck0[object Object]Range check gate
gates.rangeCheck1[object Object]-
gates.raw[object Object]-
gates.rotate[object Object]-
gates.xor[object Object]-
gates.zero[object Object]-
group{ scale: (p: MlGroup, s: MlArray\<FieldVar>) => MlGroup }-
group.scale[object Object]-
poseidon{ sponge: { absorb: (sponge: unknown, x: FieldVar) => void ; create: (isChecked: boolean) => unknown ; squeeze: (sponge: unknown) => FieldVar } ; hashToGroup: (input: MlArray\<FieldVar>) => MlPair\<FieldVar, FieldVar> ; update: (state: MlArray\<FieldVar>, input: MlArray\<FieldVar>) => [0, FieldVar, FieldVar, FieldVar] }-
poseidon.sponge{ absorb: (sponge: unknown, x: FieldVar) => void ; create: (isChecked: boolean) => unknown ; squeeze: (sponge: unknown) => FieldVar }-
poseidon.sponge.absorb[object Object]-
poseidon.sponge.create[object Object]-
poseidon.sponge.squeeze[object Object]-
poseidon.hashToGroup[object Object]-
poseidon.update[object Object]-
run{ asProver: (f: () => void) => void ; constraintSystem: (f: () => void) => { digest: string ; json: JsonConstraintSystem ; rows: number } ; inProverBlock: () => boolean ; runAndCheck: (f: () => void) => void ; runUnchecked: (f: () => void) => void }APIs that have to do with running provable code
run.asProver[object Object]Runs code as a prover.
run.constraintSystem[object Object]Returns information about the constraint system in the callback function.
run.inProverBlock[object Object]Check whether we are inside an asProver or exists block
run.runAndCheck[object Object]Runs code and checks its correctness.
run.runUnchecked[object Object]Runs code in prover mode, without checking correctness.
exists(sizeInFields: number, compute: () => MlArray\<FieldConst>) => MlArray\<VarFieldVar>witness sizeInFields field element variables Note: this is called "exists" because in a proof, you use it like this: > "I prove that there exists x, such that (some statement)"
existsVar(compute: () => FieldConst) => VarFieldVarwitness a single field element variable

Defined in

snarky.d.ts:162

snarky.d.ts:174


Test

Const Test: Object

Type declaration

NameType
encoding{ memoHashBase58: (memoBase58: string) => FieldConst ; memoToBase58: (memoString: string) => string ; ofBase58: (base58: string, versionByte: number) => MlBytes ; privateKeyOfBase58: (privateKeyBase58: string) => ScalarConst ; privateKeyToBase58: (privateKey: ScalarConst) => string ; publicKeyOfBase58: (publicKeyBase58: string) => MlPublicKey ; publicKeyToBase58: (publicKey: MlPublicKey) => string ; toBase58: (s: MlBytes, versionByte: number) => string ; tokenIdOfBase58: (fieldBase58: string) => FieldConst ; tokenIdToBase58: (field: FieldConst) => string }
encoding.memoHashBase58[object Object]
encoding.memoToBase58[object Object]
encoding.ofBase58[object Object]
encoding.privateKeyOfBase58[object Object]
encoding.privateKeyToBase58[object Object]
encoding.publicKeyOfBase58[object Object]
encoding.publicKeyToBase58[object Object]
encoding.toBase58[object Object]
encoding.tokenIdOfBase58[object Object]
encoding.tokenIdToBase58[object Object]
fieldsFromJson{ accountUpdate: (json: string) => MlArray\<FieldConst> }
fieldsFromJson.accountUpdate[object Object]
hashFromJson{ accountUpdate: (json: string) => FieldConst ; transactionCommitments: (txJson: string) => { commitment: FieldConst ; feePayerHash: FieldConst ; fullCommitment: FieldConst } ; zkappPublicInput: (txJson: string, accountUpdateIndex: number) => { accountUpdate: FieldConst ; calls: FieldConst } }
hashFromJson.accountUpdate[object Object]
hashFromJson.transactionCommitments[object Object]
hashFromJson.zkappPublicInput[object Object]
hashInputFromJson{ accountPrecondition: (json: String) => MlHashInput ; body: (json: String) => MlHashInput ; networkPrecondition: (json: String) => MlHashInput ; packInput: (input: MlHashInput) => MlArray\<FieldConst> ; permissions: (json: String) => MlHashInput ; timing: (json: String) => MlHashInput ; update: (json: String) => MlHashInput }
hashInputFromJson.accountPrecondition[object Object]
hashInputFromJson.body[object Object]
hashInputFromJson.networkPrecondition[object Object]
hashInputFromJson.packInput[object Object]
hashInputFromJson.permissions[object Object]
hashInputFromJson.timing[object Object]
hashInputFromJson.update[object Object]
poseidon{ hashToGroup: (input: MlArray\<FieldConst>) => MlPair\<FieldConst, FieldConst> }
poseidon.hashToGroup[object Object]
signature{ dummySignature: () => string ; signFieldElement: (messageHash: FieldConst, privateKey: ScalarConst, isMainnet: boolean) => string }
signature.dummySignature[object Object]
signature.signFieldElement[object Object]
tokenId{ derive: (publicKey: MlPublicKey, tokenId: FieldConst) => FieldConst ; deriveChecked: (publicKey: MlPublicKeyVar, tokenId: FieldVar) => FieldVar }
tokenId.derive[object Object]
tokenId.deriveChecked[object Object]
transactionHash{ examplePayment: () => string ; hashPayment: (payment: string) => string ; hashPaymentV1: (payment: string) => string ; serializeCommon: (common: string) => { data: Uint8Array } ; serializePayment: (payment: string) => { data: Uint8Array } ; serializePaymentV1: (payment: string) => string }
transactionHash.examplePayment[object Object]
transactionHash.hashPayment[object Object]
transactionHash.hashPaymentV1[object Object]
transactionHash.serializeCommon[object Object]
transactionHash.serializePayment[object Object]
transactionHash.serializePaymentV1[object Object]

Defined in

snarky.d.ts:616


TokenId

Const TokenId: Object

Type declaration

NameType
check(x: Field) => void
defaultField
empty() => Field
fromFields(x: Field[], aux: any[]) => Field
toAuxiliary(x?: Field) => any[]
toFields(x: Field) => Field[]
toInput(x: Field) => { fields?: Field[] ; packed?: [Field, number][] }
derive(tokenOwner: PublicKey, parentTokenId: Field) => Field
fromBase58(base58: string) => Field
fromJSON(x: string) => Field
sizeInFields() => number
toBase58(t: Field) => string
toJSON(x: Field) => string

Defined in

lib/account_update.ts:607


Undefined

Undefined: ProvablePureExtended\<undefined, null>

Defined in

lib/proof_system.ts:75

lib/proof_system.ts:76


Void

Void: ProvablePureExtended\<void, null>

Defined in

lib/proof_system.ts:80

lib/proof_system.ts:81


ZkappPublicInput

ZkappPublicInput: ProvablePureExtended\<{ accountUpdate: Field = Field; calls: Field = Field }, { accountUpdate: string = Field; calls: string = Field }>

Defined in

lib/account_update.ts:2001

lib/account_update.ts:2005


isReady

isReady: Promise\<void>

Deprecated

await isReady is no longer needed. Remove it from your code.

Defined in

index.ts:138

Functions

Account

Account(address, tokenId?): Account

Parameters

NameType
addressPublicKey
tokenId?Field

Returns

Account

Defined in

lib/zkapp.ts:1504


Bool

Bool(...args): Bool

A boolean value. You can create it like this:

Parameters

NameType
...args[x: boolean | Bool | FieldVar]

Returns

Bool

Example

const b = Bool(true);

You can also combine multiple Bools with boolean operations:

Example

const c = Bool(false);

const d = b.or(c).and(false).not();

d.assertTrue();

Bools are often created by methods on other types such as Field.equals():

const b: Bool = Field(5).equals(6);

Defined in

lib/core.ts:81


Bytes

Bytes(size): typeof Bytes

A provable type representing an array of bytes.

class Bytes32 extends Bytes(32) {}

let bytes = Bytes32.fromHex('deadbeef');

Parameters

NameType
sizenumber

Returns

typeof Bytes

Defined in

lib/provable-types/provable-types.ts:16


Field

Field(...args): Field

A Field is an element of a prime order finite field. Every other provable type is built using the Field type.

The field is the pasta base field of order 2^254 + 0x224698fc094cf91b992d30ed00000001 (ORDER).

You can create a new Field from everything "field-like" (bigint, integer number, decimal string, Field).

Parameters

NameType
...args[x: string | number | bigint | FieldVar | FieldConst | Field]

Returns

Field

A Field with the value converted from the argument

Example

Field(10n); // Field construction from a bigint
Field(100); // Field construction from a number
Field("1"); // Field construction from a decimal string

Beware: Fields cannot be constructed from fractional numbers or alphanumeric strings:

Field(3.141); // ERROR: Cannot convert a float to a field element
Field("abc"); // ERROR: Invalid argument "abc"

Creating a Field from a negative number can result in unexpected behavior if you are not familiar with modular arithmetic.

Example

const x = Field(-1); // valid Field construction from negative number
const y = Field(Field.ORDER - 1n); // same as `x`

Important: All the functions defined on a Field (arithmetic, logic, etc.) take their arguments as "field-like". A Field itself is also defined as a "field-like" element.

Defined in

lib/core.ts:81


Group

Group(...args): Group

An element of a Group.

Parameters

NameType
...args[{ x: string | number | bigint | FieldVar | Field ; y: string | number | bigint | FieldVar | Field }]

Returns

Group

Defined in

lib/core.ts:81


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:238


Reducer

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

Type parameters

NameType
Textends FlexibleProvablePure\<any>
Aextends any = InferProvable\<T>

Parameters

NameType
reducerObject
reducer.actionTypeT

Returns

ReducerReturn\<A>

Defined in

lib/zkapp.ts:1544


State

State\<A>(): State\<A>

Type parameters

Name
A

Returns

State\<A>

Defined in

lib/state.ts:85


Struct

Struct\<A, T, J, Pure>(type): (value: T) => T & { _isStruct: true } & Pure extends true ? ProvablePure\<T> : Provable\<T> & { empty: () => 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 o1js 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 o1js 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 = InferProvable\<A>
Jextends unknown = InferJson\<A>
Pureextends boolean = IsPure\<A>

Parameters

NameTypeDescription
typeAObject specifying the layout of the Struct

Returns

(value: T) => T & { _isStruct: true } & Pure extends true ? ProvablePure\<T> : Provable\<T> & { empty: () => 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:374


VarField

VarField(x): VarField

Parameters

NameType
xVarFieldVar

Returns

VarField

Defined in

lib/field.ts:1363


ZkProgram

ZkProgram\<StatementType, Types>(config): { analyzeMethods: () => { [I in keyof Types]: ReturnType\<typeof analyzeMethod> } ; compile: (options?: { cache?: Cache ; forceRecompile?: boolean }) => Promise\<{ verificationKey: { data: string ; hash: Field } }> ; digest: () => string ; name: string ; privateInputTypes: { [I in keyof Types]: Method\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]>["privateInputs"] } ; publicInputType: ProvableOrUndefined\<Get\<StatementType, "publicInput">> ; publicOutputType: ProvableOrVoid\<Get\<StatementType, "publicOutput">> ; rawMethods: { [I in keyof Types]: Method\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]>["method"] } ; verify: (proof: Proof\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>>) => Promise\<boolean> } & { [I in keyof Types]: Prover\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]> }

Type parameters

NameType
StatementTypeextends Object
Typesextends Object

Parameters

NameType
configStatementType & { methods: { [I in string | number | symbol]: Method\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]> } ; name: string ; overrideWrapDomain?: 0 | 2 | 1 }

Returns

{ analyzeMethods: () => { [I in keyof Types]: ReturnType\<typeof analyzeMethod> } ; compile: (options?: { cache?: Cache ; forceRecompile?: boolean }) => Promise\<{ verificationKey: { data: string ; hash: Field } }> ; digest: () => string ; name: string ; privateInputTypes: { [I in keyof Types]: Method\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]>["privateInputs"] } ; publicInputType: ProvableOrUndefined\<Get\<StatementType, "publicInput">> ; publicOutputType: ProvableOrVoid\<Get\<StatementType, "publicOutput">> ; rawMethods: { [I in keyof Types]: Method\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]>["method"] } ; verify: (proof: Proof\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>>) => Promise\<boolean> } & { [I in keyof Types]: Prover\<InferProvableOrUndefined\<Get\<StatementType, "publicInput">>, InferProvableOrVoid\<Get\<StatementType, "publicOutput">>, Types[I]> }

Defined in

lib/proof_system.ts:245


addCachedAccount

addCachedAccount(partialAccount, graphqlEndpoint?): void

Adds an account to the local cache, indexed by a GraphQL endpoint.

Parameters

NameTypeDefault value
partialAccountPartialAccountundefined
graphqlEndpointstringnetworkConfig.minaEndpoint

Returns

void

Defined in

lib/fetch.ts:390


arrayProp

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

Type parameters

Name
T

Parameters

NameType
elementTypeFlexibleProvable\<T>
lengthnumber

Returns

fn

▸ (target, key): void

Parameters
NameType
targetany
keystring
Returns

void

Defined in

lib/circuit_value.ts:279


assert

assert(stmt, message?): asserts stmt

Assert that a statement is true. If the statement is false, throws an error with the given message. Can be used in provable code.

Parameters

NameType
stmtboolean | Bool
message?string

Returns

asserts stmt

Defined in

lib/gadgets/common.ts:70


checkBitLength

checkBitLength(name, length, maxLength?): void

Parameters

NameTypeDefault value
namestringundefined
lengthnumberundefined
maxLengthnumberFp.sizeInBits

Returns

void

Defined in

lib/field.ts:1301


checkZkappTransaction

checkZkappTransaction(txnId, blockLength?): Promise\<{ failureReason: string[] ; success: boolean = false } | { failureReason: null = null; success: boolean = true }>

Parameters

NameTypeDefault value
txnIdstringundefined
blockLengthnumber20

Returns

Promise\<{ failureReason: string[] ; success: boolean = false } | { failureReason: null = null; success: boolean = true }>

Defined in

lib/fetch.ts:538


circuitMain

circuitMain(target, propertyName, _descriptor?): any

Parameters

NameType
targettypeof Circuit
propertyNamestring
_descriptor?PropertyDescriptor

Returns

any

Defined in

lib/circuit.ts:233


createEcdsa

createEcdsa(curve): typeof EcdsaSignature

Create a class EcdsaSignature for verifying ECDSA signatures on the given curve.

Parameters

NameType
curveCurveParams | typeof ForeignCurve

Returns

typeof EcdsaSignature

Defined in

lib/foreign-ecdsa.ts:189


createForeignCurve

createForeignCurve(params): typeof ForeignCurve

Create a class representing an elliptic curve group, which is different from the native Group.

const Curve = createForeignCurve(Crypto.CurveParams.Secp256k1);

createForeignCurve(params) takes curve parameters CurveParams as input. We support modulus and order to be prime numbers up to 259 bits.

The returned ForeignCurve class represents a non-zero curve point and supports standard elliptic curve operations like point addition and scalar multiplication.

ForeignCurve also includes to associated foreign fields: ForeignCurve.Field and ForeignCurve.Scalar, see createForeignField.

Parameters

NameType
paramsCurveParams

Returns

typeof ForeignCurve

Defined in

lib/foreign-curve.ts:293


createForeignField

createForeignField(modulus): typeof UnreducedForeignField

Create a class representing a prime order finite field, which is different from the native Field.

const SmallField = createForeignField(17n); // the finite field F_17

createForeignField(p) takes the prime modulus p of the finite field as input, as a bigint. We support prime moduli up to a size of 259 bits.

The returned ForeignField class supports arithmetic modulo p (addition and multiplication), as well as helper methods like assertEquals() and equals().

Advanced details:

Internally, a foreign field element is represented as three native field elements, each of which represents a limb of 88 bits. Therefore, being a valid foreign field element means that all 3 limbs fit in 88 bits, and the foreign field element altogether is smaller than the modulus p.

Since the full x < p check is expensive, by default we only prove a weaker assertion, x < 2^ceil(log2(p)), see assertAlmostReduced for more details.

This weaker assumption is what we call "almost reduced", and it is represented by the AlmostForeignField class. Note that only AlmostForeignField supports multiplication and inversion, while UnreducedForeignField only supports addition and subtraction.

This function returns the Unreduced class, which will cause the minimum amount of range checks to be created by default. If you want to do multiplication, you have two options:

  • create your field elements using the AlmostReduced constructor, or using the .provable type on that class.
let x = Provable.witness(ForeignField.AlmostReduced.provable, () => ForeignField.from(5));
  • create your field elements normally and convert them using x.assertAlmostReduced().
let xChecked = x.assertAlmostReduced(); // asserts x < 2^ceil(log2(p)); returns `AlmostForeignField`

Similarly, there is a separate class CanonicalForeignField which represents fully reduced, "canonical" field elements. To convert to a canonical field element, use assertCanonical:

x.assertCanonical(); // asserts x < p; returns `CanonicalForeignField`

You will likely not need canonical fields most of the time.

Base types for all of these classes are separately exported as UnreducedForeignField, AlmostForeignField and CanonicalForeignField.,

Parameters

NameTypeDescription
modulusbigintthe modulus of the finite field you are instantiating

Returns

typeof UnreducedForeignField

Defined in

lib/foreign-field.ts:627


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:1530


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, FlexibleProvablePure\<unknown>>

Returns

void

Defined in

lib/state.ts:175


fetchAccount

fetchAccount(accountInfo, graphqlEndpoint?, «destructured»?): 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?string | Fieldundefined-
graphqlEndpointstringnetworkConfig.minaEndpointThe graphql endpoint to fetch from
«destructured»Object{}-
› 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:152


fetchEvents

fetchEvents(accountInfo, graphqlEndpoint?, filterOptions?): Promise\<{ blockHash: string = event.blockInfo.stateHash; blockHeight: UInt32 ; chainStatus: string = event.blockInfo.chainStatus; events: { data: string[] ; transactionInfo: { hash: string ; memo: string ; status: string } }[] ; globalSlot: UInt32 ; parentBlockHash: string = event.blockInfo.parentHash }[]>

Asynchronously fetches event data for an account from the Mina Archive Node GraphQL API.

Parameters

NameTypeDefault valueDescription
accountInfoObjectundefinedThe account information object.
accountInfo.publicKeystringundefinedThe account public key.
accountInfo.tokenId?stringundefinedThe optional token ID for the account.
graphqlEndpoint?stringnetworkConfig.archiveEndpointThe GraphQL endpoint to query. Defaults to the Archive Node GraphQL API.
filterOptions?EventActionFilterOptions{}The optional filter options object.

Returns

Promise\<{ blockHash: string = event.blockInfo.stateHash; blockHeight: UInt32 ; chainStatus: string = event.blockInfo.chainStatus; events: { data: string[] ; transactionInfo: { hash: string ; memo: string ; status: string } }[] ; globalSlot: UInt32 ; parentBlockHash: string = event.blockInfo.parentHash }[]>

A promise that resolves to an array of objects containing event data, block information and transaction information for the account.

Async

Throws

If the GraphQL request fails or the response is invalid.

Example

const accountInfo = { publicKey: 'B62qiwmXrWn7Cok5VhhB3KvCwyZ7NHHstFGbiU5n7m8s2RqqNW1p1wF' };
const events = await fetchEvents(accountInfo);
console.log(events);

Defined in

lib/fetch.ts:874


fetchLastBlock

fetchLastBlock(graphqlEndpoint?): Promise\<PreconditionBaseTypes\<{ blockchainLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; globalSlotSinceGenesis: { 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 } } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } }>>

Fetches the last block on the Mina network.

Parameters

NameTypeDefault value
graphqlEndpointstringnetworkConfig.minaEndpoint

Returns

Promise\<PreconditionBaseTypes\<{ blockchainLength: { isSome: Bool ; value: { lower: UInt32 ; upper: UInt32 } } ; globalSlotSinceGenesis: { 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 } } ; totalCurrency: { isSome: Bool ; value: { lower: UInt64 ; upper: UInt64 } } }>>

Defined in

lib/fetch.ts:433


fetchTransactionStatus

fetchTransactionStatus(txId, graphqlEndpoint?): Promise\<TransactionStatus>

Fetches the status of a transaction.

Parameters

NameTypeDefault value
txIdstringundefined
graphqlEndpointstringnetworkConfig.minaEndpoint

Returns

Promise\<TransactionStatus>

Defined in

lib/fetch.ts:664


getWasm

getWasm(): WasmModule

Returns

WasmModule

Defined in

bindings/js/wrapper.d.ts:7


matrixProp

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

Type parameters

Name
T

Parameters

NameType
elementTypeFlexibleProvable\<T>
nRowsnumber
nColumnsnumber

Returns

fn

▸ (target, key): void

Parameters
NameType
targetany
keystring
Returns

void

Defined in

lib/circuit_value.ts:288


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

Parameters

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

Returns

void

Defined in

lib/zkapp.ts:83


prop

prop(this, target, key): void

Parameters

NameType
thisany
targetany
keystring

Returns

void

Defined in

lib/circuit_value.ts:264


provable

provable\<A>(typeObj, options?): InferredProvable\<A, Field>

Type parameters

Name
A

Parameters

NameType
typeObjA
options?Object
options.isPure?boolean

Returns

InferredProvable\<A, Field>

Defined in

bindings/lib/provable-generic.ts:23


provablePure

provablePure\<A>(typeObj): ProvablePureExtended\<InferProvable\<A>, InferJson\<A>>

Type parameters

Name
A

Parameters

NameType
typeObjA

Returns

ProvablePureExtended\<InferProvable\<A>, InferJson\<A>>

Defined in

bindings/lib/provable-snarky.ts:55


public_

public_(target, _key, index): void

Parameters

NameType
targetany
_keystring | symbol
indexnumber

Returns

void

Defined in

lib/circuit.ts:197


readVarMessage

readVarMessage(methodName, varName, varDescription): string

Parameters

NameType
methodNamestring
varNamestring
varDescriptionstring

Returns

string

Defined in

lib/field.ts:1343


scaleShifted

scaleShifted(point, shiftedScalar): Group

Parameters

NameType
pointGroup
shiftedScalarScalar

Returns

Group

Defined in

lib/signature.ts:301


sendZkapp

sendZkapp(json, graphqlEndpoint?, «destructured»?): Promise\<[FetchResponse, undefined] | [undefined, FetchError]>

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

Parameters

NameTypeDefault value
jsonstringundefined
graphqlEndpointstringnetworkConfig.minaEndpoint
«destructured»Object{}
› timeoutundefined | numberundefined

Returns

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

Defined in

lib/fetch.ts:694


setArchiveGraphqlEndpoint

setArchiveGraphqlEndpoint(graphqlEndpoint): void

Sets up a GraphQL endpoint to be used for fetching information from an Archive Node.

Parameters

NameType
graphqlEndpointstring

Returns

void

Defined in

lib/fetch.ts:107


setGraphqlEndpoint

setGraphqlEndpoint(graphqlEndpoint): void

Parameters

NameType
graphqlEndpointstring

Returns

void

Defined in

lib/fetch.ts:85


setGraphqlEndpoints

setGraphqlEndpoints(«destructured»): void

Parameters

NameType
«destructured»string[]

Returns

void

Defined in

lib/fetch.ts:78


shutdown

shutdown(): void

Returns

void

Deprecated

shutdown() is no longer needed, and is a no-op. Remove it from your code.

Defined in

index.ts:143


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
stateTypeFlexibleProvablePure\<A>

Returns

fn

▸ (target, key, _descriptor?): void

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

void

Defined in

lib/state.ts:99


toConstantField

toConstantField(x, methodName, varName?, varDescription?): ConstantField

Parameters

NameTypeDefault value
xFieldundefined
methodNamestringundefined
varNamestring'x'
varDescriptionstring'field element'

Returns

ConstantField

Defined in

lib/field.ts:1318


toFp

toFp(x): Fp

Parameters

NameType
xstring | number | bigint | Field

Returns

Fp

Defined in

lib/field.ts:1259


verify

verify(proof, verificationKey): Promise\<boolean>

Parameters

NameType
proofJsonProof | Proof\<any, any>
verificationKeystring | VerificationKey

Returns

Promise\<boolean>

Defined in

lib/proof_system.ts:191


withMessage

withMessage(error, message?): unknown

Parameters

NameType
errorunknown
message?string

Returns

unknown

Defined in

lib/field.ts:1277