-
Notifications
You must be signed in to change notification settings - Fork 122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enforce state preconditions #267
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
3d7d3ee
assert that on-chain state is constrained
mitschabaude 1616c32
adjust examples
mitschabaude dbc2c74
add method to explicitly avoid the error
mitschabaude 3694272
Merge branch 'main' into feature/enforce-state-precondition
mitschabaude 76a6227
update changelog
mitschabaude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,7 +7,10 @@ import { Account, fetchAccount } from './fetch'; | |
import * as GlobalContext from './global-context'; | ||
import { SmartContract } from './zkapp'; | ||
|
||
// external API | ||
export { State, state, declareState }; | ||
// internal API | ||
export { assertStatePrecondition, cleanStatePrecondition }; | ||
|
||
/** | ||
* Gettable and settable state that can be checked for equality. | ||
|
@@ -17,6 +20,7 @@ type State<A> = { | |
set(a: A): void; | ||
fetch(): Promise<A | undefined>; | ||
assertEquals(a: A): void; | ||
assertNothing(): void; | ||
}; | ||
function State<A>(): State<A> { | ||
return createState<A>(); | ||
|
@@ -64,8 +68,11 @@ function state<A>(stateType: AsFieldElements<A>) { | |
stateType: stateType, | ||
instance: this, | ||
class: ZkappClass, | ||
wasConstrained: false, | ||
wasRead: false, | ||
cachedVariable: undefined, | ||
}; | ||
(this._ ?? (this._ = {}))[key] = v; | ||
(this._ ??= {})[key] = v; | ||
}, | ||
}); | ||
}; | ||
|
@@ -121,6 +128,9 @@ type StateAttachedContract<A> = { | |
stateType: AsFieldElements<A>; | ||
instance: SmartContract; | ||
class: typeof SmartContract; | ||
wasRead: boolean; | ||
wasConstrained: boolean; | ||
cachedVariable?: A; | ||
}; | ||
|
||
type InternalStateType<A> = State<A> & { _contract?: StateAttachedContract<A> }; | ||
|
@@ -156,13 +166,26 @@ function createState<T>(): InternalStateType<T> { | |
x | ||
); | ||
}); | ||
this._contract.wasConstrained = true; | ||
}, | ||
|
||
assertNothing() { | ||
if (this._contract === undefined) | ||
throw Error( | ||
'assertNothing can only be called when the State is assigned to a SmartContract @state.' | ||
); | ||
this._contract.wasConstrained = true; | ||
}, | ||
|
||
get() { | ||
if (this._contract === undefined) | ||
throw Error( | ||
'get can only be called when the State is assigned to a SmartContract @state.' | ||
); | ||
if (this._contract.cachedVariable !== undefined) { | ||
this._contract.wasRead = true; | ||
return this._contract.cachedVariable; | ||
} | ||
let layout = getLayoutPosition(this._contract); | ||
let address: PublicKey = this._contract.instance.address; | ||
let stateAsFields: Field[]; | ||
|
@@ -209,6 +232,8 @@ function createState<T>(): InternalStateType<T> { | |
} | ||
let state = this._contract.stateType.ofFields(stateAsFields); | ||
this._contract.stateType.check?.(state); | ||
this._contract.wasRead = true; | ||
this._contract.cachedVariable = state; | ||
return state; | ||
}, | ||
|
||
|
@@ -267,6 +292,7 @@ function getLayout(scClass: typeof SmartContract) { | |
return sc.layout; | ||
} | ||
|
||
// per-smart contract class context for keeping track of state layout | ||
const smartContracts = new WeakMap< | ||
typeof SmartContract, | ||
{ | ||
|
@@ -276,3 +302,37 @@ const smartContracts = new WeakMap< | |
>(); | ||
|
||
const reservedPropNames = new Set(['_methods', '_']); | ||
|
||
function assertStatePrecondition(sc: SmartContract) { | ||
try { | ||
for (let [key, context] of getStateContexts(sc)) { | ||
// check if every state that was read was also contrained | ||
if (!context?.wasRead || context.wasConstrained) continue; | ||
// we accessed a precondition field but not constrained it explicitly - throw an error | ||
let errorMessage = `You used \`this.${key}.get()\` without adding a precondition that links it to the actual on-chain state. | ||
Consider adding this line to your code: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great error message :D |
||
this.${key}.assertEquals(this.${key}.get());`; | ||
throw Error(errorMessage); | ||
} | ||
} finally { | ||
cleanStatePrecondition(sc); | ||
} | ||
} | ||
|
||
function cleanStatePrecondition(sc: SmartContract) { | ||
for (let [, context] of getStateContexts(sc)) { | ||
if (context === undefined) continue; | ||
context.wasRead = false; | ||
context.wasConstrained = false; | ||
context.cachedVariable = undefined; | ||
} | ||
} | ||
|
||
function getStateContexts( | ||
sc: SmartContract | ||
): [string, StateAttachedContract<unknown> | undefined][] { | ||
let scClass = sc.constructor as typeof SmartContract; | ||
let scInfo = smartContracts.get(scClass); | ||
if (scInfo === undefined) return []; | ||
return scInfo.states.map(([key]) => [key, (sc as any)[key]?._contract]); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Quick question, when is
assertNothing
intended to be used?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No specific use case I had in mind, I just wanted to have an escape hatch to get rid of the error if you have some reason to use
.get()
without having a precondition