TokenContract
Base token contract which
- implements the
Approvable
API, with theapproveBase()
method left to be defined by subclasses - implements the
Transferable
API as a wrapper around theApprovable
API
Extends
Constructors
new TokenContract()
new TokenContract(address: PublicKey, tokenId?: Field): TokenContract
Parameters
• address: PublicKey
• tokenId?: Field
Returns
Inherited from
Source
Properties
address
address: PublicKey;
Inherited from
Source
events
events: {} = {};
A list of event types that can be emitted using this.emitEvent()`.
Index signature
[key
: string
]: FlexibleProvablePure
\<any
>
Inherited from
Source
sender
sender: {
"self": SmartContract;
"getAndRequireSignature": PublicKey;
"getUnconstrained": PublicKey;
};
self
self: SmartContract;
getAndRequireSignature()
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.
Returns
getUnconstrained()
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.
Returns
Inherited from
Source
tokenId
tokenId: Field;
Inherited from
Source
MAX_ACCOUNT_UPDATES
static MAX_ACCOUNT_UPDATES: number = 9;
The maximum number of account updates using the token in a single transaction that this contract supports.
Source
lib/mina/token/token-contract.ts:29
_maxProofsVerified?
static optional _maxProofsVerified: 0 | 2 | 1;
Inherited from
SmartContract
._maxProofsVerified
Source
_methodMetadata?
static optional _methodMetadata: Record<string, {
"actions": number;
"digest": string;
"gates": Gate[];
"rows": number;
}>;
Inherited from
Source
_methods?
static optional _methods: MethodInterface[];
Inherited from
Source
_provers?
static optional _provers: Prover[];
Inherited from
Source
_verificationKey?
static optional _verificationKey: {
"data": string;
"hash": Field;
};
data
data: string;
hash
hash: Field;
Inherited from
SmartContract
._verificationKey
Source
Accessors
account
get account(): Account
Current account of the SmartContract.
Returns
Account
Source
balance
get balance(): {
"addInPlace": void;
"subInPlace": void;
}
Balance of this SmartContract.
Returns
{
"addInPlace": void;
"subInPlace": void;
}
addInPlace()
Parameters
• x:
| string
| number
| bigint
| UInt64
| UInt32
| Int64
Returns
void
subInPlace()
Parameters
• x:
| string
| number
| bigint
| UInt64
| UInt32
| Int64
Returns
void
Source
currentSlot
get currentSlot(): CurrentSlot
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)
Returns
CurrentSlot
Source
internal
get internal(): {
"burn": AccountUpdate;
"mint": AccountUpdate;
"send": AccountUpdate;
}
Helper methods to use from within a token contract.
Returns
{
"burn": AccountUpdate;
"mint": AccountUpdate;
"send": AccountUpdate;
}
burn()
Burn token balance on address
. Returns the burn account update.
Parameters
• __namedParameters
• __namedParameters.address: PublicKey
| AccountUpdate
| SmartContract
• __namedParameters.amount: number
| bigint
| UInt64
Returns
mint()
Mints token balance to address
. Returns the mint account update.
Parameters
• __namedParameters
• __namedParameters.address: PublicKey
| AccountUpdate
| SmartContract
• __namedParameters.amount: number
| bigint
| UInt64
Returns
send()
Move token balance from from
to to
. Returns the to
account update.
Parameters
• __namedParameters
• __namedParameters.amount: number
| bigint
| UInt64
• __namedParameters.from: PublicKey
| AccountUpdate
| SmartContract
• __namedParameters.to: PublicKey
| AccountUpdate
| SmartContract
Returns
Source
lib/mina/token/token-contract.ts:77
network
get network(): Network
Current network state of the SmartContract.
Returns
Network
Source
self
get self(): AccountUpdate
Returns the current AccountUpdate associated to this SmartContract.
Returns
Source
Methods
approve()
approve(update: AccountUpdate | AccountUpdateTree | AccountUpdateForest): void
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.
`@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 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.
Parameters
• update: AccountUpdate
| AccountUpdateTree
| AccountUpdateForest
Returns
void
Inherited from
Source
approveAccountUpdate()
approveAccountUpdate(accountUpdate: AccountUpdate | AccountUpdateTree): Promise<void>
Approve a single account update (with arbitrarily many children).
Parameters
• accountUpdate: AccountUpdate
| AccountUpdateTree
Returns
Promise
\<void
>
Source
lib/mina/token/token-contract.ts:144
approveAccountUpdates()
approveAccountUpdates(accountUpdates: (AccountUpdate | AccountUpdateTree)[]): Promise<void>
Approve a list of account updates (with arbitrarily many children).
Parameters
• accountUpdates: (AccountUpdate
| AccountUpdateTree
)[]
Returns
Promise
\<void
>
Source
lib/mina/token/token-contract.ts:152
approveBase()
abstract approveBase(forest: AccountUpdateForest): Promise<void>
Parameters
• forest: AccountUpdateForest
Returns
Promise
\<void
>
Source
lib/mina/token/token-contract.ts:84
checkZeroBalanceChange()
checkZeroBalanceChange(updates: AccountUpdateForest): void
Use forEachUpdate()
to prove that the total balance change of child account updates is zero.
This is provided out of the box as it is both a good example, and probably the most common implementation, of approveBase()
.
Parameters
• updates: AccountUpdateForest
Returns
void
Source
lib/mina/token/token-contract.ts:128
deploy()
deploy(args?: DeployArgs): Promise<void>
Deploys a TokenContract.
In addition to base smart contract deployment, this adds two steps:
- set the
access
permission toproofOrSignature()
, to prevent against unauthorized token operations- not doing this would imply that anyone can bypass token contract authorization and simply mint themselves tokens
- require the zkapp account to be new, using the
isNew
precondition. this guarantees that the access permission is set from the very start of the existence of this account. creating the zkapp account before deployment would otherwise be a security vulnerability that is too easy to introduce.
Note that because of the isNew
precondition, the zkapp account must not be created prior to calling deploy()
.
If the contract needs to be re-deployed, you can switch off this behaviour by overriding the isNew
precondition:
async deploy() {
await super.deploy();
// DON'T DO THIS ON THE INITIAL DEPLOYMENT!
this.account.isNew.requireNothing();
}
Parameters
• args?: DeployArgs
Returns
Promise
\<void
>
Overrides
Source
lib/mina/token/token-contract.ts:52
deriveTokenId()
deriveTokenId(): Field
Returns the tokenId
of the token managed by this contract.
Returns
Source
lib/mina/token/token-contract.ts:70
emitEvent()
emitEvent<K>(type: K, event: any): void
Emits an event. Events will be emitted as a part of the transaction and can be collected by archive nodes.
Type parameters
• K extends string
| number
Parameters
• type: K
• event: any
Returns
void
Inherited from
Source
emitEventIf()
emitEventIf<K>(
condition: Bool,
type: K,
event: any): void
Conditionally emits an event.
Events will be emitted as a part of the transaction and can be collected by archive nodes.
Type parameters
• K extends string
| number
Parameters
• condition: Bool
• type: K
• event: any
Returns
void
Inherited from
Source
fetchEvents()
fetchEvents(start?: UInt32, end?: UInt32): Promise<{
"blockHash": string;
"blockHeight": UInt32;
"chainStatus": string;
"event": {
"data": ProvablePure<any>;
"transactionInfo": {
"transactionHash": string;
"transactionMemo": string;
"transactionStatus": string;
};
};
"globalSlot": UInt32;
"parentBlockHash": string;
"type": string;
}[]>
Asynchronously fetches events emitted by this SmartContract and returns an array of events with their corresponding types.
Parameters
• start?: UInt32
= undefined
The start height of the events to fetch.
• end?: UInt32
The end height of the events to fetch. If not provided, fetches events up to the latest height.
Returns
Promise
\<{
"blockHash"
: string
;
"blockHeight"
: UInt32
;
"chainStatus"
: string
;
"event"
: {
"data"
: ProvablePure
\<any
>;
"transactionInfo"
: {
"transactionHash"
: string
;
"transactionMemo"
: string
;
"transactionStatus"
: string
;
};
};
"globalSlot"
: UInt32
;
"parentBlockHash"
: string
;
"type"
: string
;
}[]>
A promise that resolves to an array of objects, each containing the event type and event data for the specified range.
Inherited from
Async
Throws
If there is an error fetching events from the Mina network.
Example
const startHeight = UInt32.from(1000);
const endHeight = UInt32.from(2000);
const events = await myZkapp.fetchEvents(startHeight, endHeight);
console.log(events);
Source
forEachUpdate()
forEachUpdate(updates: AccountUpdateForest, callback: (update: AccountUpdate, usesToken: Bool) => void): void
Iterate through the account updates in updates
and apply callback
to each.
This method is provable and is suitable as a base for implementing approveUpdates()
.
Parameters
• updates: AccountUpdateForest
• callback
Returns
void
Source
lib/mina/token/token-contract.ts:91
init()
init(): void
SmartContract.init()
will be called only when a 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));
}
}
Returns
void
Inherited from
Source
newSelf()
newSelf(methodName?: string): AccountUpdate
Same as SmartContract.self
but explicitly creates a new AccountUpdate.
Parameters
• methodName?: string
Returns
Inherited from
Source
requireSignature()
requireSignature(): void
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 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.
Returns
void
Inherited from
SmartContract
.requireSignature
Source
send()
send(args: {
"amount": number | bigint | UInt64;
"to": PublicKey | AccountUpdate | SmartContract;
}): AccountUpdate
Parameters
• args
• args.amount: number
| bigint
| UInt64
• args.to: PublicKey
| AccountUpdate
| SmartContract
Returns
Inherited from
Source
skipAuthorization()
skipAuthorization(): void
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.
Returns
void
Inherited from
SmartContract
.skipAuthorization
Source
transfer()
transfer(
from: PublicKey | AccountUpdate,
to: PublicKey | AccountUpdate,
amount: number | bigint | UInt64): Promise<void>
Transfer amount
of tokens from from
to to
.
Parameters
• from: PublicKey
| AccountUpdate
• to: PublicKey
| AccountUpdate
• amount: number
| bigint
| UInt64
Returns
Promise
\<void
>
Source
lib/mina/token/token-contract.ts:164
Proof()
static Proof(): typeof __class
Returns a Proof type that belongs to this SmartContract.
Returns
typeof __class
Inherited from
Source
analyzeMethods()
static analyzeMethods(__namedParameters: {
"printSummary": false;
}): Promise<Record<string, {
"actions": number;
"digest": string;
"gates": Gate[];
"rows": number;
}>>
This function is run internally before compiling a smart contract, to collect metadata about what each of your smart contract methods does.
For external usage, this function can be handy because calling it involves running all methods in the same "mode" as compile()
does,
so it serves as a quick-to-run check for whether your contract can be compiled without errors, which can greatly speed up iterating.
analyzeMethods()
will also return the number of rows
of each of your method circuits (i.e., the number of constraints in the underlying proof system),
which is a good indicator for circuit size and the time it will take to create proofs.
To inspect the created circuit in detail, you can look at the returned gates
.
Note: If this function was already called before, it will short-circuit and just return the metadata collected the first time.
Parameters
• __namedParameters= {}
• __namedParameters.printSummary: undefined
| boolean
= false
Returns
Promise
\<Record
\<string
, {
"actions"
: number
;
"digest"
: string
;
"gates"
: Gate
[];
"rows"
: number
;
}>>
an object, keyed by method name, each entry containing:
rows
the size of the constraint system created by this methoddigest
a digest of the method circuitactions
the number of actions the method dispatchesgates
the constraint system, represented as an array of gates
Inherited from
Source
compile()
static compile(__namedParameters: {
"cache": Cache.FileSystemDefault;
"forceRecompile": false;
}): Promise<{
"provers": Prover[];
"verificationKey": {
"data": string;
"hash": Field;
};
"verify": (statement: Statement<FieldConst>, proof: unknown) => Promise<boolean>;
}>
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 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.
Parameters
• __namedParameters= {}
• __namedParameters.cache: undefined
| Cache
= Cache.FileSystemDefault
• __namedParameters.forceRecompile: undefined
| boolean
= false
Returns
Promise
\<{
"provers"
: Prover
[];
"verificationKey"
: {
"data"
: string
;
"hash"
: Field
;
};
"verify"
: (statement
: Statement
\<FieldConst
>, proof
: unknown
) => Promise
\<boolean
>;
}>
provers
provers: Prover[];
verificationKey
verificationKey: {
"data": string;
"hash": Field;
};verificationKey.data
data: string;
verificationKey.hash
hash: Field;
verify()
verify: (statement: Statement<FieldConst>, proof: unknown) => Promise<boolean>;
Parameters
• statement:
Statement
\<FieldConst
>• proof:
unknown
Returns
Promise
\<boolean
>
Inherited from
Source
digest()
static digest(): Promise<string>
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
Promise
\<string
>
the digest, as a hex string
Inherited from
Source
runOutsideCircuit()
static runOutsideCircuit(run: () => void): void
Parameters
• run
Returns
void
Inherited from
SmartContract
.runOutsideCircuit