-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathzkapp.ts
1417 lines (1331 loc) · 50.8 KB
/
zkapp.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'reflect-metadata';
import { Gate, Pickles, initializeBindings } from '../../snarky.js';
import { Field, Bool } from '../provable/wrapped.js';
import {
AccountUpdate,
Authorization,
Body,
Events,
Permissions,
TokenId,
ZkappCommand,
zkAppProver,
ZkappPublicInput,
LazyProof,
AccountUpdateForest,
AccountUpdateLayout,
AccountUpdateTree,
} from './account-update.js';
import type { EventActionFilterOptions } from './graphql.js';
import {
cloneCircuitValue,
FlexibleProvablePure,
InferProvable,
} from '../provable/types/struct.js';
import {
Provable,
getBlindingValue,
memoizationContext,
} from '../provable/provable.js';
import * as Encoding from '../../bindings/lib/encoding.js';
import {
HashInput,
Poseidon,
hashConstant,
isHashable,
packToFields,
} from '../provable/crypto/poseidon.js';
import { UInt32, UInt64 } from '../provable/int.js';
import * as Mina from './mina.js';
import {
assertPreconditionInvariants,
cleanPreconditionsCache,
} from './precondition.js';
import {
analyzeMethod,
compileProgram,
computeMaxProofsVerified,
Empty,
MethodInterface,
sortMethodArguments,
VerificationKey,
} from '../proof-system/zkprogram.js';
import { Proof, ProofClass } from '../proof-system/proof.js';
import { PublicKey } from '../provable/crypto/signature.js';
import {
InternalStateType,
assertStatePrecondition,
cleanStatePrecondition,
getLayout,
} from './state.js';
import {
inAnalyze,
inCheckedComputation,
inCompile,
inProver,
} from '../provable/core/provable-context.js';
import { Cache } from '../proof-system/cache.js';
import { assert } from '../provable/gadgets/common.js';
import { SmartContractBase } from './smart-contract-base.js';
import { ZkappStateLength } from './mina-instance.js';
import {
SmartContractContext,
accountUpdateLayout,
smartContractContext,
} from './smart-contract-context.js';
import { assertPromise } from '../util/assert.js';
import { ProvablePure, ProvableType } from '../provable/types/provable-intf.js';
import { getReducer, Reducer } from './actions/reducer.js';
import { provable } from '../provable/types/provable-derivers.js';
// external API
export { SmartContract, method, DeployArgs, declareMethods };
const reservedPropNames = new Set(['_methods', '_']);
type AsyncFunction = (...args: any) => Promise<any>;
/**
* A decorator to use in a zkApp to mark a method as provable.
* You can use inside your zkApp class as:
*
* ```
* \@method async myMethod(someArg: Field) {
* // your code here
* }
* ```
*
* To return a value from the method, you have to explicitly declare the return type using the {@link method.returns} decorator:
* ```
* \@method.returns(Field)
* async myMethod(someArg: Field): Promise<Field> {
* // your code here
* }
* ```
*/
function method<K extends string, T extends SmartContract>(
target: T & {
[k in K]: (...args: any) => Promise<void>;
},
methodName: K & string & keyof T,
descriptor: PropertyDescriptor,
returnType?: Provable<any>
) {
const ZkappClass = target.constructor as typeof SmartContract;
if (reservedPropNames.has(methodName)) {
throw Error(`Property name ${methodName} is reserved.`);
}
if (typeof target[methodName] !== 'function') {
throw Error(
`@method decorator was applied to \`${methodName}\`, which is not a function.`
);
}
let paramTypes: Provable<any>[] = Reflect.getMetadata(
'design:paramtypes',
target,
methodName
);
class SelfProof extends Proof<ZkappPublicInput, Empty> {
static publicInputType = ZkappPublicInput;
static publicOutputType = Empty;
static tag = () => ZkappClass;
}
let internalMethodEntry = sortMethodArguments(
ZkappClass.name,
methodName,
paramTypes,
undefined,
SelfProof
);
// add witness arguments for the publicKey (address) and tokenId
let methodEntry = sortMethodArguments(
ZkappClass.name,
methodName,
[PublicKey, Field, ...paramTypes],
undefined,
SelfProof
);
if (returnType !== undefined) {
internalMethodEntry.returnType = returnType;
methodEntry.returnType = returnType;
}
ZkappClass._methods ??= [];
// FIXME: overriding a method implies pushing a separate method entry here, yielding two entries with the same name
// this should only be changed once we no longer share the _methods array with the parent class (otherwise a subclass declaration messes up the parent class)
ZkappClass._methods.push(methodEntry);
let func = descriptor.value as AsyncFunction;
descriptor.value = wrapMethod(func, ZkappClass, internalMethodEntry);
}
/**
* A decorator to mark a zkApp method as provable, and declare its return type.
*
* ```
* \@method.returns(Field)
* async myMethod(someArg: Field): Promise<Field> {
* // your code here
* }
* ```
*/
method.returns = function <
K extends string,
T extends SmartContract,
R extends ProvableType
>(returnType: R) {
return function decorateMethod(
target: T & {
[k in K]: (...args: any) => Promise<InferProvable<R>>;
},
methodName: K & string & keyof T,
descriptor: PropertyDescriptor
) {
return method(
target as any,
methodName,
descriptor,
ProvableType.get(returnType)
);
};
};
// do different things when calling a method, depending on the circumstance
function wrapMethod(
method: AsyncFunction,
ZkappClass: typeof SmartContract,
methodIntf: MethodInterface
) {
let methodName = methodIntf.methodName;
let noPromiseError = `Expected \`${ZkappClass.name}.${methodName}()\` to return a promise.`;
return async function wrappedMethod(
this: SmartContract,
...actualArgs: any[]
) {
cleanStatePrecondition(this);
// special case: any AccountUpdate that is passed as an argument to a method
// is unlinked from its current location, to allow the method to link it to itself
actualArgs.forEach((arg) => {
if (arg instanceof AccountUpdate) {
AccountUpdate.unlink(arg);
}
});
let insideContract = smartContractContext.get();
if (!insideContract) {
const { id, context } = SmartContractContext.enter(
this,
selfAccountUpdate(this, methodName)
);
try {
if (inCompile() || inProver() || inAnalyze()) {
// important to run this with a fresh accountUpdate everytime, otherwise compile messes up our circuits
// because it runs this multiple times
let proverData = inProver() ? zkAppProver.getData() : undefined;
let txId = Mina.currentTransaction.enter({
sender: proverData?.transaction.feePayer.body.publicKey,
// TODO could pass an update with the fee payer's content here? probably not bc it's not accessed
layout: new AccountUpdateLayout(),
fetchMode: inProver() ? 'cached' : 'test',
isFinalRunOutsideCircuit: false,
numberOfRuns: undefined,
});
try {
// inside prover / compile, the method is always called with the public input as first argument
// -- so we can add assertions about it
let publicInput = actualArgs.shift();
let accountUpdate = this.self;
// the blinding value is important because otherwise, putting callData on the transaction would leak information about the private inputs
let blindingValue = Provable.witness(Field, getBlindingValue);
// it's also good if we prove that we use the same blinding value across the method
// that's why we pass the variable (not the constant) into a new context
let memoCtx = memoizationContext() ?? {
memoized: [],
currentIndex: 0,
};
let id = memoizationContext.enter({ ...memoCtx, blindingValue });
let result: unknown;
try {
let clonedArgs = actualArgs.map(cloneCircuitValue);
result = await assertPromise(
method.apply(this, clonedArgs),
noPromiseError
);
} finally {
memoizationContext.leave(id);
}
// connects our input + result with callData, so this method can be called
let callDataFields = computeCallData(
methodIntf,
actualArgs,
result,
blindingValue
);
accountUpdate.body.callData = Poseidon.hash(callDataFields);
ProofAuthorization.setKind(accountUpdate);
debugPublicInput(accountUpdate);
let calls = context.selfLayout.finalizeChildren();
checkPublicInput(publicInput, accountUpdate, calls);
// check the self accountUpdate right after calling the method
// TODO: this needs to be done in a unified way for all account updates that are created
assertPreconditionInvariants(accountUpdate);
cleanPreconditionsCache(accountUpdate);
assertStatePrecondition(this);
return result;
} finally {
Mina.currentTransaction.leave(txId);
}
} else if (!Mina.currentTransaction.has()) {
// outside a transaction, just call the method, but check precondition invariants
let result = await assertPromise(
method.apply(this, actualArgs),
noPromiseError
);
// check the self accountUpdate right after calling the method
// TODO: this needs to be done in a unified way for all account updates that are created
assertPreconditionInvariants(this.self);
cleanPreconditionsCache(this.self);
assertStatePrecondition(this);
return result;
} else {
// called smart contract at the top level, in a transaction!
// => attach ours to the current list of account updates
let accountUpdate = context.selfUpdate;
// first, clone to protect against the method modifying arguments!
// TODO: double-check that this works on all possible inputs, e.g. CircuitValue, o1js primitives
let clonedArgs = cloneCircuitValue(actualArgs);
// we run this in a "memoization context" so that we can remember witnesses for reuse when proving
let blindingValue = getBlindingValue();
let memoContext = { memoized: [], currentIndex: 0, blindingValue };
let memoId = memoizationContext.enter(memoContext);
let result: any;
try {
result = await assertPromise(
method.apply(
this,
actualArgs.map((a, i) => {
return Provable.witness(methodIntf.args[i], () => a);
})
),
noPromiseError
);
} finally {
memoizationContext.leave(memoId);
}
let { memoized } = memoContext;
assertStatePrecondition(this);
// connect our input + result with callData, so this method can be called
let callDataFields = computeCallData(
methodIntf,
clonedArgs,
result,
blindingValue
);
accountUpdate.body.callData = Poseidon.hash(callDataFields);
if (!Authorization.hasAny(accountUpdate)) {
ProofAuthorization.setLazyProof(
accountUpdate,
{
methodName: methodIntf.methodName,
args: clonedArgs,
ZkappClass,
memoized,
blindingValue,
},
Mina.currentTransaction.get().layout
);
}
// transfer layout from the smart contract context to the transaction
if (inCheckedComputation()) {
Provable.asProver(() => {
accountUpdate = Provable.toConstant(AccountUpdate, accountUpdate);
context.selfLayout.toConstantInPlace();
});
}
let txLayout = Mina.currentTransaction.get().layout;
txLayout.pushTopLevel(accountUpdate);
txLayout.setChildren(
accountUpdate,
context.selfLayout.finalizeChildren()
);
return result;
}
} finally {
smartContractContext.leave(id);
}
}
// if we're here, this method was called inside _another_ smart contract method
let parentAccountUpdate = insideContract.this.self;
let { id, context: innerContext } = SmartContractContext.enter(
this,
selfAccountUpdate(this, methodName)
);
try {
// we just reuse the blinding value of the caller for the callee
let blindingValue = getBlindingValue();
let runCalledContract = async () => {
let constantArgs = methodIntf.args.map((type, i) =>
Provable.toConstant(type, actualArgs[i])
);
let constantBlindingValue = blindingValue.toConstant();
let accountUpdate = this.self;
accountUpdate.body.callDepth = parentAccountUpdate.body.callDepth + 1;
let memoContext = {
memoized: [],
currentIndex: 0,
blindingValue: constantBlindingValue,
};
let memoId = memoizationContext.enter(memoContext);
let result: any;
try {
result = await assertPromise(
method.apply(this, constantArgs.map(cloneCircuitValue)),
noPromiseError
);
} finally {
memoizationContext.leave(memoId);
}
let { memoized } = memoContext;
assertStatePrecondition(this);
if (result !== undefined) {
let { returnType } = methodIntf;
assert(
returnType !== undefined,
"Bug: returnType is undefined but the method result isn't."
);
result = Provable.toConstant(returnType, result);
}
// store inputs + result in callData
let callDataFields = computeCallData(
methodIntf,
constantArgs,
result,
constantBlindingValue
);
accountUpdate.body.callData = hashConstant(callDataFields);
if (!Authorization.hasAny(accountUpdate)) {
ProofAuthorization.setLazyProof(
accountUpdate,
{
methodName: methodIntf.methodName,
args: constantArgs,
ZkappClass,
memoized,
blindingValue: constantBlindingValue,
},
Mina.currentTransaction()?.layout ?? new AccountUpdateLayout()
);
}
// extract callee's account update layout
let children = innerContext.selfLayout.finalizeChildren();
return {
accountUpdate,
result: { result: result ?? null, children },
};
};
// we have to run the called contract inside a witness block, to not affect the caller's circuit
let {
accountUpdate,
result: { result, children },
} = await AccountUpdate.witness<{
result: any;
children: AccountUpdateForest;
}>(
provable({
result: methodIntf.returnType ?? provable(null),
children: AccountUpdateForest,
}),
runCalledContract,
{ skipCheck: true }
);
// we're back in the _caller's_ circuit now, where we assert stuff about the method call
// overwrite this.self with the witnessed update, so it's this one we access later in the caller method
innerContext.selfUpdate = accountUpdate;
// connect accountUpdate to our own. outside Provable.witness so compile knows the right structure when hashing children
accountUpdate.body.callDepth = parentAccountUpdate.body.callDepth + 1;
insideContract.selfLayout.pushTopLevel(accountUpdate);
insideContract.selfLayout.setChildren(accountUpdate, children);
// assert that we really called the right zkapp
accountUpdate.body.publicKey.assertEquals(this.address);
accountUpdate.body.tokenId.assertEquals(this.self.body.tokenId);
// assert that the callee account update has proof authorization. everything else would have much worse security trade-offs,
// because a one-time change of the callee semantics by using a signature could go unnoticed even if we monitor the callee's
// onchain verification key
assert(accountUpdate.body.authorizationKind.isProved, 'callee is proved');
// assert that the inputs & outputs we have match what the callee put on its callData
let callDataFields = computeCallData(
methodIntf,
actualArgs,
result,
blindingValue
);
let callData = Poseidon.hash(callDataFields);
accountUpdate.body.callData.assertEquals(callData);
return result;
} finally {
smartContractContext.leave(id);
}
};
}
function checkPublicInput(
{ accountUpdate, calls }: ZkappPublicInput,
self: AccountUpdate,
selfCalls: AccountUpdateForest
) {
accountUpdate.assertEquals(self.hash());
calls.assertEquals(selfCalls.hash);
}
/**
* compute fields to be hashed as callData, in a way that the hash & circuit changes whenever
* the method signature changes, i.e., the argument / return types represented as lists of field elements and the methodName.
* see https://github.com/o1-labs/o1js/issues/303#issuecomment-1196441140
*/
function computeCallData(
methodIntf: MethodInterface,
argumentValues: any[],
returnValue: any,
blindingValue: Field
) {
let { returnType, methodName } = methodIntf;
let args = methodIntf.args.map((type, i) => {
return { type: ProvableType.get(type), value: argumentValues[i] };
});
let input: HashInput = { fields: [], packed: [] };
for (let { type, value } of args) {
if (isHashable(type)) {
input = HashInput.append(input, type.toInput(value));
} else {
input.fields!.push(
...[Field(type.sizeInFields()), ...type.toFields(value)]
);
}
}
const totalArgFields = packToFields(input);
let totalArgSize = Field(
args.map(({ type }) => type.sizeInFields()).reduce((s, t) => s + t, 0)
);
let returnSize = Field(returnType?.sizeInFields() ?? 0);
input = { fields: [], packed: [] };
if (isHashable(returnType)) {
input = HashInput.append(input, returnType.toInput(returnValue));
} else {
input.fields!.push(...(returnType?.toFields(returnValue) ?? []));
}
let returnFields = packToFields(input);
let methodNameFields = Encoding.stringToFields(methodName);
return [
// we have to encode the sizes of arguments / return value, so that fields can't accidentally shift
// from one argument to another, or from arguments to the return value, or from the return value to the method name
totalArgSize,
...totalArgFields,
returnSize,
...returnFields,
// we don't have to encode the method name size because the blinding value is fixed to one field element,
// so method name fields can't accidentally become the blinding value and vice versa
...methodNameFields,
blindingValue,
];
}
/**
* The main zkapp class. To write a zkapp, extend this class as such:
*
* ```
* class YourSmartContract extends SmartContract {
* // your smart contract code here
* }
* ```
*
*/
class SmartContract extends SmartContractBase {
address: PublicKey;
tokenId: Field;
#executionState: ExecutionState | undefined;
// here we store various metadata associated with a SmartContract subclass.
// by initializing all of these to `undefined`, we ensure that
// subclasses aren't sharing the same property with the base class and each other
// FIXME: these are still shared between a subclass and its own subclasses, which means extending SmartContracts is broken
static _methods?: MethodInterface[];
static _methodMetadata?: Record<
string,
{
actions: number;
rows: number;
digest: string;
gates: Gate[];
proofs: ProofClass[];
}
>; // keyed by method name
static _provers?: Pickles.Prover[];
static _verificationKey?: { data: string; hash: Field };
/**
* Returns a Proof type that belongs to this {@link SmartContract}.
*/
static Proof() {
let Contract = this;
return class extends Proof<ZkappPublicInput, Empty> {
static publicInputType = ZkappPublicInput;
static publicOutputType = Empty;
static tag = () => Contract;
};
}
constructor(address: PublicKey, tokenId?: Field) {
super();
this.address = address;
this.tokenId = tokenId ?? TokenId.default;
Object.defineProperty(this, 'reducer', {
set(this, reducer: Reducer<any>) {
((this as any)._ ??= {}).reducer = reducer;
},
get(this) {
return getReducer(this);
},
});
}
/**
* Compile your smart contract.
*
* This generates both the prover functions, needed to create proofs for running `@method`s,
* and the verification key, needed to deploy your zkApp.
*
* Although provers and verification key are returned by this method, they are also cached internally and used when needed,
* so you don't actually have to use the return value of this function.
*
* Under the hood, "compiling" means calling into the lower-level [Pickles and Kimchi libraries](https://o1-labs.github.io/proof-systems/kimchi/overview.html) to
* create multiple prover & verifier indices (one for each smart contract method as part of a "step circuit" and one for the "wrap circuit" which recursively wraps
* it so that proofs end up in the original finite field). These are fairly expensive operations, so **expect compiling to take at least 20 seconds**,
* up to several minutes if your circuit is large or your hardware is not optimal for these operations.
*/
static async compile({
cache = Cache.FileSystemDefault,
forceRecompile = false,
} = {}) {
let methodIntfs = this._methods ?? [];
let methodKeys = methodIntfs.map(({ methodName }) => methodName);
let methods = methodIntfs.map(({ methodName }) => {
return async (
publicInput: unknown,
publicKey: PublicKey,
tokenId: Field,
...args: unknown[]
) => {
let instance = new this(publicKey, tokenId);
await (instance as any)[methodName](publicInput, ...args);
};
});
// run methods once to get information that we need already at compile time
let methodsMeta = await this.analyzeMethods();
let gates = methodKeys.map((k) => methodsMeta[k].gates);
let proofs = methodKeys.map((k) => methodsMeta[k].proofs);
let { verificationKey, provers, verify } = await compileProgram({
publicInputType: ZkappPublicInput,
publicOutputType: Empty,
methodIntfs,
methods,
gates,
proofs,
proofSystemTag: this,
cache,
forceRecompile,
});
this._provers = provers;
this._verificationKey = verificationKey;
// TODO: instead of returning provers, return an artifact from which provers can be recovered
return { verificationKey, provers, verify };
}
/**
* Computes a hash of your smart contract, which will reliably change _whenever one of your method circuits changes_.
* This digest is quick to compute. it is designed to help with deciding whether a contract should be re-compiled or
* a cached verification key can be used.
* @returns the digest, as a hex string
*/
static async digest() {
// TODO: this should use the method digests in a deterministic order!
let methodData = await this.analyzeMethods();
let hash = hashConstant(
Object.values(methodData).map((d) => Field(BigInt('0x' + d.digest)))
);
return hash.toBigInt().toString(16);
}
/**
* The maximum number of proofs that are verified by any of the zkApp methods.
* This is an internal parameter needed by the proof system.
*/
static async getMaxProofsVerified() {
let methodData = await this.analyzeMethods();
return computeMaxProofsVerified(
Object.values(methodData).map((d) => d.proofs.length)
);
}
/**
* Deploys a {@link SmartContract}.
*
* ```ts
* let tx = await Mina.transaction(sender, async () => {
* AccountUpdate.fundNewAccount(sender);
* await zkapp.deploy();
* });
* tx.sign([senderKey, zkAppKey]);
* ```
*/
async deploy({
verificationKey,
}: {
verificationKey?: { data: string; hash: Field | string };
} = {}) {
let accountUpdate = this.newSelf('deploy');
verificationKey ??= (this.constructor as typeof SmartContract)
._verificationKey;
if (verificationKey === undefined) {
if (!Mina.getProofsEnabled()) {
verificationKey = await VerificationKey.dummy();
} else {
throw Error(
`\`${this.constructor.name}.deploy()\` was called but no verification key was found.\n` +
`Try calling \`await ${this.constructor.name}.compile()\` first, this will cache the verification key in the background.`
);
}
}
let { hash: hash_, data } = verificationKey;
let hash = Field.from(hash_);
accountUpdate.account.verificationKey.set({ hash, data });
accountUpdate.account.permissions.set(Permissions.default());
accountUpdate.requireSignature();
AccountUpdate.attachToTransaction(accountUpdate);
// init if this account is not yet deployed or has no verification key on it
let shouldInit =
!Mina.hasAccount(this.address) ||
Mina.getAccount(this.address).zkapp?.verificationKey === undefined;
if (!shouldInit) return;
else await this.init();
let initUpdate = this.self;
// switch back to the deploy account update so the user can make modifications to it
this.#executionState = {
transactionId: this.#executionState!.transactionId,
accountUpdate,
};
// check if the entire state was overwritten, show a warning if not
let isFirstRun = Mina.currentTransaction()?.numberOfRuns === 0;
if (!isFirstRun) return;
Provable.asProver(() => {
if (
initUpdate.update.appState.some(({ isSome }) => !isSome.toBoolean())
) {
console.warn(
`WARNING: the \`init()\` method was called without overwriting the entire state. This means that your zkApp will lack
the \`provedState === true\` status which certifies that the current state was verifiably produced by proofs (and not arbitrarily set by the zkApp developer).
To make sure the entire state is reset, consider adding this line to the beginning of your \`init()\` method:
super.init();
`
);
}
});
}
// TODO make this a @method and create a proof during `zk deploy` (+ add mechanism to skip this)
/**
* `SmartContract.init()` will be called only when a {@link SmartContract} will be first deployed, not for redeployment.
* This method can be overridden as follows
* ```
* class MyContract extends SmartContract {
* init() {
* super.init();
* this.account.permissions.set(...);
* this.x.set(Field(1));
* }
* }
* ```
*/
init() {
// let accountUpdate = this.newSelf(); // this would emulate the behaviour of init() being a @method
this.account.provedState.requireEquals(Bool(false));
let accountUpdate = this.self;
// set all state fields to 0
for (let i = 0; i < ZkappStateLength; i++) {
AccountUpdate.setValue(accountUpdate.body.update.appState[i], Field(0));
}
// for all explicitly declared states, set them to their default value
let stateKeys = getLayout(this.constructor as typeof SmartContract).keys();
for (let key of stateKeys) {
let state = this[key as keyof this] as InternalStateType<any> | undefined;
if (state !== undefined && state.defaultValue !== undefined) {
state.set(state.defaultValue);
}
}
AccountUpdate.attachToTransaction(accountUpdate);
}
/**
* Use this command if the account update created by this SmartContract should be signed by the account owner,
* instead of authorized with a proof.
*
* Note that the smart contract's {@link Permissions} determine which updates have to be (can be) authorized by a signature.
*
* If you only want to avoid creating proofs for quicker testing, we advise you to
* use `LocalBlockchain({ proofsEnabled: false })` instead of `requireSignature()`. Setting
* `proofsEnabled` to `false` allows you to test your transactions with the same authorization flow as in production,
* with the only difference being that quick mock proofs are filled in instead of real proofs.
*/
requireSignature() {
this.self.requireSignature();
}
/**
* Use this command if the account update created by this SmartContract should have no authorization on it,
* instead of being authorized with a proof.
*
* WARNING: This is a method that should rarely be useful. If you want to disable proofs for quicker testing, take a look
* at `LocalBlockchain({ proofsEnabled: false })`, which causes mock proofs to be created and doesn't require changing the
* authorization flow.
*/
skipAuthorization() {
Authorization.setLazyNone(this.self);
}
/**
* Returns the current {@link AccountUpdate} associated to this {@link SmartContract}.
*/
get self(): AccountUpdate {
let inTransaction = Mina.currentTransaction.has();
let inSmartContract = smartContractContext.get();
if (!inTransaction && !inSmartContract) {
// TODO: it's inefficient to return a fresh account update everytime, would be better to return a constant "non-writable" account update,
// or even expose the .get() methods independently of any account update (they don't need one)
return selfAccountUpdate(this);
}
let transactionId = inTransaction ? Mina.currentTransaction.id() : NaN;
// running a method changes which is the "current account update" of this smart contract
// this logic also implies that when calling `this.self` inside a method on `this`, it will always
// return the same account update uniquely associated with that method call.
// it won't create new updates and add them to a transaction implicitly
if (inSmartContract && inSmartContract.this === this) {
let accountUpdate = inSmartContract.selfUpdate;
this.#executionState = { accountUpdate, transactionId };
return accountUpdate;
}
let executionState = this.#executionState;
if (
executionState !== undefined &&
executionState.transactionId === transactionId
) {
return executionState.accountUpdate;
}
// if in a transaction, but outside a @method call, we implicitly create an account update
// which is stable during the current transaction -- as long as it doesn't get overridden by a method call
let accountUpdate = selfAccountUpdate(this);
this.#executionState = { transactionId, accountUpdate };
return accountUpdate;
}
/**
* Same as `SmartContract.self` but explicitly creates a new {@link AccountUpdate}.
*/
newSelf(methodName?: string): AccountUpdate {
let inTransaction = Mina.currentTransaction.has();
let transactionId = inTransaction ? Mina.currentTransaction.id() : NaN;
let accountUpdate = selfAccountUpdate(this, methodName);
this.#executionState = { transactionId, accountUpdate };
return accountUpdate;
}
#_senderState: { sender: PublicKey; transactionId: number };
sender = {
self: this as SmartContract,
/**
* The public key of the current transaction's sender account.
*
* Throws an error if not inside a transaction, or the sender wasn't passed in.
*
* **Warning**: The fact that this public key equals the current sender is not part of the proof.
* A malicious prover could use any other public key without affecting the validity of the proof.
*
* Consider using `this.sender.getAndRequireSignature()` if you need to prove that the sender controls this account.
*/
getUnconstrained(): PublicKey {
// TODO this logic now has some overlap with this.self, we should combine them somehow
// (but with care since the logic in this.self is a bit more complicated)
if (!Mina.currentTransaction.has()) {
throw Error(
`this.sender is not available outside a transaction. Make sure you only use it within \`Mina.transaction\` blocks or smart contract methods.`
);
}
let transactionId = Mina.currentTransaction.id();
let sender;
if (this.self.#_senderState?.transactionId === transactionId) {
sender = this.self.#_senderState.sender;
} else {
sender = Provable.witness(PublicKey, () => Mina.sender());
this.self.#_senderState = { transactionId, sender };
}
// we prove that the returned public key is not the empty key, in which case
// `createSigned()` would skip adding the account update, and nothing is proved
sender.x.assertNotEquals(0);
return sender;
},
/**
* Return a public key that is forced to sign this transaction.
*
* Note: This doesn't prove that the return value is the transaction sender, but it proves that whoever created
* the transaction controls the private key associated with the returned public key.
*/
getAndRequireSignature(): PublicKey {
let sender = this.getUnconstrained();
AccountUpdate.createSigned(sender);
return sender;
},
};
/**
* Current account of the {@link SmartContract}.
*/
get account() {
return this.self.account;
}
/**
* Current network state of the {@link SmartContract}.
*/
get network() {
return this.self.network;
}
/**
* Current global slot on the network. This is the slot at which this transaction is included in a block. Since we cannot know this value
* at the time of transaction construction, this only has the `assertBetween()` method but no `get()` (impossible to implement)
* or `assertEquals()` (confusing, because the developer can't know the exact slot at which this will be included either)
*/
get currentSlot() {
return this.self.currentSlot;
}
/**
* Approve an account update or tree / forest of updates. Doing this means you include the account update in the zkApp's public input,
* which allows you to read and use its content in a proof, make assertions about it, and modify it.
*
* ```ts
* `@method` myApprovingMethod(update: AccountUpdate) {
* this.approve(update);
*
* // read balance on the account (for example)
* let balance = update.account.balance.getAndRequireEquals();
* }
* ```
*
* Under the hood, "approving" just means that the account update is made a child of the zkApp in the
* tree of account updates that forms the transaction. Similarly, if you pass in an {@link AccountUpdateTree},
* the entire tree will become a subtree of the zkApp's account update.
*
* Passing in a forest is a bit different, because it means you set the entire children of the zkApp's account update
* at once. `approve()` will fail if the zkApp's account update already has children, to prevent you from accidentally
* excluding important information from the public input.
*/
approve(update: AccountUpdate | AccountUpdateTree | AccountUpdateForest) {
this.self.approve(update);
}
send(args: {
to: PublicKey | AccountUpdate | SmartContract;
amount: number | bigint | UInt64;
}) {
return this.self.send(args);
}
/**
* Balance of this {@link SmartContract}.
*/
get balance() {
return this.self.balance;
}
/**
* A list of event types that can be emitted using this.emitEvent()`.
*/
events: { [key: string]: FlexibleProvablePure<any> } = {};
// TODO: not able to type event such that it is inferred correctly so far
/**
* Conditionally emits an event.
*
* Events will be emitted as a part of the transaction and can be collected by archive nodes.
*/
emitEventIf<K extends keyof this['events']>(
condition: Bool,
type: K,
event: any
) {
let accountUpdate = this.self;
let eventTypes: (keyof this['events'])[] = Object.keys(this.events);
if (eventTypes.length === 0)