-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathaccount_update.ts
1565 lines (1439 loc) · 48.5 KB
/
account_update.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 {
provable,
provablePure,
cloneCircuitValue,
memoizationContext,
memoizeWitness,
toConstant,
} from './circuit_value.js';
import { Field, Bool, Ledger, Circuit, Pickles, Provable } from '../snarky.js';
import { jsLayout, Types } from '../snarky/types.js';
import { PrivateKey, PublicKey } from './signature.js';
import { UInt64, UInt32, Int64, Sign } from './int.js';
import * as Mina from './mina.js';
import { SmartContract } from './zkapp.js';
import * as Precondition from './precondition.js';
import { inCheckedComputation, Proof, snarkContext } from './proof_system.js';
import {
emptyHashWithPrefix,
hashWithPrefix,
packToFields,
prefixes,
TokenSymbol,
} from './hash.js';
import * as Encoding from './encoding.js';
import { Context } from './global-context.js';
import { toJSONEssential } from '../snarky/transaction-helpers.js';
import { customTypes } from '../snarky/gen/transaction.js';
// external API
export { Permissions, AccountUpdate, ZkappPublicInput };
// internal API
export {
smartContractContext,
SetOrKeep,
Permission,
Preconditions,
Body,
Authorization,
FeePayerUnsigned,
ZkappCommand,
zkappCommandToJson,
addMissingSignatures,
addMissingProofs,
signJsonTransaction,
ZkappStateLength,
Events,
SequenceEvents,
TokenId,
Token,
CallForest,
createChildAccountUpdate,
makeChildAccountUpdate,
AccountUpdatesLayout,
};
const ZkappStateLength = 8;
let smartContractContext = Context.create<{
this: SmartContract;
methodCallDepth: number;
isCallback: boolean;
selfUpdate: AccountUpdate;
}>();
type AuthRequired = Types.Json.AuthRequired;
type AccountUpdateBody = Types.AccountUpdate['body'];
type Update = AccountUpdateBody['update'];
/**
* Preconditions for the network and accounts
*/
type Preconditions = AccountUpdateBody['preconditions'];
/**
* Timing info inside an account.
*/
type Timing = Update['timing']['value'];
/**
* Either set a value or keep it the same.
*/
type SetOrKeep<T> = { isSome: Bool; value: T };
function keep<T>(dummy: T): SetOrKeep<T> {
return { isSome: Bool(false), value: dummy };
}
const True = () => Bool(true);
const False = () => Bool(false);
/**
* One specific permission value.
*
* A [[ Permission ]] tells one specific permission for our zkapp how it should behave
* when presented with requested modifications.
*
* Use static factory methods on this class to use a specific behavior. See
* documentation on those methods to learn more.
*/
type Permission = Types.AuthRequired;
let Permission = {
/**
* Modification is impossible.
*/
impossible: (): Permission => ({
constant: True(),
signatureNecessary: True(),
signatureSufficient: False(),
}),
/**
* Modification is always permitted
*/
none: (): Permission => ({
constant: True(),
signatureNecessary: False(),
signatureSufficient: True(),
}),
/**
* Modification is permitted by zkapp proofs only
*/
proof: (): Permission => ({
constant: False(),
signatureNecessary: False(),
signatureSufficient: False(),
}),
/**
* Modification is permitted by signatures only, using the private key of the zkapp account
*/
signature: (): Permission => ({
constant: False(),
signatureNecessary: True(),
signatureSufficient: True(),
}),
/**
* Modification is permitted by zkapp proofs or signatures
*/
proofOrSignature: (): Permission => ({
constant: False(),
signatureNecessary: False(),
signatureSufficient: True(),
}),
};
// TODO: we could replace the interface below if we could bridge annotations from OCaml
type Permissions_ = Update['permissions']['value'];
/**
* Permissions specify how specific aspects of the zkapp account are allowed to
* be modified. All fields are denominated by a [[ Permission ]].
*/
interface Permissions extends Permissions_ {
/**
* The [[ Permission ]] corresponding to the 8 state fields associated with an
* account.
*/
editState: Permission;
/**
* The [[ Permission ]] corresponding to the ability to send transactions from this
* account.
*/
send: Permission;
/**
* The [[ Permission ]] corresponding to the ability to receive transactions to this
* account.
*/
receive: Permission;
/**
* The [[ Permission ]] corresponding to the ability to set the delegate field of
* the account.
*/
setDelegate: Permission;
/**
* The [[ Permission ]] corresponding to the ability to set the permissions field of
* the account.
*/
setPermissions: Permission;
/**
* The [[ Permission ]] corresponding to the ability to set the verification key
* associated with the circuit tied to this account. Effectively
* "upgradability" of the smart contract.
*/
setVerificationKey: Permission;
/**
* The [[ Permission ]] corresponding to the ability to set the zkapp uri typically
* pointing to the source code of the smart contract. Usually this should be
* changed whenever the [[ Permissions.setVerificationKey ]] is changed.
* Effectively "upgradability" of the smart contract.
*/
setZkappUri: Permission;
/**
* The [[ Permission ]] corresponding to the ability to change the sequence state
* associated with the account.
*
* TODO: Define sequence state here as well.
*/
editSequenceState: Permission;
/**
* The [[ Permission ]] corresponding to the ability to set the token symbol for
* this account.
*/
setTokenSymbol: Permission;
// TODO: doccomments
incrementNonce: Permission;
setVotingFor: Permission;
}
let Permissions = {
...Permission,
/**
* Default permissions are:
* [[ Permissions.editState ]]=[[ Permission.proof ]]
* [[ Permissions.send ]]=[[ Permission.signature ]]
* [[ Permissions.receive ]]=[[ Permission.none ]]
* [[ Permissions.setDelegate ]]=[[ Permission.signature ]]
* [[ Permissions.setPermissions ]]=[[ Permission.signature ]]
* [[ Permissions.setVerificationKey ]]=[[ Permission.signature ]]
* [[ Permissions.setZkappUri ]]=[[ Permission.signature ]]
* [[ Permissions.editSequenceState ]]=[[ Permission.proof ]]
* [[ Permissions.setTokenSymbol ]]=[[ Permission.signature ]]
*/
default: (): Permissions => ({
editState: Permission.proof(),
send: Permission.signature(),
receive: Permission.none(),
setDelegate: Permission.signature(),
setPermissions: Permission.signature(),
setVerificationKey: Permission.signature(),
setZkappUri: Permission.signature(),
editSequenceState: Permission.proof(),
setTokenSymbol: Permission.signature(),
incrementNonce: Permissions.signature(),
setVotingFor: Permission.signature(),
}),
initial: (): Permissions => ({
editState: Permission.signature(),
send: Permission.signature(),
receive: Permission.none(),
setDelegate: Permission.signature(),
setPermissions: Permission.signature(),
setVerificationKey: Permission.signature(),
setZkappUri: Permission.signature(),
editSequenceState: Permission.signature(),
setTokenSymbol: Permission.signature(),
incrementNonce: Permissions.signature(),
setVotingFor: Permission.signature(),
}),
fromString: (permission: AuthRequired): Permission => {
switch (permission) {
case 'None':
return Permission.none();
case 'Either':
return Permission.proofOrSignature();
case 'Proof':
return Permission.proof();
case 'Signature':
return Permission.signature();
case 'Impossible':
return Permission.impossible();
default:
throw Error(
`Cannot parse invalid permission. ${permission} does not exist.`
);
}
},
fromJSON: (permissions: {
editState: AuthRequired;
send: AuthRequired;
receive: AuthRequired;
setDelegate: AuthRequired;
setPermissions: AuthRequired;
setVerificationKey: AuthRequired;
setZkappUri: AuthRequired;
editSequenceState: AuthRequired;
setTokenSymbol: AuthRequired;
incrementNonce: AuthRequired;
setVotingFor: AuthRequired;
}): Permissions => {
return Object.fromEntries(
Object.entries(permissions).map(([k, v]) => [
k,
Permissions.fromString(v),
])
) as unknown as Permissions;
},
};
type Event = Field[];
type Events = {
hash: Field;
data: Event[];
};
const Events = {
empty(): Events {
let hash = emptyHashWithPrefix('MinaZkappEventsEmpty');
return { hash, data: [] };
},
pushEvent(events: Events, event: Event): Events {
let eventHash = hashWithPrefix(prefixes.event, event);
let hash = hashWithPrefix(prefixes.events, [events.hash, eventHash]);
return { hash, data: [event, ...events.data] };
},
hash(events: Event[]) {
return [...events].reverse().reduce(Events.pushEvent, Events.empty()).hash;
},
};
const SequenceEvents = {
// same as events but w/ different hash prefixes
empty(): Events {
let hash = emptyHashWithPrefix('MinaZkappSequenceEmpty');
return { hash, data: [] };
},
pushEvent(sequenceEvents: Events, event: Event): Events {
let eventHash = hashWithPrefix(prefixes.event, event);
let hash = hashWithPrefix(prefixes.sequenceEvents, [
sequenceEvents.hash,
eventHash,
]);
return { hash, data: [event, ...sequenceEvents.data] };
},
hash(events: Event[]) {
return [...events]
.reverse()
.reduce(SequenceEvents.pushEvent, SequenceEvents.empty()).hash;
},
// different than events
emptySequenceState() {
return emptyHashWithPrefix('MinaZkappSequenceStateEmptyElt');
},
updateSequenceState(state: Field, sequenceEventsHash: Field) {
return hashWithPrefix(prefixes.sequenceEvents, [state, sequenceEventsHash]);
},
};
// TODO: get docstrings from OCaml and delete this interface
/**
* The body of describing how some [[ AccountUpdate ]] should change.
*
* TODO: We need to rename this still.
*/
interface Body extends AccountUpdateBody {
/**
* The address for this body.
*/
publicKey: PublicKey;
/**
* Specify [[ Update ]]s to tweakable pieces of the account record backing
* this address in the ledger.
*/
update: Update;
/**
* The TokenId for this account.
*/
tokenId: Field;
/**
* By what [[ Int64 ]] should the balance of this account change. All
* balanceChanges must balance by the end of smart contract execution.
*/
balanceChange: {
magnitude: UInt64;
sgn: Sign;
};
/**
* Recent events that have been emitted from this account.
*
* TODO: Add a reference to general explanation of events.
*/
events: Events;
sequenceEvents: Events;
caller: Field;
callData: Field;
callDepth: number;
preconditions: Preconditions;
useFullCommitment: Bool;
incrementNonce: Bool;
authorizationKind: AccountUpdateBody['authorizationKind'];
}
const Body = {
noUpdate(): Update {
return {
appState: Array(ZkappStateLength)
.fill(0)
.map(() => keep(Field.zero)),
delegate: keep(PublicKey.empty()),
// TODO
verificationKey: keep({ data: '', hash: Field.zero }),
permissions: keep(Permissions.initial()),
// TODO don't hard code
zkappUri: keep({
data: '',
hash: Field(
'22930868938364086394602058221028773520482901241511717002947639863679740444066'
),
}),
// TODO
tokenSymbol: keep(TokenSymbol.empty),
timing: keep<Timing>({
cliffAmount: UInt64.zero,
cliffTime: UInt32.zero,
initialMinimumBalance: UInt64.zero,
vestingIncrement: UInt64.zero,
vestingPeriod: UInt32.zero,
}),
votingFor: keep(Field.zero),
};
},
/**
* A body that Don't change part of the underlying account record.
*/
keepAll(publicKey: PublicKey): Body {
return {
publicKey,
update: Body.noUpdate(),
tokenId: TokenId.default,
balanceChange: Int64.zero,
events: Events.empty(),
sequenceEvents: SequenceEvents.empty(),
caller: TokenId.default,
callData: Field.zero,
callDepth: 0,
preconditions: Preconditions.ignoreAll(),
// the default assumption is that snarkyjs transactions don't include the fee payer
// so useFullCommitment has to be false for signatures to be correct
useFullCommitment: Bool(false),
// this should be set to true if accountUpdates are signed
incrementNonce: Bool(false),
authorizationKind: { isSigned: Bool(false), isProved: Bool(false) },
};
},
dummy(): Body {
return Body.keepAll(PublicKey.empty());
},
};
type FeePayer = Types.ZkappCommand['feePayer'];
type FeePayerBody = FeePayer['body'];
const FeePayerBody = {
keepAll(publicKey: PublicKey, nonce: UInt32): FeePayerBody {
return {
publicKey,
nonce,
fee: UInt64.zero,
validUntil: undefined,
};
},
};
type FeePayerUnsigned = FeePayer & {
lazyAuthorization?: LazySignature | undefined;
};
/**
* Either check a value or ignore it.
*
* Used within [[ AccountPredicate ]]s and [[ ProtocolStatePredicate ]]s.
*/
type OrIgnore<T> = { isSome: Bool; value: T };
/**
* An interval representing all the values between `lower` and `upper` inclusive
* of both the `lower` and `upper` values.
*
* @typeParam A something with an ordering where one can quantify a lower and
* upper bound.
*/
type ClosedInterval<T> = { lower: T; upper: T };
type NetworkPrecondition = Preconditions['network'];
let NetworkPrecondition = {
ignoreAll(): NetworkPrecondition {
let stakingEpochData = {
ledger: { hash: ignore(Field.zero), totalCurrency: ignore(uint64()) },
seed: ignore(Field.zero),
startCheckpoint: ignore(Field.zero),
lockCheckpoint: ignore(Field.zero),
epochLength: ignore(uint32()),
};
let nextEpochData = cloneCircuitValue(stakingEpochData);
return {
snarkedLedgerHash: ignore(Field.zero),
timestamp: ignore(uint64()),
blockchainLength: ignore(uint32()),
minWindowDensity: ignore(uint32()),
totalCurrency: ignore(uint64()),
globalSlotSinceHardFork: ignore(uint32()),
globalSlotSinceGenesis: ignore(uint32()),
stakingEpochData,
nextEpochData,
};
},
};
/**
* Ignores a `dummy`
*
* @param dummy The value to ignore
* @returns Always an ignored value regardless of the input.
*/
function ignore<T>(dummy: T): OrIgnore<T> {
return { isSome: Bool(false), value: dummy };
}
/**
* Ranges between all uint32 values
*/
const uint32 = () => ({ lower: UInt32.fromNumber(0), upper: UInt32.MAXINT() });
/**
* Ranges between all uint64 values
*/
const uint64 = () => ({ lower: UInt64.fromNumber(0), upper: UInt64.MAXINT() });
type AccountPrecondition = Preconditions['account'];
const AccountPrecondition = {
ignoreAll(): AccountPrecondition {
let appState: Array<OrIgnore<Field>> = [];
for (let i = 0; i < ZkappStateLength; ++i) {
appState.push(ignore(Field.zero));
}
return {
balance: ignore(uint64()),
nonce: ignore(uint32()),
receiptChainHash: ignore(Field.zero),
delegate: ignore(PublicKey.empty()),
state: appState,
sequenceState: ignore(SequenceEvents.emptySequenceState()),
provedState: ignore(Bool(false)),
isNew: ignore(Bool(false)),
};
},
nonce(nonce: UInt32): AccountPrecondition {
let p = AccountPrecondition.ignoreAll();
AccountUpdate.assertEquals(p.nonce, nonce);
return p;
},
};
const Preconditions = {
ignoreAll(): Preconditions {
return {
account: AccountPrecondition.ignoreAll(),
network: NetworkPrecondition.ignoreAll(),
};
},
};
type Control = Types.AccountUpdate['authorization'];
type LazySignature = { kind: 'lazy-signature'; privateKey?: PrivateKey };
type LazyProof = {
kind: 'lazy-proof';
methodName: string;
args: any[];
previousProofs: { publicInput: Field[]; proof: Pickles.Proof }[];
ZkappClass: typeof SmartContract;
memoized: { fields: Field[]; aux: any[] }[];
blindingValue: Field;
};
const TokenId = {
...Types.TokenId,
...Encoding.TokenId,
get default() {
return Field.one;
},
};
class Token {
readonly id: Field;
readonly parentTokenId: Field;
readonly tokenOwner: PublicKey;
static Id = TokenId;
static getId(tokenOwner: PublicKey, parentTokenId = TokenId.default) {
if (tokenOwner.isConstant() && parentTokenId.isConstant()) {
return Ledger.customTokenId(tokenOwner, parentTokenId);
} else {
return Ledger.customTokenIdChecked(tokenOwner, parentTokenId);
}
}
constructor({
tokenOwner,
parentTokenId = TokenId.default,
}: {
tokenOwner: PublicKey;
parentTokenId?: Field;
}) {
this.parentTokenId = parentTokenId;
this.tokenOwner = tokenOwner;
try {
this.id = Token.getId(tokenOwner, parentTokenId);
} catch (e) {
throw new Error(
`Could not create a custom token id:\nError: ${(e as Error).message}`
);
}
}
}
class AccountUpdate implements Types.AccountUpdate {
id: number;
body: Body;
authorization: Control;
lazyAuthorization: LazySignature | LazyProof | undefined = undefined;
account: Precondition.Account;
network: Precondition.Network;
children: { calls?: Field; accountUpdates: AccountUpdate[] } = {
accountUpdates: [],
};
parent: AccountUpdate | undefined = undefined;
private isSelf: boolean;
constructor(body: Body, authorization?: Control);
constructor(body: Body, authorization = {} as Control, isSelf = false) {
this.id = Math.random();
this.body = body;
this.authorization = authorization;
let { account, network } = Precondition.preconditions(this, isSelf);
this.account = account;
this.network = network;
this.isSelf = isSelf;
}
static clone(accountUpdate: AccountUpdate) {
let body = cloneCircuitValue(accountUpdate.body);
let authorization = cloneCircuitValue(accountUpdate.authorization);
let clonedAccountUpdate: AccountUpdate = new (AccountUpdate as any)(
body,
authorization,
accountUpdate.isSelf
);
clonedAccountUpdate.lazyAuthorization = cloneCircuitValue(
accountUpdate.lazyAuthorization
);
clonedAccountUpdate.children.calls = accountUpdate.children.calls;
clonedAccountUpdate.children.accountUpdates =
accountUpdate.children.accountUpdates.map(AccountUpdate.clone);
clonedAccountUpdate.parent = accountUpdate.parent;
return clonedAccountUpdate;
}
token() {
let thisAccountUpdate = this;
let customToken = new Token({
tokenOwner: thisAccountUpdate.body.publicKey,
parentTokenId: thisAccountUpdate.body.tokenId,
});
return {
id: customToken.id,
parentTokenId: customToken.parentTokenId,
tokenOwner: customToken.tokenOwner,
mint({
address,
amount,
}: {
address: PublicKey;
amount: number | bigint | UInt64;
}) {
let receiverAccountUpdate = createChildAccountUpdate(
thisAccountUpdate,
address,
this.id
);
// Add the amount to mint to the receiver's account
receiverAccountUpdate.body.balanceChange = Int64.fromObject(
receiverAccountUpdate.body.balanceChange
).add(amount);
return receiverAccountUpdate;
},
burn({
address,
amount,
}: {
address: PublicKey;
amount: number | bigint | UInt64;
}) {
let senderAccountUpdate = createChildAccountUpdate(
thisAccountUpdate,
address,
this.id
);
senderAccountUpdate.body.useFullCommitment = Bool(true);
// Sub the amount to burn from the sender's account
senderAccountUpdate.body.balanceChange = Int64.fromObject(
senderAccountUpdate.body.balanceChange
).sub(amount);
// Require signature from the sender account being deducted
Authorization.setLazySignature(senderAccountUpdate);
},
send({
from,
to,
amount,
}: {
from: PublicKey;
to: PublicKey;
amount: number | bigint | UInt64;
}) {
// Create a new accountUpdate for the sender to send the amount to the receiver
let senderAccountUpdate = createChildAccountUpdate(
thisAccountUpdate,
from,
this.id
);
senderAccountUpdate.body.useFullCommitment = Bool(true);
let i0 = senderAccountUpdate.body.balanceChange;
senderAccountUpdate.body.balanceChange = new Int64(
i0.magnitude,
i0.sgn
).sub(amount);
// Require signature from the sender accountUpdate
Authorization.setLazySignature(senderAccountUpdate);
let receiverAccountUpdate = createChildAccountUpdate(
thisAccountUpdate,
to,
this.id
);
// Add the amount to send to the receiver's account
let i1 = receiverAccountUpdate.body.balanceChange;
receiverAccountUpdate.body.balanceChange = new Int64(
i1.magnitude,
i1.sgn
).add(amount);
return receiverAccountUpdate;
},
};
}
get tokenId() {
return this.body.tokenId;
}
get tokenSymbol() {
let accountUpdate = this;
return {
set(tokenSymbol: string) {
AccountUpdate.setValue(
accountUpdate.update.tokenSymbol,
TokenSymbol.from(tokenSymbol)
);
},
};
}
send({
to,
amount,
}: {
to: PublicKey | AccountUpdate;
amount: number | bigint | UInt64;
}) {
let receiver;
if (to instanceof AccountUpdate) {
receiver = to;
receiver.body.tokenId.assertEquals(this.body.tokenId);
} else {
receiver = AccountUpdate.defaultAccountUpdate(to, this.body.tokenId);
}
this.authorize(receiver);
// Sub the amount from the sender's account
this.body.balanceChange = Int64.fromObject(this.body.balanceChange).sub(
amount
);
// Add the amount to send to the receiver's account
receiver.body.balanceChange = Int64.fromObject(
receiver.body.balanceChange
).add(amount);
}
authorize(childUpdate: AccountUpdate, layout?: AccountUpdatesLayout) {
makeChildAccountUpdate(this, childUpdate);
if (layout !== undefined) {
AccountUpdate.witnessChildren(childUpdate, layout, { skipCheck: true });
}
}
get balance() {
let accountUpdate = this;
return {
addInPlace(x: Int64 | UInt32 | UInt64 | string | number | bigint) {
let { magnitude, sgn } = accountUpdate.body.balanceChange;
accountUpdate.body.balanceChange = new Int64(magnitude, sgn).add(x);
},
subInPlace(x: Int64 | UInt32 | UInt64 | string | number | bigint) {
let { magnitude, sgn } = accountUpdate.body.balanceChange;
accountUpdate.body.balanceChange = new Int64(magnitude, sgn).sub(x);
},
};
}
get update(): Update {
return this.body.update;
}
static setValue<T>(maybeValue: SetOrKeep<T>, value: T) {
maybeValue.isSome = Bool(true);
maybeValue.value = value;
}
/** Constrain a property to lie between lower and upper bounds.
*
* @param property The property to constrain
* @param lower The lower bound
* @param upper The upper bound
*
* Example: To constrain the account balance of a SmartContract to lie between 0 and 20 MINA, you can use
*
* ```ts
* @method onlyRunsWhenBalanceIsLow() {
* let lower = UInt64.zero;
* let upper = UInt64.fromNumber(20e9);
* AccountUpdate.assertBetween(this.self.body.preconditions.account.balance, lower, upper);
* // ...
* }
* ```
*/
static assertBetween<T>(
property: OrIgnore<ClosedInterval<T>>,
lower: T,
upper: T
) {
property.isSome = Bool(true);
property.value.lower = lower;
property.value.upper = upper;
}
// TODO: assertGreaterThan, assertLowerThan?
/** Fix a property to a certain value.
*
* @param property The property to constrain
* @param value The value it is fixed to
*
* Example: To fix the account nonce of a SmartContract to 0, you can use
*
* ```ts
* @method onlyRunsWhenNonceIsZero() {
* AccountUpdate.assertEquals(this.self.body.preconditions.account.nonce, UInt32.zero);
* // ...
* }
* ```
*/
static assertEquals<T>(property: OrIgnore<ClosedInterval<T> | T>, value: T) {
property.isSome = Bool(true);
if ('lower' in property.value && 'upper' in property.value) {
property.value.lower = value;
property.value.upper = value;
} else {
property.value = value;
}
}
get publicKey(): PublicKey {
return this.body.publicKey;
}
sign(privateKey?: PrivateKey) {
let nonce = AccountUpdate.getNonce(this);
this.account.nonce.assertEquals(nonce);
this.body.incrementNonce = Bool(true);
Authorization.setLazySignature(this, { privateKey });
}
static signFeePayerInPlace(
feePayer: FeePayerUnsigned,
privateKey?: PrivateKey
) {
feePayer.body.nonce = this.getNonce(feePayer);
feePayer.authorization = Ledger.dummySignature();
feePayer.lazyAuthorization = { kind: 'lazy-signature', privateKey };
}
static getNonce(accountUpdate: AccountUpdate | FeePayerUnsigned) {
return memoizeWitness(UInt32, () =>
AccountUpdate.getNonceUnchecked(accountUpdate)
);
}
private static getNonceUnchecked(update: AccountUpdate | FeePayerUnsigned) {
let publicKey = update.body.publicKey;
let tokenId =
update instanceof AccountUpdate ? update.body.tokenId : TokenId.default;
let nonce = Number(
Precondition.getAccountPreconditions(update.body).nonce.toString()
);
// if the fee payer is the same account update as this one, we have to start the nonce predicate at one higher,
// bc the fee payer already increases its nonce
let isFeePayer = Mina.currentTransaction()?.sender?.equals(publicKey);
if (isFeePayer?.toBoolean()) nonce++;
// now, we check how often this accountUpdate already updated its nonce in this tx, and increase nonce from `getAccount` by that amount
CallForest.forEachPredecessor(
Mina.currentTransaction.get().accountUpdates,
update as AccountUpdate,
(otherUpdate) => {
let shouldIncreaseNonce = otherUpdate.publicKey
.equals(publicKey)
.and(otherUpdate.tokenId.equals(tokenId))
.and(otherUpdate.body.incrementNonce);
if (shouldIncreaseNonce.toBoolean()) nonce++;
}
);
return UInt32.from(nonce);
}
toFields() {
return Types.AccountUpdate.toFields(this);
}
toJSON() {
return Types.AccountUpdate.toJSON(this);
}
hash() {
// these two ways of hashing are (and have to be) consistent / produce the same hash
// TODO: there's no reason anymore to use two different hashing methods here!
// -- the "inCheckedComputation" branch works in all circumstances now
// we just leave this here for a couple more weeks, because it checks consistency between
// JS & OCaml hashing on *every single accountUpdate proof* we create. It will give us 100%
// confidence that the two implementations are equivalent, and catch regressions quickly
if (inCheckedComputation()) {
let input = Types.AccountUpdate.toInput(this);
return hashWithPrefix(prefixes.body, packToFields(input));
} else {
let json = Types.AccountUpdate.toJSON(this);
return Ledger.hashAccountUpdateFromJson(JSON.stringify(json));
}
}
// TODO: this was only exposed to be used in a unit test
// consider removing when we have inline unit tests
toPublicInput(): ZkappPublicInput {
let accountUpdate = this.hash();
let calls = CallForest.hashChildren(this);
return { accountUpdate, calls };
}
static defaultAccountUpdate(address: PublicKey, tokenId?: Field) {
const body = Body.keepAll(address);
if (tokenId) {
body.tokenId = tokenId;
body.caller = tokenId;
}
return new AccountUpdate(body);
}
static dummy() {
return this.defaultAccountUpdate(PublicKey.empty());
}
isDummy() {
return this.body.publicKey.isEmpty();
}
static defaultFeePayer(
address: PublicKey,
key: PrivateKey,
nonce: UInt32
): FeePayerUnsigned {
let body = FeePayerBody.keepAll(address, nonce);
return {
body,