Agent documentation index: llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
Skip to main content

External API Extension

This guide walks through the external-api example from the FCE Go scaffold. The extension fetches a price from three public APIs inside the TEE and posts each source's answer as it arrives. It then signs the median with the TEE key, and the contract verifies that signature before storing the price.

New to FCC extensions?

Start with Build Your First Extension. It covers installing fce, the template, and the deploy and run flow that this guide reuses.

It shows three patterns that most data-fetching extensions need:

  • Calling outside services over TLS from a TEE whose operator controls the network.
  • Long-running work: answering past tee-node's 2-second limit, with partial results along the way.
  • Putting a TEE's answer onchain: signing a message of your own and having the contract check it.
An example, not a production oracle

One TEE answers each request, and its operator sees the price first and can withhold it. A stored price may already be 10 minutes old by the time the contract stores it. For production price feeds on Flare, use the FTSO.

Overview​

Here is a summary of the extension's operations:

Op typeOp commandChannelPayloadPartial resultsFinal result
PRICESGET_PRICEInstructionabi.encode(string pair)abi.encode(string source, uint256 price)abi.encode(string pair, uint256 price, uint8 decimals, uint8 sources, bytes signature)
PRICESGET_PRICE_DIRECTDirectJSON {"pair"}JSON {"source", "price"}JSON {"pair", "price", "decimals", "sources"} (unsigned)

The supported pairs are BTC/USD, ETH/USD, and FLR/USD. Prices are integers with 8 decimals. The sources field counts how many APIs answered.

The flow for GET_PRICE:

Statuses​

Every result has a status from 0 to 255 and a public log. GET_PRICE and GET_PRICE_DIRECT use the same numbers. tee-proxy keeps one result per action. Status 0 and status 1 are final and replace whatever is stored, so status 1 replaces status 6. A status of 2 or higher is replaced only by a higher status or by a final one.

StatusLogMeaning
0error: <text>Failed, and final. data is empty.
1okSucceeded, and final. data is the price to submit.
2pendingAccepted. The fetch continues in the background.
3set by the nodePosted by tee-node when POST /action takes longer than 2 seconds.
4–255partialOne partial per source that answered, in arrival order. This example posts 4, then 5, then 6.

Status 0 before any fetch means unknown pair, invalid payload, or, on GET_PRICE only, instruction already answered. Fewer than two sources answering ends the job as status 0 with error: too few sources answered. A partial's data is that source's name and price. Status 1's data is the signed median for GET_PRICE, and the unsigned JSON median for GET_PRICE_DIRECT. If the TEE restarts after status 2, the proxy keeps the last status, so time it out yourself.

Trusting the Sources​

The sources are fixed in the code, so they are part of the attested image. Anyone who rebuilds the image can see which APIs the TEE trusts, and the operator cannot point it anywhere else.

View sources.go
examples/external-api/internal/app/sources.go
package app

import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"regexp"
"strings"
"time"
)

// pairs are the pairs the extension prices; each source names them its own way.
var pairs = []string{"BTC/USD", "ETH/USD", "FLR/USD"}

// sources are the APIs the extension trusts. They are constants of the code, so
// part of the attested image: the operator can't point the TEE elsewhere. The
// host is reached over TLS, verified against the CA bundle in the image.
var sources = []source{
{
name: "coinbase",
urls: urls("https://api.coinbase.com/v2/prices/%s/spot", "BTC-USD", "ETH-USD", "FLR-USD"),
price: coinbasePrice,
},
{
name: "kraken",
urls: urls("https://api.kraken.com/0/public/Ticker?pair=%s", "XBTUSD", "ETHUSD", "FLRUSD"),
price: krakenPrice,
},
{
name: "bitstamp",
urls: urls("https://www.bitstamp.net/api/v2/ticker/%s/", "btcusd", "ethusd", "flrusd"),
price: bitstampPrice,
},
}

const (
// decimals is the precision prices are given in: 8, as USD feeds commonly use
decimals = 8
// sourceTimeout bounds each source's answer; the job runs in the background, past the node's 2 s
sourceTimeout = 5 * time.Second
// maxBody caps a source's answer: it is untrusted input
maxBody = 64 << 10
)

