Documentation
Language Features
Context

Context

The context object (accessed via the ctx object) is a special value that holds the public key needed for authorization checks by the program.

Suppose we have this contract:

contract User {
    id: string;
    name: string;
    publicKey: PublicKey;
 
    constructor (id: string, name: string) {
        this.id = id;
        this.name = name;
        // extract the public key from the context
         this.publicKey = ctx.publicKey;
     }
 
    function setName(newName: string) {
          // check that the public keys match before 
          // allowing function call.
        if (ctx.publicKey != this.publicKey) {
            error('Unauthorized access!)
        }
    }
 }

To pass in the context, pass in the signature like so:

--ctx '{ "publicKey": {"kty": "EC", "crv": "secp256k1", "alg": "ES256K", "use": "sig", "x": "nnzHFO4bZ239bIuAo8t0wQwXH3fPwbKQnpWPzOptv0Q=", "y": "Z1-oY62A6q5kCRGfBuk6E3IrSUjPCK2F6_EwVhW22lY="} }'

For example:

$ cargo run --bin compile -- contract:Account function:setName <<< \
'contract User {
     id: string;
     name: string;
     publicKey: PublicKey;
 
     constructor (id: string, name: string) {
         this.id = id;
         this.name = name;
         // extract the public key from the context
         this.publicKey = ctx.publicKey;
     }
 
     function setName(newName: string) {
           // check that the public keys match before 
           // allowing function call.
         if (ctx.publicKey != this.publicKey) {
             error('Unauthorized access!)
        }
     }
 }' \
  | cargo run -p miden-run -- \
    --ctx '{ "publicKey": {"kty": "EC", "crv": "secp256k1", "alg": "ES256K", "use": "sig", "x": "nnzHFO4bZ239bIuAo8t0wQwXH3fPwbKQnpWPzOptv0Q=", "y": "Z1-oY62A6q5kCRGfBuk6E3IrSUjPCK2F6_EwVhW22lY="} }' \
    --this-json '{ "id": "id1", "name": "John"}' \
    --advice-tape-json '["Tom"]'

Polylang Docs