Skip to content

Commit 8e3f7b2

Browse files
authored
docs(ftso): ftso adapters (#952)
2 parents 8bb1552 + ab1c54d commit 8e3f7b2

File tree

12 files changed

+1565
-1
lines changed

12 files changed

+1565
-1
lines changed

docs/ftso/guides/adapters.mdx

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
---
2+
slug: adapters
3+
title: Migrate an app to FTSO
4+
tags: [intermediate, ftso, solidity, javascript]
5+
description: Migrate your dApp from other oracles to FTSO.
6+
keywords:
7+
[
8+
solidity,
9+
reference,
10+
ftso,
11+
flare-time-series-oracle,
12+
flare-network,
13+
smart-contracts,
14+
chainlink,
15+
pyth,
16+
api3,
17+
band,
18+
chronicle,
19+
]
20+
---
21+
22+
import CodeBlock from "@theme/CodeBlock";
23+
import ChainlinkExample from "!!raw-loader!/examples/developer-hub-solidity/ChainlinkExample.sol";
24+
import chainlinkExample from "!!raw-loader!/examples/developer-hub-javascript/chainlinkExample.ts";
25+
import PythExample from "!!raw-loader!/examples/developer-hub-solidity/PythExample.sol";
26+
import pythExample from "!!raw-loader!/examples/developer-hub-javascript/pythExample.ts";
27+
import Api3Example from "!!raw-loader!/examples/developer-hub-solidity/Api3Example.sol";
28+
import api3Example from "!!raw-loader!/examples/developer-hub-javascript/api3Example.ts";
29+
import BandExample from "!!raw-loader!/examples/developer-hub-solidity/BandExample.sol";
30+
import bandExample from "!!raw-loader!/examples/developer-hub-javascript/bandExample.ts";
31+
import ChronicleExample from "!!raw-loader!/examples/developer-hub-solidity/ChronicleExample.sol";
32+
import chronicleExample from "!!raw-loader!/examples/developer-hub-javascript/chronicleExample.ts";
33+
34+
FTSO Adapters, provided by the `@flarenetwork/ftso-adapters` library, allow decentralized applications (dApps) built for other popular oracle interfaces to integrate with Flare's FTSO with minimal code changes.
35+
The library provides adapters for Pyth, Chainlink, API3, Band Protocol, and Chronicle.
36+
These adapters act as a compatibility layer, translating the FTSO's data structure into the format expected by each respective oracle's interface.
37+
38+
This enables a seamless migration path for projects looking to leverage the speed, decentralization, and cost-effectiveness of Flare's native oracle.
39+
This guide focuses on the specific code modifications required to migrate your existing dApp.
40+
41+
All code examples can be found in our [hardhat-starter-kit](https://github.com/flare-foundation/flare-hardhat-starter/tree/master/contracts/adapters).
42+
43+
## Key code changes
44+
45+
Migrating to a Flare FTSO adapter requires a different approach to handling oracle data. Instead of your contract calling an external oracle, it will now manage price data internally by using an adapter library.
46+
This process involves two main changes: modifying your smart contract and setting up a new offchain keeper process.
47+
48+
### 1. Onchain: Use the adapter library
49+
50+
The main changes happen within your smart contract. You will modify it to store, update, and serve the FTSO price data itself.
51+
52+
- **State Variables**: Instead of storing an address to an external oracle, you add state variables to your contract to manage the FTSO feed and cache the price data.
53+
- **Before**: `AggregatorV3Interface internal dataFeed;`
54+
- **After**: `bytes21 public immutable ftsoFeedId; FtsoChainlinkAdapterLibrary.Round private _latestPriceData;`
55+
56+
- **Constructor**: Your constructor no longer needs an oracle's address. Instead, it takes FTSO-specific information, such as the `ftsoFeedId` and any other parameters the adapter needs (like `chainlinkDecimals`).
57+
- **Before**: `constructor(address _dataFeedAddress) { dataFeed = AggregatorV3Interface(_dataFeedAddress); }`
58+
- **After**: `constructor(bytes21 _ftsoFeedId, uint8 _chainlinkDecimals) { ftsoFeedId = _ftsoFeedId; chainlinkDecimals = _chainlinkDecimals; }`
59+
60+
- **Implement `refresh()`**: You must add a public `refresh()` function. This function's only job is to call the adapter library's `refresh` logic, which updates your contract's state variables with the latest FTSO price.
61+
62+
- **Implement the Oracle Interface**: You then add the standard `view` function for the oracle you are migrating from (e.g., `latestRoundData()` for Chainlink).
63+
This function calls the corresponding logic from the adapter library, reading directly from your contract's cached state.
64+
65+
- **No Change to Core Logic**: Your dApp's internal logic that uses the price data remains unchanged.
66+
It continues to call the same standard oracle functions as before (e.g., `latestRoundData()`), but now it's calling a function implemented directly within your own contract.
67+
68+
### 2. Offchain: Set up a keeper bot
69+
70+
Since your contract now manages its own price updates, you need an external process to trigger them.
71+
72+
- **Create a Keeper Script**: This is a simple script that connects to the network and periodically calls the public `refresh()` function on your deployed contract.
73+
- **Run the Keeper**: This script ensures the price cached in your contract stays fresh. It replaces the need to rely on the oracle provider's keepers, giving you direct control over how often your prices are updated and how much you spend on gas.
74+
75+
## FtsoChainlinkAdapter
76+
77+
The `FtsoChainlinkAdapter` implements Chainlink's `AggregatorV3Interface`. The example is an `AssetVault` contract that uses the FTSO price to value collateral for borrowing and lending.
78+
79+
### `ChainlinkExample.sol`
80+
81+
<CodeBlock language="solidity" title="/contracts/adapters/ChainlinkExample.sol">
82+
{ChainlinkExample}
83+
</CodeBlock>
84+
85+
### `chainlinkExample.ts`
86+
87+
<CodeBlock language="typescript" title="/scripts/adapters/chainlinkExample.ts">
88+
{chainlinkExample}
89+
</CodeBlock>
90+
91+
## FtsoPythAdapter
92+
93+
The `FtsoPythAdapter` implements Pyth's `IPyth` interface. The example is a `PythNftMinter` contract that dynamically calculates a $1 minting fee based on the live FTSO price.
94+
95+
### `PythExample.sol`
96+
97+
<CodeBlock language="solidity" title="/contracts/adapters/PythExample.sol">
98+
{PythExample}
99+
</CodeBlock>
100+
101+
### `pythExample.ts`
102+
103+
<CodeBlock language="typescript" title="/scripts/adapters/pythExample.ts">
104+
{pythExample}
105+
</CodeBlock>
106+
107+
## FtsoApi3Adapter
108+
109+
The `FtsoApi3Adapter` implements the `IApi3ReaderProxy` interface. The example is a `PriceGuesser` prediction market that uses the FTSO price to settle bets.
110+
111+
### `Api3Example.sol`
112+
113+
<CodeBlock language="solidity" title="/contracts/adapters/Api3Example.sol">
114+
{Api3Example}
115+
</CodeBlock>
116+
117+
### `api3Example.ts`
118+
119+
<CodeBlock language="typescript" title="/scripts/adapters/api3Example.ts">
120+
{api3Example}
121+
</CodeBlock>
122+
123+
## FtsoBandAdapter
124+
125+
The `FtsoBandAdapter` implements Band Protocol's `IStdReference` interface. The example is a `PriceTriggeredSafe` that locks withdrawals during high market volatility, detected by checking a basket of FTSO prices.
126+
127+
### `BandExample.sol`
128+
129+
<CodeBlock language="solidity" title="/contracts/adapters/BandExample.sol">
130+
{BandExample}
131+
</CodeBlock>
132+
133+
### `bandExample.ts`
134+
135+
<CodeBlock language="typescript" title="/scripts/adapters/bandExample.ts">
136+
{bandExample}
137+
</CodeBlock>
138+
139+
## FtsoChronicleAdapter
140+
141+
The `FtsoChronicleAdapter` implements the `IChronicle` interface. The example is a `DynamicNftMinter` that mints NFTs of different tiers based on the live FTSO asset price.
142+
143+
### `ChronicleExample.sol`
144+
145+
<CodeBlock language="solidity" title="/contracts/adapters/ChronicleExample.sol">
146+
{ChronicleExample}
147+
</CodeBlock>
148+
149+
### `chronicleExample.ts`
150+
151+
<CodeBlock language="typescript" title="/scripts/adapters/chronicleExample.ts">
152+
{chronicleExample}
153+
</CodeBlock>
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { artifacts, run, web3 } from "hardhat";
2+
import { PriceGuesserInstance } from "../../typechain-types";
3+
4+
// --- Configuration ---
5+
const PriceGuesser: PriceGuesserInstance = artifacts.require("PriceGuesser");
6+
const FTSO_FEED_ID = "0x01464c522f55534400000000000000000000000000";
7+
const DESCRIPTION = "FTSOv2 FLR/USD adapted for API3";
8+
const MAX_AGE_SECONDS = 3600;
9+
const STRIKE_PRICE_USD = 0.025;
10+
const ROUND_DURATION_SECONDS = 300;
11+
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
12+
13+
async function deployContracts(): Promise<{ guesser: PriceGuesserInstance }> {
14+
const strikePriceWei = BigInt(STRIKE_PRICE_USD * 1e18);
15+
const guesserArgs: (string | number)[] = [
16+
FTSO_FEED_ID,
17+
DESCRIPTION,
18+
MAX_AGE_SECONDS,
19+
strikePriceWei.toString(),
20+
ROUND_DURATION_SECONDS,
21+
];
22+
console.log("\nDeploying integrated PriceGuesser contract with arguments:");
23+
console.log(` - FTSO Feed ID: ${guesserArgs[0]}`);
24+
console.log(` - Description: ${guesserArgs[1]}`);
25+
console.log(` - Max Age (seconds): ${guesserArgs[2]}`);
26+
console.log(` - Strike Price: ${STRIKE_PRICE_USD} (${guesserArgs[3]} wei)`);
27+
console.log(` - Round Duration: ${guesserArgs[4]} seconds`);
28+
const guesser = await PriceGuesser.new(
29+
...(guesserArgs as [string, string, number, string, number]),
30+
);
31+
console.log("\n✅ PriceGuesser deployed to:", guesser.address);
32+
33+
try {
34+
console.log("\nVerifying PriceGuesser on block explorer...");
35+
await run("verify:verify", {
36+
address: guesser.address,
37+
constructorArguments: guesserArgs,
38+
});
39+
console.log("PriceGuesser verification successful.");
40+
} catch (e: unknown) {
41+
if (e instanceof Error) {
42+
console.error("PriceGuesser verification failed:", e.message);
43+
} else {
44+
console.error("An unknown error occurred during verification:", e);
45+
}
46+
}
47+
48+
return { guesser };
49+
}
50+
51+
async function interactWithMarket(guesser: PriceGuesserInstance) {
52+
const accounts = await web3.eth.getAccounts();
53+
const deployer = accounts[0];
54+
const bettorAbove = accounts.length > 1 ? accounts[1] : deployer;
55+
const bettorBelow = accounts.length > 2 ? accounts[2] : deployer;
56+
const betAmountAbove = 10n * 10n ** 18n;
57+
const betAmountBelow = 20n * 10n ** 18n;
58+
59+
console.log(`\n--- Simulating Prediction Market ---`);
60+
console.log(` - Deployer/Settler: ${deployer}`);
61+
console.log(` - Bettor "Above": ${bettorAbove}`);
62+
console.log(` - Bettor "Below": ${bettorBelow}`);
63+
64+
console.log("\nStep 1: Bettors are placing their bets...");
65+
await guesser.betAbove({
66+
from: bettorAbove,
67+
value: betAmountAbove.toString(),
68+
});
69+
console.log(
70+
` - Bettor "Above" placed ${web3.utils.fromWei(betAmountAbove.toString())} tokens.`,
71+
);
72+
await guesser.betBelow({
73+
from: bettorBelow,
74+
value: betAmountBelow.toString(),
75+
});
76+
console.log(
77+
` - Bettor "Below" placed ${web3.utils.fromWei(betAmountBelow.toString())} tokens.`,
78+
);
79+
80+
console.log(
81+
`\nStep 2: Betting round is live. Waiting ${ROUND_DURATION_SECONDS} seconds for it to expire...`,
82+
);
83+
await wait(ROUND_DURATION_SECONDS * 1000);
84+
console.log(" - The betting round has now expired.");
85+
86+
console.log(
87+
"\nStep 3: Refreshing the FTSO price on the contract post-expiry...",
88+
);
89+
await guesser.refresh({ from: deployer });
90+
console.log(" - Price has been updated on the PriceGuesser contract.");
91+
92+
console.log("\nStep 4: Settling the prediction market...");
93+
const settleTx = await guesser.settle({ from: deployer });
94+
const settledEvent = settleTx.logs.find((e) => e.event === "MarketSettled");
95+
const finalPrice = BigInt(settledEvent.args.finalPrice.toString());
96+
const outcome = Number(settledEvent.args.outcome);
97+
const finalPriceFormatted = Number(finalPrice / 10n ** 14n) / 10000;
98+
const outcomeString = outcome === 1 ? "ABOVE" : "BELOW";
99+
console.log(
100+
`✅ Market settled! Final Price: ${finalPriceFormatted.toFixed(4)}`,
101+
);
102+
console.log(`✅ Outcome: The price was ${outcomeString} the strike price.`);
103+
104+
console.log("\nStep 5: Distributing winnings...");
105+
const [winner, loser] =
106+
outcome === 1 ? [bettorAbove, bettorBelow] : [bettorBelow, bettorAbove];
107+
const prizePool = outcome === 1 ? betAmountBelow : betAmountAbove;
108+
const winnerBet = outcome === 1 ? betAmountAbove : betAmountBelow;
109+
110+
if (prizePool > 0n || winnerBet > 0n) {
111+
console.log(` - Attempting to claim for WINNER ("${outcomeString}")`);
112+
await guesser.claimWinnings({ from: winner });
113+
const totalWinnings = winnerBet + prizePool;
114+
console.log(
115+
` - WINNER claimed their prize of ${web3.utils.fromWei(totalWinnings.toString())} tokens.`,
116+
);
117+
} else {
118+
console.log(" - WINNER's pool won, but no bets were placed to claim.");
119+
}
120+
121+
if (winner !== loser) {
122+
try {
123+
await guesser.claimWinnings({ from: loser });
124+
} catch (error: unknown) {
125+
if (error instanceof Error && error.message.includes("NothingToClaim")) {
126+
console.log(
127+
" - LOSER correctly failed to claim winnings as expected.",
128+
);
129+
} else if (error instanceof Error) {
130+
console.error(
131+
" - An unexpected error occurred for the loser:",
132+
error.message,
133+
);
134+
} else {
135+
console.error(" - An unknown error occurred for the loser:", error);
136+
}
137+
}
138+
} else {
139+
console.log(
140+
" - Skipping loser claim attempt as winner and loser are the same account.",
141+
);
142+
}
143+
}
144+
145+
async function main() {
146+
console.log("🚀 Starting Prediction Market Management Script 🚀");
147+
const { guesser } = await deployContracts();
148+
await interactWithMarket(guesser);
149+
console.log("\n🎉 Script finished successfully! 🎉");
150+
}
151+
152+
void main()
153+
.then(() => process.exit(0))
154+
.catch((error) => {
155+
console.error(error);
156+
process.exit(1);
157+
});

0 commit comments

Comments
 (0)