Wallets Extension
This guide walks through the wallets example from the FCE Go scaffold.
The example signs EVM transactions with a wallet key that tee-node generates inside a TEE and never lets out.
A Flare contract decides who may use the wallet and numbers each transaction.
Every TEE that holds the key builds and signs the transaction, and posts it to its proxy, ready to broadcast.
The extension never sees the private key.
It asks tee-node to sign through the sign port, and only after it has checked that the key and the instruction match the wallet.
Start with Build Your First Extension for fce, the template, and the deploy flow.
For the TEE identity key and how wallet keys differ from it, see TEE public and private keys.
The key lives only in the memory of the TEEs that hold it. A machine that restarts loses it until the key is restored from a backup. Whoever holds the signer's key can have the TEE sign any transaction from the wallet. The TEE checks nothing about the transaction except its chain ID: there are no limits and no simulation.
The fce CLI cannot set up wallets yet, so you cannot run this example end to end with fce run alone.
You can build and test it locally with go test and fce conformance, and follow the onchain wallet setup by hand.
Protocol Managed Wallets, the built-in FCC application for XRPL and Bitcoin, is a separate system that is still in development.
Overview
| Op type | Op command | Channel | Payload | Result |
|---|---|---|---|---|
WALLETS | SIGN_TRANSACTION | Instruction | abi.encode(bytes32 walletId, uint64 keyId, uint64 nonce, Transaction tx) | The signed transaction: EIP-2718 bytes, ready for eth_sendRawTransaction |
The Transaction type is (uint256 chainId, address to, uint256 value, bytes data, uint64 gas, uint256 maxFeePerGas, uint256 maxPriorityFeePerGas).
That is an EIP-1559 transaction without a nonce (which the contract assigns) and with an empty access list.
The example does not create contracts, so to is always a recipient.
Wallets and Keys
An extension's wallets belong to wallet projects.
Each project has an owner, a key type, and a signing algorithm.
A wallet holds keys, and tee-node generates each key inside one TEE of the extension.
The extension never sees the keys, nor the instructions that create them.
It learns a wallet's ID and key ID only from its own payloads.
One key is one address, the same on every EVM chain. This example therefore only accepts wallets with exactly one key, since two keys would sign from two different addresses.
The onchain side spans IWalletProjectManager, IWalletManager, and IWalletKeyManager, all served by the FlareTeeManager diamond.
Who May Sign: The Contract
The wallet's project owner calls setSigner(walletId, signer).
Setting the zero address stops the signer.
The signer then calls signTransaction(walletId, transaction), paying at least quoteSignTransaction(walletId).
The contract refuses the call unless all of the following hold:
- The caller is the wallet's signer.
- The chain ID isn't 0.
- The wallet's project belongs to this extension, with an
EVMkey that signs withkeccak256-secp256k1-ecdsa. - The wallet is in production, not paused.
- The wallet has exactly one key, and a production TEE holds it.
The contract then sends the instruction to every production TEE that holds the key, with the wallet's cosigners attached. The fee is charged per TEE, so it rises when a restored key gains another holder.
View the contract code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { ExtensionBase } from "fcc-extension-scaffold/src/ExtensionBase.sol";
import { IInstructions } from "flare-periphery/src/coston2/IInstructions.sol";
import { TeeIdKeyIdPair } from "flare-periphery/src/coston2/ITeeIdKeyIdPair.sol";
import { IWalletKeyManager } from "flare-periphery/src/coston2/IWalletKeyManager.sol";
import { IWalletManager } from "flare-periphery/src/coston2/IWalletManager.sol";
import { IWalletProjectManager } from "flare-periphery/src/coston2/IWalletProjectManager.sol";
/// @title InstructionSender
/// @notice The wallets example's entrypoint contract: the TEEs holding a wallet's key sign EVM
/// transactions with it, for the one signer the wallet's project owner names. The contract numbers
/// each wallet's transactions per chain; each TEE posts the signed transaction to its proxy.
/// @dev NOTE: the deployer owns this contract, with 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 {
/// @notice The extension's op type, the Go side's OPTypeWallets.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant OP_TYPE_WALLETS = bytes32("WALLETS");
/// @notice SIGN_TRANSACTION, the Go side's OPCommandSignTransaction.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant OP_COMMAND_SIGN_TRANSACTION = bytes32("SIGN_TRANSACTION");
/// @notice The key type of a wallet that signs EVM transactions.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant KEY_TYPE_EVM = bytes32("EVM");
/// @notice The signing algorithm of a wallet that signs EVM transactions.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant SIGNING_ALGO_ECDSA = bytes32("keccak256-secp256k1-ecdsa");
/// @notice An EIP-1559 transaction, without its nonce: the contract numbers it.
struct Transaction {
uint256 chainId;
address to;
uint256 value;
bytes data;
uint64 gas;
uint256 maxFeePerGas;
uint256 maxPriorityFeePerGas;
}
/// @notice Who may have each wallet sign, as its project owner set it.
mapping(bytes32 walletId => address) public signers;
/// @notice The nonce of each wallet's next transaction on each chain, from 0: one key is one
/// address on every chain, and each chain counts its own nonce.
mapping(bytes32 walletId => mapping(uint256 chainId => uint64)) public nextNonce;
event SignerSet(bytes32 indexed walletId, address signer);
event TransactionSent(
bytes32 indexed instructionId, bytes32 indexed walletId, uint256 indexed chainId, uint64 nonce
);
error OnlyProjectOwner(bytes32 walletId);
error OnlySigner(bytes32 walletId);
error NotThisExtension(bytes32 walletId);
error NotAnEvmSigningKey(bytes32 walletId);
error WalletNotInProduction(bytes32 walletId);
error NotOneKey(bytes32 walletId, uint256 keys);
error ChainIdRequired();
error NotNumberedYet(uint64 nonce);
/// @param _flareTeeManager The FlareTeeManager diamond's address.
constructor(address _flareTeeManager) ExtensionBase(_flareTeeManager) { }
/// @notice Names the one address that may have `_walletId` sign; the zero address stops it.
/// Only the owner of the wallet's project may call it.
function setSigner(bytes32 _walletId, address _signer) external {
bytes32 projectId = IWalletManager(flareTeeManager).getWalletProjectId(_walletId);
require(msg.sender == IWalletProjectManager(flareTeeManager).getOwner(projectId), OnlyProjectOwner(_walletId));
signers[_walletId] = _signer;
emit SignerSet(_walletId, _signer);
}
/// @notice The price of signTransaction or replaceTransaction for `_walletId`: the fee is per TEE
/// holding its key, so it rises when a restored key gains a holder.
function quoteSignTransaction(bytes32 _walletId) external view returns (uint256) {
address[] memory teeIds = IWalletKeyManager(flareTeeManager).getReceivingTeeIds(_walletId);
return _protocolFee(OP_TYPE_WALLETS, OP_COMMAND_SIGN_TRANSACTION, teeIds) + projectFee;
}
/// @notice Has the TEEs holding `_walletId`'s key sign `_transaction` with the next nonce of that
/// wallet on its chain; each posts it, signed, to its proxy. Pay at least
/// quoteSignTransaction(_walletId); the contract keeps any excess.
/// @dev Only the wallet's signer may call it. A transaction that never lands blocks every later
/// one on its chain: replaceTransaction signs that nonce again.
function signTransaction(bytes32 _walletId, Transaction calldata _transaction)
external
payable
chargesFees
returns (bytes32 _instructionId, uint64 _nonce)
{
_nonce = nextNonce[_walletId][_transaction.chainId]++;
_instructionId = _sign(_walletId, _nonce, _transaction);
}
/// @notice Signs `_transaction` again at `_nonce`, one signTransaction already took on its
/// chain: to raise the fee of one still pending, or to replace one that never landed.
/// Pay at least quoteSignTransaction(_walletId); the contract keeps any excess.
function replaceTransaction(bytes32 _walletId, uint64 _nonce, Transaction calldata _transaction)
external
payable
chargesFees
returns (bytes32 _instructionId)
{
require(_nonce < nextNonce[_walletId][_transaction.chainId], NotNumberedYet(_nonce));
_instructionId = _sign(_walletId, _nonce, _transaction);
}
/// @dev Sends the transaction to every TEE in production holding the wallet's one key, with the
/// wallet's cosigners, which each TEE checks against the key's.
function _sign(bytes32 _walletId, uint64 _nonce, Transaction calldata _transaction) internal returns (bytes32 _id) {
require(msg.sender == signers[_walletId], OnlySigner(_walletId));
require(_transaction.chainId != 0, ChainIdRequired());
address manager = flareTeeManager;
bytes32 projectId = IWalletManager(manager).getWalletProjectId(_walletId);
require(IWalletProjectManager(manager).getExtensionId(projectId) == extensionId, NotThisExtension(_walletId));
require(
IWalletProjectManager(manager).getKeyType(projectId) == KEY_TYPE_EVM
&& IWalletProjectManager(manager).getSigningAlgo(projectId) == SIGNING_ALGO_ECDSA,
NotAnEvmSigningKey(_walletId)
);
// also refuses a paused wallet
require(
IWalletManager(manager).getWalletStatus(_walletId) == IWalletManager.WalletStatus.PRODUCTION,
WalletNotInProduction(_walletId)
);
// each key is its own address: two keys would sign from two addresses
(, uint64[] memory keyIds,) = IWalletKeyManager(manager).getWalletKeysInfo(_walletId);
require(keyIds.length == 1, NotOneKey(_walletId, keyIds.length));
// reverts ThresholdNotMet when no TEE holding the key is in production
TeeIdKeyIdPair[] memory pairs = IWalletKeyManager(manager).receivingTeesAndKeys(_walletId);
address[] memory teeIds = new address[](pairs.length);
for (uint256 i; i < pairs.length; ++i) {
teeIds[i] = pairs[i].teeId;
}
(address[] memory cosigners, uint64 threshold) =
IWalletManager(manager).getWalletCosignersAndThreshold(_walletId);
_id = _send(
teeIds,
IInstructions.TeeInstructionParams({
opType: OP_TYPE_WALLETS,
opCommand: OP_COMMAND_SIGN_TRANSACTION,
message: abi.encode(_walletId, keyIds[0], _nonce, _transaction),
cosigners: cosigners,
cosignersThreshold: threshold,
claimBackAddress: msg.sender
})
);
emit TransactionSent(_id, _walletId, _transaction.chainId, _nonce);
}
}
Checking in the TEE
Inside the TEE, tee-node signs with any key the TEE holds, regardless of the request.
It only checks that the instruction's own cosigners signed it.
So the extension checks the rest itself, using the key's info from the sign port (tee.KeyInfo):
- The key is an
EVMkey that signs withkeccak256-secp256k1-ecdsa. - The instruction's cosigners and threshold match the wallet's, compared the same way
tee-nodecompares them for its own wallet operations.
Then the extension builds the EIP-1559 transaction from the fields and has the key sign it (tee.SignWallet).
It checks that the signature recovers to the key's address before returning the signed transaction.
The key only ever signs a transaction the extension built, never bytes a caller chose.
View the handler code
package app
import (
"context"
"errors"
"fmt"
"math/big"
"slices"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
"github.com/flare-foundation/fce-go-scaffold/pkg/extension"
"github.com/flare-foundation/fce-go-scaffold/pkg/node"
"github.com/flare-foundation/fce-go-scaffold/pkg/payload"
"github.com/flare-foundation/go-flare-common/pkg/tee/instruction"
"github.com/flare-foundation/go-flare-common/pkg/tee/structs/wallet"
)
// Refusals of SIGN_TRANSACTION.
var (
errNoChainID = extension.PublicError("chain id required", nil)
errNoKey = extension.PublicError("wallet key not on this TEE", nil)
errNotEVM = extension.PublicError("not an EVM signing key", nil)
errCosigners = extension.PublicError("cosigners differ from the wallet's", nil)
errUnreadable = errors.New("unreadable public key")
errOtherKey = errors.New("signed by another key")
)
// The key type and signing algorithm of an EVM key that signs transactions,
// right-padded as the chain stores them.
var (
keyTypeEVM = pad32("EVM")
algoECDSA = pad32("keccak256-secp256k1-ecdsa")
)
// txType is the contract's Transaction struct.
var txType = func() abi.Type {
t, err := abi.NewType("tuple", "", []abi.ArgumentMarshaling{
{Name: "chainId", Type: "uint256"},
{Name: "to", Type: "address"},
{Name: "value", Type: "uint256"},
{Name: "data", Type: "bytes"},
{Name: "gas", Type: "uint64"},
{Name: "maxFeePerGas", Type: "uint256"},
{Name: "maxPriorityFeePerGas", Type: "uint256"},
})
if err != nil {
panic(err)
}
return t
}()
// signArgs is abi.encode(walletId, keyId, nonce, tx), as the contract builds it.
var signArgs = abi.Arguments{
{Name: "walletId", Type: abiType("bytes32")},
{Name: "keyId", Type: abiType("uint64")},
{Name: "nonce", Type: abiType("uint64")},
{Name: "tx", Type: txType},
}
type signMessage struct {
WalletID common.Hash `abi:"walletId"`
KeyID uint64 `abi:"keyId"`
Nonce uint64 `abi:"nonce"`
Tx txFields `abi:"tx"`
}
// txFields is the contract's Transaction struct; the fields keep its order.
type txFields struct {
ChainID *big.Int `abi:"chainId"`
To common.Address `abi:"to"`
Value *big.Int `abi:"value"`
Data []byte `abi:"data"`
Gas uint64 `abi:"gas"`
MaxFeePerGas *big.Int `abi:"maxFeePerGas"`
MaxPriorityFeePerGas *big.Int `abi:"maxPriorityFeePerGas"`
}
// signTransaction signs an EIP-1559 transaction with the wallet key the
// contract names, and answers it raw, ready for eth_sendRawTransaction. It signs
// only with an EVM key, for an instruction whose cosigners are the wallet's, and
// a transaction with a chain id.
func (w *wallets) signTransaction(ctx context.Context, i *instruction.DataFixed) ([]byte, extension.Run, error) {
var p signMessage
if err := payload.DecodeABI(signArgs, i.OriginalMessage, &p); err != nil {
return nil, nil, extension.PublicError("invalid payload", err)
}
if p.Tx.ChainID.Sign() == 0 {
return nil, nil, errNoChainID
}
info, err := w.keys.KeyInfo(ctx, p.WalletID, p.KeyID)
switch {
case errors.Is(err, node.ErrNotFound):
return nil, nil, errNoKey
case err != nil:
return nil, nil, extension.PublicError("can't read the wallet key", err)
}
if info.KeyType != keyTypeEVM || info.SigningAlgo != algoECDSA {
return nil, nil, errNotEVM
}
// tee-node checks only that an instruction's own cosigners signed it
if !sameCosigners(i, info.ConfigConstants) {
return nil, nil, errCosigners
}
pub, err := crypto.UnmarshalPubkey(append([]byte{4}, info.PublicKey...))
if err != nil {
return nil, nil, extension.PublicError("can't read the wallet key", errUnreadable)
}
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: p.Tx.ChainID,
Nonce: p.Nonce,
GasTipCap: p.Tx.MaxPriorityFeePerGas,
GasFeeCap: p.Tx.MaxFeePerGas,
Gas: p.Tx.Gas,
To: &p.Tx.To,
Value: p.Tx.Value,
Data: p.Tx.Data,
})
raw, err := w.sign(ctx, p.WalletID, p.KeyID, crypto.PubkeyToAddress(*pub), tx)
if err != nil {
return nil, nil, extension.PublicError("can't sign", err)
}
return raw, nil, nil
}
// sign has the wallet key sign tx, and returns it signed, as EIP-2718 bytes,
// once its sender checks out as from.
func (w *wallets) sign(ctx context.Context, walletID common.Hash, keyID uint64, from common.Address, tx *types.Transaction) ([]byte, error) {
signer := types.NewLondonSigner(tx.ChainId())
preimage, err := signingPreimage(tx)
if err != nil {
return nil, err
}
// the wallet key signs keccak256(preimage), which must be the hash chains check
if crypto.Keccak256Hash(preimage) != signer.Hash(tx) {
return nil, errors.New("preimage doesn't match the signing hash")
}
sig, err := w.keys.SignWallet(ctx, walletID, keyID, preimage)
if err != nil {
return nil, err
}
signed, err := tx.WithSignature(signer, sig)
if err != nil {
return nil, fmt.Errorf("adding the signature: %w", err)
}
if sender, err := types.Sender(signer, signed); err != nil || sender != from {
return nil, errOtherKey
}
return signed.MarshalBinary()
}
// signingPreimage is what an EIP-1559 transaction's signature covers:
// 0x02 || rlp([chainId, nonce, tip, feeCap, gas, to, value, data, accessList]).
func signingPreimage(tx *types.Transaction) ([]byte, error) {
b, err := rlp.EncodeToBytes([]any{
tx.ChainId(), tx.Nonce(), tx.GasTipCap(), tx.GasFeeCap(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList(),
})
if err != nil {
return nil, fmt.Errorf("encoding the transaction: %w", err)
}
return append([]byte{types.DynamicFeeTxType}, b...), nil
}
// sameCosigners reports whether the instruction carries the wallet's cosigners
// and threshold, compared as tee-node compares them for its own wallet ops.
func sameCosigners(i *instruction.DataFixed, c wallet.IWalletKeyManagerKeyConfigConstants) bool {
if len(i.Cosigners) != len(c.Cosigners) || i.CosignersThreshold != c.CosignersThreshold {
return false
}
for _, a := range c.Cosigners {
if !slices.Contains(i.Cosigners, a) {
return false
}
}
return true
}
func abiType(t string) abi.Type {
typ, err := abi.NewType(t, "", nil)
if err != nil {
panic(err)
}
return typ
}
func pad32(s string) (h [32]byte) {
copy(h[:], s)
return h
}
The handler's refusals appear as error: <text> in the result log:
| Text | When |
|---|---|
invalid payload | The payload isn't exactly the contract's encoding |
chain id required | chainId is 0 |
wallet key not on this TEE | The TEE doesn't hold that key |
not an EVM signing key | The key has another type or algorithm, such as VRF |
cosigners differ from the wallet's | The instruction's cosigners or threshold don't match the wallet's |
can't read the wallet key, can't sign | tee-node failed, or the signature recovers to another address |
Nonces and Replacement
The contract numbers each wallet's transactions per chain, starting at 0.
Reading nextNonce(walletId, chainId) returns the next nonce.
Signing is deterministic: if an instruction is delivered again, it produces the same signed bytes, and the target chain accepts that transaction only once. So the extension needs no replay protection and keeps no state.
A numbered transaction that never lands blocks every later transaction on that chain.
This can happen because of a lost instruction, a TEE that is down, a fee that is too low, or a balance that is too small.
Calling replaceTransaction(walletId, nonce, transaction) signs an already-numbered nonce again with new fields, for example to raise the fee or replace a transaction that never landed.
Both signed transactions stay valid and public until one of them lands.
Broadcasting
The signed transaction appears on each key holder's proxy at GET /action/result/<instructionId>.
Anyone can broadcast it with eth_sendRawTransaction or cast publish.
The wallet's address pays the gas, so fund it on the target chain first.
The address comes from the key: read it with getWalletKeyPublicKey, or recover it from any transaction the key signed.
Setting Up a Wallet
Until fce supports wallets, these are the onchain steps on the FlareTeeManager diamond:
- As the extension owner, once:
addAllowedTeeWalletProjectOwners(extensionId, owners)andaddSupportedKeyTypes(extensionId, ["EVM"]). - As an allowed owner:
createProject(extensionId, "EVM", "keccak256-secp256k1-ecdsa"), thencreateWallet(projectId). - Call
setAdmins(walletId, publicKeys, threshold), thenconfirmAdmin(walletId)from each admin's address. Optionally callsetCosignersandconfirmCosigner. Then callcloseWalletInitialization(walletId). - Call
setMultisigThreshold(walletId, 1), thenaddKey(teeId, walletId, claimBack), paying its fee. In that TEE,tee-nodegenerates the key. - Read the key's existence proof, signed by the TEE, from its proxy, and call
confirmKey(proof, signature). - Call
enableWallet(walletId): the wallet goes into production, and no more keys can be added. - On the example contract:
setSigner(walletId, signer).
Restarts and Backups
A TEE that restarts comes back as a new TEE, without its wallet keys.
Each key is backed up by tee-proxy in shares encrypted to the wallet's admins and to the data providers.
A restore puts the key on another TEE, either from the shares (which need the admins and the data providers) or directly from a TEE that still holds it.
The project owner, or its backup manager, then confirms the new holder with confirmKey.
Until then, no instruction reaches the new holder.
With no holder in production, signTransaction reverts with ThresholdNotMet.
A key that cannot be restored is lost.
Since you can't add a key to an enabled wallet, the only way out is a new wallet with a new address.
Test Locally
go test ./examples/wallets/...
fce conformance ./examples/wallets
The fake sign port that the tests and fce conformance use holds one wallet key: wallet keccak256("fakenode wallet"), key 0, no cosigners.
That key is Anvil's second test account so that you can broadcast the first fixture's transaction on a local Anvil node:
anvil &
cast publish --rpc-url http://127.0.0.1:8545 "$(jq -r .result.data examples/wallets/conformance/1-sign-transfer.json)"
The forge tests send the fixtures' fields through the contract and check that it builds exactly the fixtures' payloads, so the contract and the handler cannot drift apart.
To learn more about FCC extensions, see:
- TEE public and private keys: the difference between the TEE identity key and wallet keys.
- Data providers and cosigners: how cosigners add an authorization layer on top of data provider signatures.
- The scaffold's contracts guide on sending one instruction to several TEEs.