# Direct Actions Extension

> Provision secrets encrypted to a TEE with signed direct actions, protect against replays, run a sealed-bid auction, and report state that a contract verifies.

> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

Source: https://dev.flare.network/fcc/guides/direct-actions-extension

This guide walks through the [`direct`](https://github.com/flare-foundation/fce-go-scaffold/tree/main/examples/direct) example from the FCE Go scaffold. It shows how to get a secret, such as an API key, into a TEE without putting it onchain or in the image. It also shows how to keep sensitive inputs private while the chain still records who sent them.

The example covers:

-   **Direct actions**: what they are, who can send them, and how the extension authorizes them.
-   **Secrets encrypted to the TEE**: encrypted with ECIES to the TEE's public key and decrypted only inside the TEE.
-   **Replay protection**: making each action idempotent or numbering it.
-   **A sealed-bid auction**: users bid onchain with ciphertexts that only the round's TEE can open.
-   **State verification**: the TEE reports state, and the contract checks it at every availability check.

New to FCC extensions?

Start with [Build Your First Extension](/fcc/guides/getting-started). It covers installing `fce`, the template, and the deploy and run flow that this guide reuses. For how ECIES and the TEE key work, see [TEE public and private keys](/fcc/tee-keys).

## Overview[​](#overview "Direct link to Overview")

Op type

Op command

Channel

Payload

Result

`SECRETS`

`SET_ADMIN`

Instruction

`abi.encode(uint64 nonce, address admin)`

The same

`SECRETS`

`PROVISION`

Direct

JSON `{"teeId", "name", "ciphertext", "signature"}`

JSON `{"name"}`

`SECRETS`

`ROTATE`

Direct

JSON `{"teeId", "counter", "name", "ciphertext", "signature"}`

JSON `{"name", "counter"}`

`AUCTION`

`START`

Instruction

`abi.encode(uint64 round)`

The same

`AUCTION`

`BID`

Instruction

`abi.encode(uint64 round, uint64 number, address bidder, bytes ciphertext)`

`abi.encode(round, number, bidder, bool valid)`

`AUCTION`

`END`

Instruction

`abi.encode(uint64 round, uint64 bids)`

`abi.encode(round, bids, address winner, uint256 amount, bytes signature)`

How it fits together:

1.  The contract owner sets an **admin** onchain with `setAdmin`, which sends a `SET_ADMIN` instruction to the chosen TEEs.
2.  The admin encrypts a secret to a TEE's public key, signs the payload, and posts it to that TEE's proxy as a `PROVISION` or `ROTATE` direct action.
3.  The TEE checks the admin's signature, decrypts the secret, and keeps it in memory. The result names the secret but never contains it.
4.  The TEE reports `(nonce, admin)` as its state. At each availability check, the registry asks the contract, which is the extension's **state verifier**, whether that state is acceptable.

All state lives in memory. A restarted TEE has a new key and therefore a new address, so it needs a new registration and a new `setAdmin`.

## Direct Actions[​](#direct-actions "Direct link to Direct Actions")

A direct action never touches the chain: a client posts it to the TEE's proxy at `POST /direct`. There is no fee and no data provider signature. `tee-node` checks only that the op type is not a system one (`F_`).

Instruction

Direct action

Reaches

The TEEs the contract chooses

Only the TEE behind the proxy it was posted to

Proves who sent it

The contract decides, onchain

Nothing: the proxy API key only opens `/direct`, and it is shared

Can be replayed

By the operator, while its signing policy is the active one or the one before

By anyone who saw it, at any later time

Result read at

`GET /action/result/<id>`

`GET /action/result/<id>?submissionTag=submit` (kept for 30 minutes by default)

An op only accepts direct actions if it is registered with `RegisterDirectHandler`, and each op pair belongs to one channel. So `SET_ADMIN`, which is registered as an instruction, cannot be reached by posting to the proxy.

<details>
<summary>View app.go</summary>

View `app.go`

examples/direct/internal/app/app.go

```
// Package app is the direct example: an admin, set on-chain by the contract's// owner, provisions secrets through direct actions it signs, each encrypted to// the TEE's public key. The owner also runs hidden auctions in rounds: users// bid through the contract, encrypted to the round's TEE, which names only the// winner, signed for the contract.//// Anyone who saw a direct action can post it again, so each one is either// idempotent, as PROVISION, or protected against replay, as ROTATE.// GET /state reports the admin, which the contract checks as the state verifier.package appimport (	"context"	"sync"	"github.com/ethereum/go-ethereum/common"	"github.com/flare-foundation/fce-go-scaffold/pkg/extension"	"github.com/flare-foundation/go-flare-common/pkg/tee/op")// The extension's op pairs. Each pair belongs to one channel, instructions or// direct actions, never both; an op type may have commands on both.const (	// OPTypeSecrets names the extension.	OPTypeSecrets op.Type = "SECRETS"	// OPCommandSetAdmin arrives as an instruction: the contract's owner sets the admin.	OPCommandSetAdmin op.Command = "SET_ADMIN"	// OPCommandProvision arrives as a direct action: the admin stores a secret once.	OPCommandProvision op.Command = "PROVISION"	// OPCommandRotate arrives as a direct action: the admin replaces a secret.	OPCommandRotate op.Command = "ROTATE"	// OPTypeAuction names the auction.	OPTypeAuction op.Type = "AUCTION"	// OPCommandStart arrives as an instruction: the owner starts a round.	OPCommandStart op.Command = "START"	// OPCommandBid arrives as an instruction: a user bids, encrypted to the TEE's key.	OPCommandBid op.Command = "BID"	// OPCommandEnd arrives as an instruction: the owner ends a round after its deadline.	OPCommandEnd op.Command = "END")// Register registers the extension's handlers on s. tee is the TEE's address,// which every signed payload must name; key decrypts the secrets and the bids,// and signs each round's result.func Register(s *extension.Server, tee common.Address, key TEEKey) {	st := newState(tee, key)	s.RegisterInstructionHandler(OPTypeSecrets, OPCommandSetAdmin, st.setAdmin)	s.RegisterDirectHandler(OPTypeSecrets, OPCommandProvision, st.provision)	s.RegisterDirectHandler(OPTypeSecrets, OPCommandRotate, st.rotate)	s.RegisterInstructionHandler(OPTypeAuction, OPCommandStart, st.start)	s.RegisterInstructionHandler(OPTypeAuction, OPCommandBid, st.bid)	s.RegisterInstructionHandler(OPTypeAuction, OPCommandEnd, st.end)	s.RegisterStateFunc(st.report)}// TEEKey decrypts and signs with the TEE key, as *node.Client does through the// sign port.type TEEKey interface {	Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)	SignTEE(ctx context.Context, msg []byte) ([]byte, error)}// state lives in memory. A reboot wipes it and gives the TEE a new address, so// the owner sets the admin again, payloads signed before name another TEE, and// the rounds open on it can't end.type state struct {	tee common.Address	key TEEKey	// tee-node runs instructions and direct actions concurrently	mu       sync.Mutex	nonce    uint64                    // the last setAdmin applied; 0: none	admin    common.Address            // zero: none	counters map[common.Address]uint64 // the last counter ROTATE accepted, per admin	secrets  map[string]string	rounds   map[uint64]*round // each start and bid pays a fee, which bounds their growth}func newState(tee common.Address, key TEEKey) *state {	return &state{		tee: tee, key: key,		counters: map[common.Address]uint64{}, secrets: map[string]string{}, rounds: map[uint64]*round{},	}}
```

</details>

The extension needs its own TEE address so it can check that each payload names it. `main.go` fetches the address from `tee-node` once at startup:

<details>
<summary>View main.go</summary>

View `main.go`

examples/direct/cmd/extension/main.go

```
// Command extension serves tee-node's calls to the extension until it is stopped.package mainimport (	"context"	"fmt"	"os"	"os/signal"	"syscall"	"github.com/flare-foundation/fce-go-scaffold/examples/direct/internal/app"	"github.com/flare-foundation/fce-go-scaffold/pkg/extension"	"github.com/flare-foundation/fce-go-scaffold/pkg/node"	"github.com/flare-foundation/go-flare-common/pkg/logger")func main() {	if err := run(); err != nil {		logger.Fatalf("%v", err)	}}func run() error {	env, err := extension.ReadEnv()	if err != nil {		return fmt.Errorf("reading the environment: %w", err)	}	logger.Set(logger.Config{Level: env.LogLevel})	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)	defer stop()	// signed payloads name the TEE; waits for tee-node to listen	n := node.New(env.SignPort)	tee, err := n.TEEAddress(ctx)	if ctx.Err() != nil {		return nil // stopped while waiting	}	if err != nil {		return fmt.Errorf("fetching the TEE's address: %w", err)	}	srv := extension.New()	app.Register(srv, tee, n)	return srv.ListenAndServe(ctx, env.ExtensionPort)}
```

</details>

## Setting the Admin Onchain[​](#setting-the-admin-onchain "Direct link to Setting the Admin Onchain")

The trusted key is set onchain, so it stays out of the operator's hands and out of the image. Only the contract owner can call `setAdmin`. The chain accepts the extension's instructions only from its registered contract, so nobody else can send `SET_ADMIN`.

Each call takes the next `nonce`, starting at 1. `tee-node` does not remember instructions, so the operator cannot deliver an old `SET_ADMIN` again. The TEE applies a nonce only if it is higher than the last one it applied:

<details>
<summary>View setadmin.go</summary>

View `setadmin.go`

examples/direct/internal/app/setadmin.go

```
package appimport (	"context"	"github.com/ethereum/go-ethereum/accounts/abi"	"github.com/ethereum/go-ethereum/common"	"github.com/flare-foundation/fce-go-scaffold/pkg/extension"	"github.com/flare-foundation/fce-go-scaffold/pkg/payload"	"github.com/flare-foundation/go-flare-common/pkg/tee/instruction")var errOldNonce = extension.PublicError("nonce not above the last", nil)// setAdminArgs is abi.encode(nonce, admin), as the contract's setAdmin builds it.var setAdminArgs = abi.Arguments{	{Name: "nonce", Type: abiType("uint64")},	{Name: "admin", Type: abiType("address")},}// setAdmin sets the admin; the zero address removes it. Only the contract's// owner reaches it: the chain takes this extension's instructions only from its// registered contract, and tee-node checks the data providers signed them.// tee-node doesn't remember instructions, so one can arrive again, or after a// newer one: the contract numbers them, and only a nonce above the last applies.// It answers the payload, abi.encode(nonce, admin).func (st *state) setAdmin(_ context.Context, i *instruction.DataFixed) ([]byte, extension.Run, error) {	var p struct {		Nonce uint64		Admin common.Address	}	if err := payload.DecodeABI(setAdminArgs, i.OriginalMessage, &p); err != nil {		return nil, nil, extension.PublicError("invalid payload", err)	}	st.mu.Lock()	defer st.mu.Unlock()	if p.Nonce <= st.nonce {		return nil, nil, errOldNonce	}	st.nonce, st.admin = p.Nonce, p.Admin	return i.OriginalMessage, nil, nil}func abiType(t string) abi.Type {	typ, err := abi.NewType(t, "", nil)	if err != nil {		panic(err)	}	return typ}
```

</details>

## Authorizing a Direct Action[​](#authorizing-a-direct-action "Direct link to Authorizing a Direct Action")

Nothing tells the extension who posted a direct action, so the authorization travels in the payload. The admin signs, with the Ethereum signed-message prefix (as `cast wallet sign` does), the keccak256 of:

Op

Signed fields

`PROVISION`

`abi.encode(bytes32 opType, bytes32 opCommand, address teeId, string name, bytes ciphertext)`

`ROTATE`

`abi.encode(bytes32 opType, bytes32 opCommand, address teeId, uint256 counter, string name, bytes ciphertext)`

-   **The TEE address** makes a payload signed for one machine invalid on every other machine.
-   **The op pair** keeps a signature for one op from authorizing another.
-   **The ciphertext** keeps anyone from swapping in a different secret.

<details>
<summary>View admin.go</summary>

View `admin.go`

examples/direct/internal/app/admin.go

```
package appimport (	"bytes"	"context"	"errors"	"github.com/ethereum/go-ethereum/accounts"	"github.com/ethereum/go-ethereum/common"	"github.com/ethereum/go-ethereum/crypto"	"github.com/flare-foundation/fce-go-scaffold/pkg/extension")// Refusals every admin action shares.var (	errNoAdmin  = extension.PublicError("no admin", nil)	errWrongTEE = extension.PublicError("not for this TEE", nil)	errNotAdmin = extension.PublicError("not signed by the admin", nil))// Limits on a secret; the admin is trusted, they only keep mistakes small.const (	maxName       = 64	maxValue      = 1024	maxCiphertext = maxValue + eciesOverhead)// eciesOverhead is an ephemeral public key (65 bytes), an IV (16) and a MAC (32).const eciesOverhead = 65 + 16 + 32// authorize checks that a payload names this TEE and that the admin signed its// digest. No caller reaches the extension with a direct action, so the// signature is the only proof of who sent it. st.mu must be held.func (st *state) authorize(tee common.Address, digest common.Hash, sig []byte) error {	if st.admin == (common.Address{}) {		return errNoAdmin	}	if tee != st.tee {		return errWrongTEE	}	signer, err := recoverSigner(digest, sig)	if err != nil || signer != st.admin {		return errNotAdmin	}	return nil}// recoverSigner returns who signed digest under EIP-191, as cast wallet sign// and eth_sign do: V is 27 or 28, or 0 or 1.func recoverSigner(digest common.Hash, sig []byte) (common.Address, error) {	if len(sig) != crypto.SignatureLength {		return common.Address{}, errors.New("not a 65-byte signature")	}	s := bytes.Clone(sig)	if s[crypto.RecoveryIDOffset] >= 27 {		s[crypto.RecoveryIDOffset] -= 27	}	pub, err := crypto.SigToPub(accounts.TextHash(digest[:]), s)	if err != nil {		return common.Address{}, err	}	return crypto.PubkeyToAddress(*pub), nil}func validSecret(name string, ciphertext []byte) bool {	return name != "" && len(name) <= maxName && len(ciphertext) <= maxCiphertext}// open decrypts a secret with the TEE key. Called after authorize, so only the// admin's ciphertexts get here; the sign port is on loopback, so st.mu stays held.func (st *state) open(ctx context.Context, ciphertext []byte) (string, error) {	plain, err := st.key.Decrypt(ctx, ciphertext)	if err != nil {		return "", extension.PublicError("can't decrypt", err)	}	if len(plain) > maxValue {		return "", extension.PublicError("invalid payload", errors.New("secret over the limit"))	}	return string(plain), nil}
```

</details>

## Replay Protection[​](#replay-protection "Direct link to Replay Protection")

The proxy, its operator, and anyone else along the way can post the same direct action again at any time. So every direct action must be one of the following:

-   **Idempotent**: a second send changes nothing, whenever it comes. `PROVISION` stores a secret once. Sending the same secret again succeeds, and sending a different one fails. Encryption is randomized, so the extension compares decrypted secrets, not ciphertexts.
-   **Numbered**: the payload carries something that makes a second send fail. `ROTATE` replaces a secret, and a replayed old rotation would set the secret back. So each rotation carries a `counter`, which must be higher than the last counter this TEE accepted from that admin.

<details>
<summary>View provision.go</summary>

View `provision.go`

examples/direct/internal/app/provision.go

```
package appimport (	"context"	"encoding/json"	"errors"	"fmt"	"github.com/ethereum/go-ethereum/accounts/abi"	"github.com/ethereum/go-ethereum/common"	"github.com/ethereum/go-ethereum/common/hexutil"	"github.com/ethereum/go-ethereum/crypto"	"github.com/flare-foundation/fce-go-scaffold/pkg/extension"	"github.com/flare-foundation/fce-go-scaffold/pkg/payload"	"github.com/flare-foundation/tee-node/pkg/types")var errAnotherValue = extension.PublicError("provisioned with another value", nil)// provisionMessage is the JSON the admin posts to the proxy's /direct. The// secret is encrypted to the TEE's public key: the payload passes the proxy.type provisionMessage struct {	TEE        common.Address `json:"teeId"`	Name       string         `json:"name"`	Ciphertext hexutil.Bytes  `json:"ciphertext"`	Signature  hexutil.Bytes  `json:"signature"`}// secret is the result of PROVISION and ROTATE. Results are public, so it never holds the secret.type secret struct {	Name    string `json:"name"`	Counter uint64 `json:"counter,omitempty"`}// provisionArgs is what the admin signs for PROVISION: the keccak256 of// abi.encode(opType, opCommand, teeId, name, ciphertext), under EIP-191.var provisionArgs = abi.Arguments{	{Name: "opType", Type: abiType("bytes32")},	{Name: "opCommand", Type: abiType("bytes32")},	{Name: "teeId", Type: abiType("address")},	{Name: "name", Type: abiType("string")},	{Name: "ciphertext", Type: abiType("bytes")},}// provision stores a secret once: the same secret again succeeds, another is// refused. A replay, at any later time, changes nothing, so it needs no counter.// Encryption is randomized, so it compares the decrypted secrets.func (st *state) provision(ctx context.Context, d *types.DirectInstruction) ([]byte, extension.Run, error) {	var m provisionMessage	if err := payload.DecodeJSON(d.Message, &m); err != nil {		return nil, nil, extension.PublicError("invalid payload", err)	}	if !validSecret(m.Name, m.Ciphertext) {		return nil, nil, extension.PublicError("invalid payload", errors.New("name or ciphertext out of bounds"))	}	digest, err := provisionDigest(m.TEE, m.Name, m.Ciphertext)	if err != nil {		return nil, nil, extension.PublicError("invalid payload", err)	}	st.mu.Lock()	defer st.mu.Unlock()	if err := st.authorize(m.TEE, digest, m.Signature); err != nil {		return nil, nil, err	}	value, err := st.open(ctx, m.Ciphertext)	if err != nil {		return nil, nil, err	}	if v, ok := st.secrets[m.Name]; ok && v != value {		return nil, nil, errAnotherValue	}	st.secrets[m.Name] = value	out, err := json.Marshal(secret{Name: m.Name})	if err != nil {		return nil, nil, extension.PublicError("encoding the result", err)	}	return out, nil, nil}func provisionDigest(tee common.Address, name string, ciphertext []byte) (common.Hash, error) {	b, err := provisionArgs.Pack(OPTypeSecrets.Hash(), OPCommandProvision.Hash(), tee, name, ciphertext)	if err != nil {		return common.Hash{}, fmt.Errorf("encoding the digest: %w", err)	}	return crypto.Keccak256Hash(b), nil}
```

</details>
<details>
<summary>View rotate.go</summary>

View `rotate.go`

examples/direct/internal/app/rotate.go

```
package appimport (	"context"	"encoding/json"	"errors"	"fmt"	"math/big"	"github.com/ethereum/go-ethereum/accounts/abi"	"github.com/ethereum/go-ethereum/common"	"github.com/ethereum/go-ethereum/common/hexutil"	"github.com/ethereum/go-ethereum/crypto"	"github.com/flare-foundation/fce-go-scaffold/pkg/extension"	"github.com/flare-foundation/fce-go-scaffold/pkg/payload"	"github.com/flare-foundation/tee-node/pkg/types")var (	errNotProvisioned = extension.PublicError("not provisioned", nil)	errOldCounter     = extension.PublicError("counter not above the last", nil))// rotateMessage is the JSON the admin posts to the proxy's /direct.type rotateMessage struct {	TEE        common.Address `json:"teeId"`	Counter    uint64         `json:"counter"`	Name       string         `json:"name"`	Ciphertext hexutil.Bytes  `json:"ciphertext"`	Signature  hexutil.Bytes  `json:"signature"`}// rotateArgs is what the admin signs for ROTATE: the keccak256 of// abi.encode(opType, opCommand, teeId, counter, name, ciphertext), under EIP-191.var rotateArgs = abi.Arguments{	{Name: "opType", Type: abiType("bytes32")},	{Name: "opCommand", Type: abiType("bytes32")},	{Name: "teeId", Type: abiType("address")},	{Name: "counter", Type: abiType("uint256")},	{Name: "name", Type: abiType("string")},	{Name: "ciphertext", Type: abiType("bytes")},}// rotate replaces a provisioned secret. Replayed later, an old rotation would// set the secret back, so the admin numbers them: each counter must be above// the last one accepted from that admin. Counters live in memory, which is// enough: after a reboot the TEE has a new address, which old payloads don't name.func (st *state) rotate(ctx context.Context, d *types.DirectInstruction) ([]byte, extension.Run, error) {	var m rotateMessage	if err := payload.DecodeJSON(d.Message, &m); err != nil {		return nil, nil, extension.PublicError("invalid payload", err)	}	if !validSecret(m.Name, m.Ciphertext) {		return nil, nil, extension.PublicError("invalid payload", errors.New("name or ciphertext out of bounds"))	}	digest, err := rotateDigest(m.TEE, m.Counter, m.Name, m.Ciphertext)	if err != nil {		return nil, nil, extension.PublicError("invalid payload", err)	}	st.mu.Lock()	defer st.mu.Unlock()	if err := st.authorize(m.TEE, digest, m.Signature); err != nil {		return nil, nil, err	}	if m.Counter <= st.counters[st.admin] {		return nil, nil, errOldCounter	}	if _, ok := st.secrets[m.Name]; !ok {		return nil, nil, errNotProvisioned	}	value, err := st.open(ctx, m.Ciphertext)	if err != nil {		return nil, nil, err	}	st.counters[st.admin] = m.Counter	st.secrets[m.Name] = value	out, err := json.Marshal(secret{Name: m.Name, Counter: m.Counter})	if err != nil {		return nil, nil, extension.PublicError("encoding the result", err)	}	return out, nil, nil}func rotateDigest(tee common.Address, counter uint64, name string, ciphertext []byte) (common.Hash, error) {	b, err := rotateArgs.Pack(OPTypeSecrets.Hash(), OPCommandRotate.Hash(), tee, new(big.Int).SetUint64(counter), name, ciphertext)	if err != nil {		return common.Hash{}, fmt.Errorf("encoding the digest: %w", err)	}	return crypto.Keccak256Hash(b), nil}
```

</details>

The counters can live in memory, and no clock is needed. After a restart the TEE has a new address, which no previously signed payload names.

Results and logs are public

Never repeat a secret in a result, a log, or an error message. Wrap errors that might carry one in `extension.PublicError`.

## Sealed-Bid Auction[​](#sealed-bid-auction "Direct link to Sealed-Bid Auction")

The same contract runs sealed-bid auctions in rounds, using the TEE's key for privacy:

1.  **`startRound(period)`**: the owner starts a round. The contract picks a random production TEE to run it and accepts bids for `period` seconds. `rounds(round)` returns the round's TEE and deadline.
    
2.  **`bid(round, ciphertext)`**: anyone bids before the deadline. The plaintext is JSON that names the round, the bidder, and the amount, encrypted to the round TEE's key:
    
    ```
    printf -v amount '%78s' "$AMOUNT"; amount=${amount// /0}printf '{"tag":"AUCTION_BID_V1","round":%d,"bidder":"%s","amount":"%s"}' "$ROUND" "$BIDDER" "$amount" \  | fce encrypt -pubkey "$key" -tee "$TEE_ID"
    ```
    
    The amount is zero-padded to 78 digits because a ciphertext is as long as its plaintext, so a variable-width amount would reveal its size onchain. The plaintext names the bidder and the round, so anyone who copies the ciphertext into their own bid gets an invalid bid.
    
3.  **`endRound(round)`**: after the deadline, the owner ends the round. The TEE answers only once it has seen the round's start and every bid the contract counted. This turns a withheld bid into a visible refusal (`error: bid N missing`) instead of a result that silently leaves it out.
    
4.  **`submitResult(round, result)`**: anyone submits the TEE's signed answer. The contract checks that the round's TEE signed it and that the bid count matches, then records the winner and the amount.
    

The TEE only ever reveals the winner and the winning amount, never a losing bid. The contract records who won and at what price, but moves no money besides fees. Lost instructions can be sent again with `resendStart` and `resendBid`. A stalled round can be cancelled with `cancelRound`.

Encrypted input onchain is public forever

Anyone can read the ciphertext, and only the round's TEE can open it. That means the operator and the chain see who bids and when, but never how much. Always bind such input to its sender, as the bid's `bidder` field does, so a copy can't be passed off as someone else's.

## State and the State Verifier[​](#state-and-the-state-verifier "Direct link to State and the State Verifier")

`GET /state` reports the extension's state, which `tee-node` includes in its signed TEE info. This extension reports `abi.encode(uint64 nonce, address admin)`, the last `setAdmin` the TEE applied. The report omits the secrets and counters because they arrive by direct action, and the chain cannot check them.

<details>
<summary>View report.go</summary>

View `report.go`

examples/direct/internal/app/report.go

```
package appimport (	"context"	"github.com/ethereum/go-ethereum/common")// stateVersion names report's encoding: the contract's STATE_VERSION,// right-padded as op names are.var stateVersion = func() (h common.Hash) {	copy(h[:], "SECRETS_STATE_V1")	return h}()// report serves GET /state: abi.encode(nonce, admin), the last setAdmin// applied, (0, 0) before any. The contract, the registered state verifier,// checks it against what it sent this TEE. Only what came from the chain is// reported: the chain can't check the secrets or the counters.func (st *state) report(context.Context) (common.Hash, []byte, error) {	st.mu.Lock()	defer st.mu.Unlock()	b, err := setAdminArgs.Pack(st.nonce, st.admin)	return stateVersion, b, err}
```

</details>

The registry accepts a non-empty state only from an extension with a registered **state verifier** contract. `InstructionSender` here is both the instruction sender and the state verifier, and `Deploy.s.sol` writes its address under both names, so `fce deploy` registers it as both.

At each availability check, the registry calls `verifyTeeState`. It accepts only:

-   a `(nonce, admin)` that the contract actually sent to that TEE, or `(0, 0)`;
-   and only while every newer `setAdmin` sent to that TEE is at most `MAX_STATE_LAG` (2 hours) old.

So an operator who withholds a `setAdmin` can keep the machine on the old admin for at most 2 hours. After that, the machine fails its availability checks and anyone can suspend it. A state verifier must never revert, because a revert would block every availability check of the machine.

<details>
<summary>View InstructionSender.sol</summary>

View `InstructionSender.sol`

examples/direct/contracts/src/InstructionSender.sol

```
// SPDX-License-Identifier: MITpragma solidity ^0.8.28;import { ExtensionBase } from "fcc-extension-scaffold/src/ExtensionBase.sol";import { ITeeExtensionStateVerifier } from "flare-periphery/src/coston2/ITeeExtensionStateVerifier.sol";/// @title InstructionSender/// @notice The direct example's entrypoint contract: its owner sets the admin, whose signed/// direct actions provision the extension's secrets. The owner also runs hidden auctions in/// rounds: users bid through it, encrypted to the round's TEE, and anyone submits the winner the/// TEE signs. It is also the extension's state verifier: a TEE passes its availability checks/// only while it keeps up with the admins set for it./// @dev NOTE: the deployer owns this contract, with the admin, the project fee and its/// withdrawal, and, through fce deploy, the extension in the registry, which decides what code/// its machines run. Secure that key, or move both (for example to a multisig), before production.contract InstructionSender is ExtensionBase, ITeeExtensionStateVerifier {    /// @notice The extension's op type, the Go side's OPTypeSecrets.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant OP_TYPE_SECRETS = bytes32("SECRETS");    /// @notice SET_ADMIN, the Go side's OPCommandSetAdmin.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant OP_COMMAND_SET_ADMIN = bytes32("SET_ADMIN");    /// @notice The auction's op type, the Go side's OPTypeAuction.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant OP_TYPE_AUCTION = bytes32("AUCTION");    /// @notice START, the Go side's OPCommandStart.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant OP_COMMAND_START = bytes32("START");    /// @notice BID, the Go side's OPCommandBid.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant OP_COMMAND_BID = bytes32("BID");    /// @notice END, the Go side's OPCommandEnd.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant OP_COMMAND_END = bytes32("END");    /// @notice The tag opening every result the TEE signs, the Go side's resultTag: it keeps the    /// signature from meaning anything else.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant RESULT_TAG = bytes32("AUCTION_RESULT_V1");    /// @notice Names the state's encoding, abi.encode(uint64 nonce, address admin): the Go side's    /// stateVersion.    // forge-lint: disable-next-line(unsafe-typecast)    bytes32 public constant STATE_VERSION = bytes32("SECRETS_STATE_V1");    /// @notice How long a TEE may go without applying a setAdmin sent to it. It covers the time    /// between the TEE reporting its state and the availability proof reaching the chain, under    /// the registry's challenge window, plus delivery.    uint256 public constant MAX_STATE_LAG = 2 hours;    /// @notice The largest ciphertext bid takes, the Go side's maxBidCiphertext: the TEE would    /// refuse a larger one, and the fee isn't refunded.    uint256 public constant MAX_BID_SIZE = 369;    /// @notice How long after a round's last endRound, with no result submitted, the owner may    /// cancel it.    uint256 public constant RESULT_TIMEOUT = 1 hours;    /// @notice An admin setting, as setAdmin sent it.    struct AdminSetting {        address admin;        uint64 sentAt;    }    /// @notice The last setAdmin's number; each call takes the next, from 1.    uint64 public adminNonce;    /// @notice Each setAdmin's setting, by its number.    mapping(uint64 nonce => AdminSetting) public adminSettings;    // the numbers of the setAdmin calls sent to each TEE, increasing    mapping(address teeId => uint64[]) private sentNonces;    /// @notice Where a round is: bidding and then waiting for its result are both Open.    enum Status {        None,        Open,        Settled,        Cancelled    }    /// @notice An auction round: the TEE running it, its deadline, how many bids it took, when the    /// owner last ended it (0: never), and its winner and the winning amount once settled.    struct Round {        address teeId;        uint64 deadline;        uint64 bids;        uint64 endedAt;        Status status;        address winner;        uint256 amount;    }    /// @notice The last round's number; each startRound takes the next, from 1.    uint64 public roundCount;    /// @notice Each round, by its number.    mapping(uint64 round => Round) public rounds;    /// @notice keccak256(abi.encode(bidder, ciphertext)) of each bid, by round and number, so a bid    /// the pipeline lost can be sent again.    mapping(uint64 round => mapping(uint64 number => bytes32)) public bidHashes;    event AdminSent(uint64 indexed nonce, address indexed admin, address[] teeIds);    event RoundStarted(uint64 indexed round, address teeId, uint64 deadline, bytes32 instructionId);    event BidPlaced(uint64 indexed round, uint64 number, address indexed bidder, bytes32 instructionId);    event RoundEnded(uint64 indexed round, uint64 bids, bytes32 instructionId);    // number 0: the round's start    event Resent(uint64 indexed round, uint64 number, bytes32 instructionId);    event RoundSettled(uint64 indexed round, address indexed winner, uint256 amount);    event RoundCancelled(uint64 indexed round);    error ZeroPeriod();    error RoundNotOpen(uint64 round);    error BiddingClosed(uint64 round, uint64 deadline);    error BiddingOpen(uint64 round, uint64 deadline);    error BidTooLarge(uint256 size);    error NotTheBid(uint64 round, uint64 number);    error WrongRound(uint64 round);    error WrongBidCount(uint64 bids, uint64 expected);    error WrongTee(address signer, address teeId);    error TooEarlyToCancel(uint64 round, uint256 allowedAfter);    /// @param _flareTeeManager The FlareTeeManager diamond's address.    constructor(address _flareTeeManager) ExtensionBase(_flareTeeManager) { }    /// @notice The price of setAdmin for `_teeIds`.    function quoteSetAdmin(address[] calldata _teeIds) external view returns (uint256) {        return _protocolFee(OP_TYPE_SECRETS, OP_COMMAND_SET_ADMIN, _teeIds) + projectFee;    }    /// @notice Sets the admin on each of `_teeIds`, which must be distinct; the zero address    /// removes it. Pay at least quoteSetAdmin(_teeIds); the contract keeps any excess.    /// @dev Each call is numbered, and a TEE applies only a number above the last it applied: an    /// instruction can arrive again, or after a newer one. Each TEE keeps the admin in memory:    /// one that reboots comes back as a new TEE, and needs it again.    function setAdmin(address _admin, address[] calldata _teeIds)        external        payable        onlyOwner        chargesFees        returns (bytes32)    {        uint64 nonce = ++adminNonce;        adminSettings[nonce] = AdminSetting(_admin, uint64(block.timestamp));        for (uint256 i; i < _teeIds.length; ++i) {            sentNonces[_teeIds[i]].push(nonce);        }        emit AdminSent(nonce, _admin, _teeIds);        return _send(_teeIds, OP_TYPE_SECRETS, OP_COMMAND_SET_ADMIN, abi.encode(nonce, _admin));    }    /// @notice Starts a round, taking bids for `_period` seconds, on a random production TEE of the    /// extension; bidders encrypt to that TEE's key. Pay at least    /// quoteFee(OP_TYPE_AUCTION, OP_COMMAND_START); the contract keeps any excess.    function startRound(uint32 _period) external payable onlyOwner chargesFees returns (uint64 _round) {        require(_period != 0, ZeroPeriod());        address[] memory teeIds = _randomTee();        _round = ++roundCount;        uint64 deadline = uint64(block.timestamp) + _period;        rounds[_round] = Round(teeIds[0], deadline, 0, 0, Status.Open, address(0), 0);        bytes32 id = _send(teeIds, OP_TYPE_AUCTION, OP_COMMAND_START, abi.encode(_round));        emit RoundStarted(_round, teeIds[0], deadline, id);    }    /// @notice Bids in `_round` until its deadline: `_ciphertext` is the bid encrypted to the round's    /// TEE, in the format the README gives. Pay at least quoteFee(OP_TYPE_AUCTION, OP_COMMAND_BID);    /// the contract keeps any excess.    /// @dev The ciphertext stays public on chain; the TEE counts it as invalid unless its plaintext    /// names the caller and the round. Every valid bid stands: the highest leads.    function bid(uint64 _round, bytes calldata _ciphertext) external payable chargesFees returns (uint64 _number) {        Round storage r = _open(_round);        // a validator moves the timestamp by seconds; bidding takes longer        // forge-lint: disable-next-line(block-timestamp)        require(block.timestamp <= r.deadline, BiddingClosed(_round, r.deadline));        require(_ciphertext.length <= MAX_BID_SIZE, BidTooLarge(_ciphertext.length));        _number = ++r.bids;        bidHashes[_round][_number] = keccak256(abi.encode(msg.sender, _ciphertext));        bytes32 id = _sendTo(r.teeId, OP_COMMAND_BID, abi.encode(_round, _number, msg.sender, _ciphertext));        emit BidPlaced(_round, _number, msg.sender, id);    }    /// @notice Ends `_round` after its deadline: its TEE answers with the winner, signed, for    /// submitResult, once it has the round's start and every bid. Send it again while the TEE    /// answers that a bid is missing. Pay at least quoteFee(OP_TYPE_AUCTION, OP_COMMAND_END); the    /// excess is kept.    function endRound(uint64 _round) external payable onlyOwner chargesFees returns (bytes32 _instructionId) {        Round storage r = _open(_round);        // a validator moves the timestamp by seconds; bidding takes longer        // forge-lint: disable-next-line(block-timestamp)        require(block.timestamp > r.deadline, BiddingOpen(_round, r.deadline));        r.endedAt = uint64(block.timestamp);        _instructionId = _sendTo(r.teeId, OP_COMMAND_END, abi.encode(_round, r.bids));        emit RoundEnded(_round, r.bids, _instructionId);    }    /// @notice Sends `_round`'s start again, for one the pipeline lost. Pay at least    /// quoteFee(OP_TYPE_AUCTION, OP_COMMAND_START); the contract keeps any excess.    function resendStart(uint64 _round) external payable onlyOwner chargesFees returns (bytes32 _instructionId) {        Round storage r = _open(_round);        _instructionId = _sendTo(r.teeId, OP_COMMAND_START, abi.encode(_round));        emit Resent(_round, 0, _instructionId);    }    /// @notice Sends bid `_number` of `_round` again, for one the pipeline lost: anyone may, even after    /// the deadline, with the bid's bidder and ciphertext. Pay at least    /// quoteFee(OP_TYPE_AUCTION, OP_COMMAND_BID); the contract keeps any excess.    function resendBid(uint64 _round, uint64 _number, address _bidder, bytes calldata _ciphertext)        external        payable        chargesFees        returns (bytes32 _instructionId)    {        Round storage r = _open(_round);        require(bidHashes[_round][_number] == keccak256(abi.encode(_bidder, _ciphertext)), NotTheBid(_round, _number));        _instructionId = _sendTo(r.teeId, OP_COMMAND_BID, abi.encode(_round, _number, _bidder, _ciphertext));        emit Resent(_round, _number, _instructionId);    }    /// @notice Settles `_round`: `_result` is the data of its TEE's answer to endRound,    /// abi.encode(round, bids, winner, amount, signature). Anyone may submit it, once; the TEE's    /// signature is the proof. With no valid bid, the winner and the amount are zero.    function submitResult(uint64 _round, bytes calldata _result) external {        Round storage r = _open(_round);        (uint64 resultRound, uint64 bids, address winner, uint256 amount, bytes memory signature) =            abi.decode(_result, (uint64, uint64, address, uint256, bytes));        require(resultRound == _round, WrongRound(resultRound));        require(bids == r.bids, WrongBidCount(bids, r.bids));        address signer = _teeSigner(resultDigest(_round, bids, winner, amount), signature);        require(signer == r.teeId, WrongTee(signer, r.teeId));        r.status = Status.Settled;        r.winner = winner;        r.amount = amount;        emit RoundSettled(_round, winner, amount);    }    /// @notice Cancels `_round`: before the owner first ends it, or once RESULT_TIMEOUT has passed    /// since the last endRound with no result submitted. A cancelled round takes nothing more.    function cancelRound(uint64 _round) external onlyOwner {        Round storage r = _open(_round);        uint256 allowedAfter = uint256(r.endedAt) + RESULT_TIMEOUT;        // a validator moves the timestamp by seconds; the timeout is an hour        // forge-lint: disable-next-line(block-timestamp)        require(r.endedAt == 0 || block.timestamp > allowedAfter, TooEarlyToCancel(_round, allowedAfter));        r.status = Status.Cancelled;        emit RoundCancelled(_round);    }    /// @notice The keccak256 of the message the TEE signs for a round's outcome:    /// abi.encode(RESULT_TAG, round, keccak256(abi.encode(bids, winner, amount))).    function resultDigest(uint64 _round, uint64 _bids, address _winner, uint256 _amount) public pure returns (bytes32) {        return keccak256(abi.encode(RESULT_TAG, _round, keccak256(abi.encode(_bids, _winner, _amount))));    }    /// @notice The registry's check of a TEE's state, at each availability check. The state is    /// the last setAdmin the TEE applied, (0, 0) before any: it must be one this contract sent    /// that TEE, and every newer one sent to it must be at most MAX_STATE_LAG old. A TEE whose    /// state fails can be suspended by anyone.    /// @dev Returns false on anything else, and never reverts: a revert would block every check    /// of the machine, suspending it with a proof included.    function verifyTeeState(address _teeId, bytes32 _stateVersion, bytes calldata _state) external view returns (bool) {        if (_stateVersion != STATE_VERSION || _state.length != 64) return false;        uint256 n = uint256(bytes32(_state[:32]));        uint256 a = uint256(bytes32(_state[32:]));        if (n > type(uint64).max || a > type(uint160).max) return false;        // casting is safe: both checked just above        // forge-lint: disable-next-line(unsafe-typecast)        uint64 nonce = uint64(n);        // forge-lint: disable-next-line(unsafe-typecast)        address admin = address(uint160(a));        // lo: how many nonces sent to teeId are at most nonce; a binary search keeps the gas        // bounded however far the TEE lags        uint64[] storage sent = sentNonces[_teeId];        uint256 lo;        uint256 hi = sent.length;        while (lo < hi) {            uint256 mid = (lo + hi) / 2;            if (sent[mid] > nonce) {                hi = mid;            } else {                lo = mid + 1;            }        }        if (nonce == 0) {            if (admin != address(0)) return false;        } else if (lo == 0 || sent[lo - 1] != nonce || adminSettings[nonce].admin != admin) {            return false;        }        // a validator moves the timestamp by seconds; the window is hours        // forge-lint: disable-next-line(block-timestamp)        return lo == sent.length || block.timestamp <= adminSettings[sent[lo]].sentAt + MAX_STATE_LAG;    }    function _open(uint64 _round) internal view returns (Round storage _r) {        _r = rounds[_round];        require(_r.status == Status.Open, RoundNotOpen(_round));    }    function _sendTo(address _teeId, bytes32 _opCommand, bytes memory _message) internal returns (bytes32) {        address[] memory teeIds = new address[](1);        teeIds[0] = _teeId;        return _send(teeIds, OP_TYPE_AUCTION, _opCommand, _message);    }}
```

</details>

## Run It on Coston2[​](#run-it-on-coston2 "Direct link to Run It on Coston2")

Follow Steps 1 through 3 of [Build Your First Extension](/fcc/guides/getting-started), then deploy and run `examples/direct`:

```
go test ./examples/direct/...fce conformance ./examples/directfce deploy -chain coston2 -account coston2-deployer ./examples/directfce add-version -chain coston2 -account coston2-deployer -test ./examples/directfce governance -chain coston2 -account coston2-deployer \  -signers "$(cast wallet address --account coston2-deployer)" -threshold 1 ./examples/directfce run -chain coston2 -account coston2-deployer ./examples/direct
```

The `fce run` command prints the machine's address and public URL. In a second terminal, set them as variables, along with an admin key. For this test, the admin is a separate keystore account:

```
TEE_ID=0x...           # "machine 0x... of extension ..." from fce runPROXY_URL=https://...  # the URL from the same linecast wallet import coston2-admin --interactiveADMIN=$(cast wallet address --account coston2-admin)
```

### Set the admin[​](#set-the-admin "Direct link to Set the admin")

```
fce send -chain coston2 -account coston2-deployer ./examples/direct \  "$(cast calldata 'setAdmin(address,address[])' "$ADMIN" "[$TEE_ID]")"
```

The `fce send` command takes a function signature with plain arguments, or raw calldata. For arrays and tuples, build the calldata with `cast calldata`.

The result echoes `abi.encode(1, admin)`. Until it arrives, `PROVISION` and `ROTATE` answer `error: no admin`.

### Encrypt and sign a secret[​](#encrypt-and-sign-a-secret "Direct link to Encrypt and sign a secret")

Fetch the TEE's public key from its proxy, then encrypt the secret with `fce encrypt`. `fce encrypt` reads from stdin, so the secret stays out of your shell history:

```
key=$(curl -s "$PROXY_URL/info" | jq -c .teeInfo.publicKey)read -rs SECRETciphertext=$(printf %s "$SECRET" | fce encrypt -pubkey "$key" -tee "$TEE_ID")
```

`-tee` refuses a key that doesn't belong to `$TEE_ID`.

Sign the `PROVISION` digest as the admin:

```
digest=$(cast keccak $(cast abi-encode "f(bytes32,bytes32,address,string,bytes)" \  $(cast format-bytes32-string SECRETS) $(cast format-bytes32-string PROVISION) \  "$TEE_ID" api-key "$ciphertext"))signature=$(cast wallet sign --account coston2-admin "$digest")
```

### Provision it[​](#provision-it "Direct link to Provision it")

```
message=$(printf '{"teeId":"%s","name":"api-key","ciphertext":"%s","signature":"%s"}' \  "$TEE_ID" "$ciphertext" "$signature" | xxd -p | tr -d '\n')fce direct -chain coston2 ./examples/direct SECRETS PROVISION "0x$message"
```

The result is `{"name":"api-key"}`. Post the same message again: it succeeds and changes nothing. To replace the secret, sign a `ROTATE` with a `counter` higher than the last one, using the `ROTATE` fields from the table above.

### Check the state[​](#check-the-state "Direct link to Check the state")

```
curl -s "$PROXY_URL/info" | jq .teeInfo.state
```

`stateVersion` is `SECRETS_STATE_V1`, right-padded to 32 bytes, and `state` is `abi.encode(1, admin)`. The contract verifies this value at each availability check.

Press **Ctrl-C** in the `fce run` terminal when you are done.

What's next

To learn more about FCC extensions, see:

-   [Wallets Extension](/fcc/guides/wallets-extension): let `tee-node` generate and hold the key itself, instead of provisioning it.
-   [External API Extension](/fcc/guides/external-api-extension): use a provisioned API key to call an authenticated web API.
-   The scaffold's [direct actions doc](https://github.com/flare-foundation/fce-go-scaffold/blob/main/docs/direct-actions.md) and [assumptions](https://github.com/flare-foundation/fce-go-scaffold/blob/main/docs/assumptions.md) cover the trust model in depth.