// source is one API: its URL for each pair, and how to read the price from its answer.
type source struct {
name string
urls map[string]string
price func(body []byte) (string, error) // a decimal string
}

func urls(format string, symbols ...string) map[string]string {
m := make(map[string]string, len(pairs))
for i, p := range pairs {
m[p] = fmt.Sprintf(format, symbols[i])
}
return m
}

// newClient returns the sources' client over base. It follows no redirect, so
// a source can't send the TEE to another host, or off TLS.
func newClient(base http.RoundTripper) *http.Client {
return &http.Client{
Transport: base,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}

// fetch returns src's price for pair, in decimals.
func fetch(ctx context.Context, client *http.Client, src source, pair string) (*big.Int, error) {
ctx, cancel := context.WithTimeout(ctx, sourceTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, src.urls[pair], nil)
if err != nil {
return nil, err
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close() //nolint:errcheck // the body is read in full or dropped; nothing to report
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status %d", res.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(res.Body, maxBody+1))
if err != nil {
return nil, err
}
if len(body) > maxBody {
return nil, errors.New("answer over the limit")
}
s, err := src.price(body)
if err != nil {
return nil, err
}
return parsePrice(s)
}

var decimalRE = regexp.MustCompile(`^[0-9]{1,20}(\.[0-9]{1,30})?$`)

// parsePrice reads a positive decimal string, as the sources write prices, in
// decimals; digits past them are dropped.
func parsePrice(s string) (*big.Int, error) {
if !decimalRE.MatchString(s) {
return nil, fmt.Errorf("price %q is not a decimal", s)
}
whole, frac, _ := strings.Cut(s, ".")
frac = (frac + strings.Repeat("0", decimals))[:decimals]
n, ok := new(big.Int).SetString(whole+frac, 10)
if !ok || n.Sign() <= 0 {
return nil, fmt.Errorf("price %q is not positive", s)
}
return n, nil
}

// Each reader decodes leniently: the APIs add fields over time.

func coinbasePrice(body []byte) (string, error) {
var v struct {
Data struct {
Amount string `json:"amount"`
} `json:"data"`
}
err := json.Unmarshal(body, &v)
return v.Data.Amount, err
}

func krakenPrice(body []byte) (string, error) {
var v struct {
Error []string `json:"error"`
Result map[string]struct {
Last []string `json:"c"` // the last trade: price, volume
} `json:"result"`
}
if err := json.Unmarshal(body, &v); err != nil {
return "", err
}
if len(v.Error) > 0 || len(v.Result) != 1 {
return "", errors.New("not one ticker")
}
for _, t := range v.Result {
if len(t.Last) > 0 {
return t.Last[0], nil
}
}
return "", errors.New("no last trade")
}

func bitstampPrice(body []byte) (string, error) {
var v struct {
Last string `json:"last"`
}
err := json.Unmarshal(body, &v)
return v.Last, err
}

The operator runs the machine and its network, so the extension treats every answer as hostile until it has checked it:

  • It uses only https URLs, verified against the CA bundle in the attested image.
  • It follows no redirects, so a source cannot send the TEE to another host or off TLS.
  • It caps each answer at 64 KiB and requires a positive decimal price.
  • If a source fails, the extension leaves it out and keeps the error internal, because logs are public.
  • The median needs two of the three sources. One of the three may be down or wrong.
  • The caller picks a pair from a fixed list, so caller input never reaches a URL.

Long-Running Results​

Three HTTP requests can take longer than tee-node's 2 seconds, so the handler returns a Run and the action is status 2 at once. The Run fetches in the background.

The long-running mode posts results through tee-node's sign port, so main.go passes extension.WithSignPort. It also passes a node.Client that the handler uses to sign with the TEE key:

View main.go
examples/external-api/cmd/extension/main.go
// Command extension serves tee-node's calls to the extension until it is stopped.
package main

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"

"github.com/flare-foundation/fce-go-scaffold/examples/external-api/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()

// long-running results are posted through the sign port, and the prices signed there
srv := extension.New(extension.WithSignPort(env.SignPort))
app.Register(srv, node.New(env.SignPort))
return srv.ListenAndServe(ctx, env.ExtensionPort)
}
View app.go
examples/external-api/internal/app/app.go
// Package app is the external-api example: a price, as the median of several
// public APIs, fetched over TLS in the background and posted as it arrives.
// The instruction's final answer is signed with the TEE key, for the contract.
package app

import (
"context"
"net/http"

"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 (
// OPTypePrices names the extension.
OPTypePrices op.Type = "PRICES"
// OPCommandGetPrice arrives as an instruction, sent through the contract; ABI in and out.
OPCommandGetPrice op.Command = "GET_PRICE"
// OPCommandGetPriceDirect arrives as a direct action, posted to the proxy; JSON in and out.
OPCommandGetPriceDirect op.Command = "GET_PRICE_DIRECT"
)

// Register registers the extension's handlers on s, fetching from the sources
// below over http.DefaultTransport and signing with signer.
func Register(s *extension.Server, signer Signer) {
p := newPrices(newClient(http.DefaultTransport), sources, signer)
s.RegisterInstructionHandler(OPTypePrices, OPCommandGetPrice, p.getPrice)
s.RegisterDirectHandler(OPTypePrices, OPCommandGetPriceDirect, p.getPriceDirect)
}

// Signer signs with the TEE key, as *node.Client does through the sign port.
type Signer interface {
SignTEE(ctx context.Context, msg []byte) ([]byte, error)
}

func newPrices(client *http.Client, srcs []source, signer Signer) *prices {
return &prices{client: client, sources: srcs, signer: signer, answered: map[common.Hash]bool{}}
}

Inside the Run, each prog.Post publishes the next partial, from status 4 up, in the order the sources answer. The bytes the Run returns become the final result: status 1, or status 0 with error: too few sources answered.

View getprice.go
examples/external-api/internal/app/getprice.go
package app

import (
"context"
"math/big"
"slices"

"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"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/go-flare-common/pkg/tee/instruction"
)

var (
// getPriceArgs is abi.encode(pair), as the contract's getPrice builds it.
getPriceArgs = abi.Arguments{{Name: "pair", Type: abiType("string")}}
// partialArgs is a partial result: abi.encode(source, price).
partialArgs = abi.Arguments{{Name: "source", Type: abiType("string")}, {Name: "price", Type: abiType("uint256")}}
// priceArgs is a price, as its signed message commits to it: abi.encode(pair, price, decimals, sources).
priceArgs = abi.Arguments{
{Name: "pair", Type: abiType("string")},
{Name: "price", Type: abiType("uint256")},
{Name: "decimals", Type: abiType("uint8")},
{Name: "sources", Type: abiType("uint8")},
}
// finalArgs is the final result: abi.encode(pair, price, decimals, sources, signature),
// what the contract's submitPrice takes.
finalArgs = append(slices.Clone(priceArgs), abi.Argument{Name: "signature", Type: abiType("bytes")})
// messageArgs is what the TEE signs: abi.encode(priceTag, instructionId, keccak256(price)).
messageArgs = abi.Arguments{
{Name: "tag", Type: abiType("bytes32")},
{Name: "instructionId", Type: abiType("bytes32")},
{Name: "priceHash", Type: abiType("bytes32")},
}
)

// priceTag opens every signed price, the contract's PRICE_TAG: it keeps the
// signature from meaning anything else, such as one of tee-node's own.
var priceTag = func() (h common.Hash) {
copy(h[:], "PRICES_PRICE_V1")
return h
}()

// getPrice answers status 2 at once and fetches in the background: three APIs
// take longer than the node's 2 s. Each source's price is posted as a partial
// result as it arrives, then the median as the final one, ABI-encoded and
// signed for the contract. Each instruction is answered once.
func (p *prices) getPrice(_ context.Context, i *instruction.DataFixed) ([]byte, extension.Run, error) {
var pair string
if err := payload.DecodeABI(getPriceArgs, i.OriginalMessage, &pair); err != nil {
return nil, nil, extension.PublicError("invalid payload", err)
}
if !slices.Contains(pairs, pair) {
return nil, nil, errUnknownPair
}
if !p.answer(i.InstructionID) {
return nil, nil, errAnswered
}

id := i.InstructionID
return nil, func(ctx context.Context, prog *extension.Progress) ([]byte, error) {
return p.quoteABI(ctx, id, pair, prog.Post)
}, nil
}

// quoteABI posts each source's price through post, and returns the median,
// ABI-encoded and signed for instruction id.
func (p *prices) quoteABI(ctx context.Context, id common.Hash, pair string, post func(context.Context, []byte) error) ([]byte, error) {
price, n, err := p.median(ctx, pair, func(src string, price *big.Int) {
if b, err := partialArgs.Pack(src, price); err == nil {
_ = post(ctx, b) // the library logs a dropped partial; the final still follows
}
})
if err != nil {
return nil, err
}
sources := uint8(n) //nolint:gosec // n is at most len(sources)

msg, err := priceMessage(id, pair, price, sources)
if err != nil {
return nil, extension.PublicError("encoding the result", err)
}
sig, err := p.signer.SignTEE(ctx, msg)
if err != nil {
return nil, extension.PublicError("signing the result", err)
}
sig[crypto.RecoveryIDOffset] += 27 // the sign port gives V 0 or 1; ecrecover wants 27 or 28

out, err := finalArgs.Pack(pair, price, uint8(decimals), sources, sig)
if err != nil {
return nil, extension.PublicError("encoding the result", err)
}
return out, nil
}

// priceMessage is what the TEE signs for a price: bound to the instruction
// that asked for it, which the contract accepts once.
func priceMessage(id common.Hash, pair string, price *big.Int, sources uint8) ([]byte, error) {
b, err := priceArgs.Pack(pair, price, uint8(decimals), sources)
if err != nil {
return nil, err
}
return messageArgs.Pack(priceTag, id, crypto.Keccak256Hash(b))
}

func abiType(t string) abi.Type {
typ, err := abi.NewType(t, "", nil)
if err != nil {
panic(err)
}
return typ
}

Points to note:

  • Bound the job yourself. The library limits neither how long a job runs nor how many run at once. The example bounds each source with a 5-second timeout.
  • Time out a result that stays below status 1. If the TEE restarts mid-job, it posts no final status, and the proxy keeps the last one.
  • Answer each instruction once. getPrice refuses an instruction ID it has already answered. Otherwise, an operator could deliver the same instruction again, fetch again, and submit whichever price it prefers.

Putting the Price Onchain​

The TEE signs its final answer through the sign port (SignTEE, EIP-191 over the message's keccak256):

abi.encode(bytes32 "PRICES_PRICE_V1", bytes32 instructionId, keccak256(abi.encode(pair, price, decimals, sources)))
  • PRICES_PRICE_V1 is a tag of the extension's own. It keeps this signature from meaning anything else, such as one of tee-node's own signatures.
  • instructionId binds the signature to one request, on one chain, at one contract. The ID arrives with the instruction, signed by the data providers, and the contract accepts it only once. So the extension doesn't need a chain ID.
  • V must be 27 or 28. The signature's last byte, V, tells ecrecover which of the two possible keys signed. The sign port returns that byte as 0 or 1. ecrecover only accepts 27 or 28, so the extension adds 27 before it packs the signature into the result.
Never sign bytes a user chooses

SignTEE signs in the same domain as tee-node's own signatures. Always build the message yourself in a format only your extension uses, and encode it with abi.encode, never by concatenating variable-length fields.

The contract records each request in getPrice, then verifies the result in submitPrice:

View InstructionSender.sol
examples/external-api/contracts/src/InstructionSender.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import { ExtensionBase } from "fcc-extension-scaffold/src/ExtensionBase.sol";

/// @title InstructionSender
/// @notice The external-api example's entrypoint contract: anyone may ask for a price, which the
/// TEE fetches from several public APIs and answers as their median, signed; anyone may then
/// submit the signed answer, and the contract keeps the latest price per pair.
/// @dev WARNING: an example, not a production oracle. One TEE answers each request, and its
/// operator sees the price first and may withhold it. A price may be up to MAX_PRICE_DELAY old
/// when stored, and ages from there: consumers check requestedAt.
/// 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 OPTypePrices.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant OP_TYPE_PRICES = bytes32("PRICES");

/// @notice GET_PRICE, the Go side's OPCommandGetPrice.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant OP_COMMAND_GET_PRICE = bytes32("GET_PRICE");

/// @notice The tag opening every price the TEE signs, the Go side's priceTag: it keeps the
/// signature from meaning anything else.
// forge-lint: disable-next-line(unsafe-typecast)
bytes32 public constant PRICE_TAG = bytes32("PRICES_PRICE_V1");

/// @notice How long after its request a price may be submitted, in chain time. The TEE fetched
/// it between the two blocks, so it bounds how long the operator can hold a request back.
uint256 public constant MAX_PRICE_DELAY = 10 minutes;

/// @notice A getPrice waiting for its signed answer.
struct Request {
bytes32 pairHash;
address teeId;
uint64 requestedAt;
}

/// @notice A pair's latest price: an integer with `decimals` decimals, the median of `sources`
/// sources, requested at `requestedAt` and fetched at most MAX_PRICE_DELAY later.
struct Price {
uint256 price;
uint8 decimals;
uint8 sources;
uint64 requestedAt;
}

/// @notice The requests waiting for an answer, by instruction id.
mapping(bytes32 instructionId => Request) public requests;

mapping(bytes32 pairHash => Price) internal latest;

event PriceRequested(bytes32 indexed instructionId, string pair, address teeId);
event PriceSubmitted(bytes32 indexed instructionId, string pair, uint256 price, uint64 requestedAt);

error UnknownRequest(bytes32 instructionId);
error TooLate(bytes32 instructionId, uint256 deadline);
error WrongPair(bytes32 instructionId);
error WrongTee(address signer, address teeId);

/// @param _flareTeeManager The FlareTeeManager diamond's address.
constructor(address _flareTeeManager) ExtensionBase(_flareTeeManager) { }

/// @notice Asks for `_pair`'s price, such as "BTC/USD". Pay at least
/// quoteFee(OP_TYPE_PRICES, OP_COMMAND_GET_PRICE); the contract keeps any excess.
/// @dev One random TEE answers, on its proxy: a partial result per source, then the signed
/// median, for submitPrice. It refuses a pair it doesn't price; the contract leaves that check
/// to it.
function getPrice(string calldata _pair) external payable chargesFees returns (bytes32 _instructionId) {
address[] memory teeIds = _randomTee();
_instructionId = _send(teeIds, OP_TYPE_PRICES, OP_COMMAND_GET_PRICE, abi.encode(_pair));
requests[_instructionId] = Request(keccak256(bytes(_pair)), teeIds[0], uint64(block.timestamp));
emit PriceRequested(_instructionId, _pair, teeIds[0]);
}

/// @notice Stores a signed price: `_result` is the data of the TEE's final answer to
/// `_instructionId`, abi.encode(pair, price, decimals, sources, signature). Anyone may submit
/// it, once, within MAX_PRICE_DELAY of the request; the TEE's signature is the proof.
/// @dev An answer to an older request than the stored price's is accepted but not stored.
function submitPrice(bytes32 _instructionId, bytes calldata _result) external {
Request memory r = requests[_instructionId];
require(r.teeId != address(0), UnknownRequest(_instructionId));
uint256 deadline = r.requestedAt + MAX_PRICE_DELAY;
// a validator moves the timestamp by seconds; the window is minutes
// forge-lint: disable-next-line(block-timestamp)
require(block.timestamp <= deadline, TooLate(_instructionId, deadline));

(string memory pair, uint256 price, uint8 decimals, uint8 sources, bytes memory signature) =
abi.decode(_result, (string, uint256, uint8, uint8, bytes));
require(keccak256(bytes(pair)) == r.pairHash, WrongPair(_instructionId));
address signer = _teeSigner(priceDigest(_instructionId, pair, price, decimals, sources), signature);
require(signer == r.teeId, WrongTee(signer, r.teeId));

delete requests[_instructionId];
if (r.requestedAt >= latest[r.pairHash].requestedAt) {
latest[r.pairHash] = Price(price, decimals, sources, r.requestedAt);
}
emit PriceSubmitted(_instructionId, pair, price, r.requestedAt);
}

/// @notice `_pair`'s latest stored price; all zero if none. Check requestedAt: the price is
/// as old as it says, and older by up to MAX_PRICE_DELAY.
function latestPrice(string calldata _pair) external view returns (Price memory) {
return latest[keccak256(bytes(_pair))];
}

/// @notice The keccak256 of the message the TEE signs for a price:
/// abi.encode(PRICE_TAG, instructionId, keccak256(abi.encode(pair, price, decimals, sources))).
function priceDigest(bytes32 _instructionId, string memory _pair, uint256 _price, uint8 _decimals, uint8 _sources)
public
pure
returns (bytes32)
{
return
keccak256(abi.encode(PRICE_TAG, _instructionId, keccak256(abi.encode(_pair, _price, _decimals, _sources))));
}
}

submitPrice stores the price only if all of the following hold:

  • The contract requested that instruction, and nobody has submitted an answer to it yet.
  • The submission comes no more than MAX_PRICE_DELAY (10 minutes) after the request, by block time.
  • The pair is the one requested.
  • _teeSigner recovers the TEE the request went to, and that TEE is a production machine of this extension. The extension must also not be emergency-paused.

_teeSigner comes from ExtensionBase. It recovers the signer and asks FlareTeeManager whether that signer is a production TEE of this extension.

Nothing reaches the contract on its own. Someone has to read the result from the proxy and call submitPrice: the caller, a keeper, or any other account, since the TEE signature is the proof.

Run It on Coston2​

Follow Steps 1 through 3 of Build Your First Extension to install fce, fork the scaffold, and import a keystore account. Then test and deploy examples/external-api:

go test ./examples/external-api/...
fce conformance ./examples/external-api

fce deploy -chain coston2 -account coston2-deployer ./examples/external-api
fce add-version -chain coston2 -account coston2-deployer -test ./examples/external-api
fce governance -chain coston2 -account coston2-deployer \
-signers "$(cast wallet address --account coston2-deployer)" -threshold 1 ./examples/external-api
fce run -chain coston2 -account coston2-deployer ./examples/external-api

From a second terminal, request a price:

fce send -chain coston2 -account coston2-deployer ./examples/external-api 'getPrice(string)' 'BTC/USD'

fce send prints the instruction ID, then each status as the proxy stores it: 2, then a partial for each source, then status 1 and its signed data. Submit that data to the contract within 10 minutes, then read the stored price:

SENDER=$(jq -r .instructionSender examples/external-api/deployments/coston2.json)
RPC=https://coston2-api.flare.network/ext/C/rpc

cast send --rpc-url "$RPC" --account coston2-deployer "$SENDER" \
'submitPrice(bytes32,bytes)' <instructionId> <data>
cast call --rpc-url "$RPC" "$SENDER" 'latestPrice(string)((uint256,uint8,uint8,uint64))' 'BTC/USD'

The direct variant needs no fee and returns an unsigned answer:

fce direct -chain coston2 ./examples/external-api PRICES GET_PRICE_DIRECT \
0x$(printf '{"pair":"ETH/USD"}' | xxd -p | tr -d '\n')

Its answer is unsigned because tee-proxy picks a direct action's ID. A signed direct answer could pass as an instruction's answer.

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

Limits​

  • Latency: the instruction waits for data provider signatures, the sources take up to 5 seconds, and someone has to submit the result. This takes seconds even when everything goes well.
  • Freshness: the bound is in chain time only. The TEE fetched the price at some point between the request block and the submission block, which are at most 10 minutes apart. Check requestedAt.
  • One TEE: each request goes to one random TEE, whose operator can withhold the price. A stronger design sends the request to several TEEs and requires a quorum of signed answers.
  • Availability: the contract accepts any production TEE of the extension, even one whose availability check has lapsed. If that matters to you, also check getAvailabilityCheckValidity.
  • Sources: the example doesn't check the sources' own timestamps.
What's next

To learn more about FCC extensions, see: