⚙️Thales integration

Thales API

In order to ensure easy integration with external partners Thales API is created. API returns all main data available on Thales. Using Thales API endpoints someone can get data about:

  • Thales collaterals

  • Thales markets

  • Thales market

  • User Thales positions

  • User Thales transactions

  • Buy quote

  • Sell quote

More details about each API endpoint with request/response examples can be found under Postman documentation.

Contract integration

Once all data are fetched from API, the next step is integration with Thales contracts. Depending on whether someone wants to buy a position on Tokenized Positional Markets or Tokenized Ranged Markets integration should be done with ThalesAMM or RangedAMM contract.

The next sections describe integration with Thales API and Thales contracts together with JS code examples.

Buy a UP/DOWN position

Let's say someone wants to buy UP positional tokens on the BTC market with a strike price of 35000 on 7th November 2023 with a buy-in amount of 100 sUSD:

Integration with Thales API and Thales AMM contract should include the following steps:

  1. Get a buy quote for the market from Thales API

  2. Get a Thales AMM contract address for a specific network from Thales contracts

  3. Get a Thales AMM contract ABI from Thales contract repository contract repository

  4. Create Thales AMM contract instance

  5. Call buyFromAmm method on Thales AMM contract with input parameters fetched from Thales API in step #1

The JS code snippet below implements these steps:

import { ethers } from "ethers";
import w3utils from "web3-utils";
import axios from "axios";
import dotenv from "dotenv";
import ammContractAbi from "./ammContractAbi.js"; // ThalesAMM contract ABI

dotenv.config();

const API_URL = "https://api.thalesmarket.io"; // base API URL
const NETWORK_ID = 10; // optimism network ID
const NETWORK = "optimism"; // optimism network
const AMM_CONTRACT_ADDRESS = "0x278B5A44397c9D8E52743fEdec263c4760dc1A1A"; // ThalesAMM contract address on optimism
const MARKET_ADDRESS = "0x150Faf51367770DEfF9e004773B73A9387d9EB58"; // address of BTC market with strike price 35000 at 2023-11-07
const POSITION = 0; // select UP position
const BUY_IN = 100; // 100 sUSD
const SLIPPAGE = 0.02; // slippage 2%

// create instance of Infura provider for optimism network
const provider = new ethers.providers.InfuraProvider(
  { chainId: Number(NETWORK_ID), name: NETWORK },
  process.env.INFURA
);

// create wallet instance for provided private key and provider
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

// create instance of Thales AMM contract
const amm = new ethers.Contract(AMM_CONTRACT_ADDRESS, ammContractAbi, wallet);

const buyFromAmm = async () => {
  try {
    // get a buy quote from Thales API for provided market, position and buy-in amount on optimism network
    const quoteResponse = await axios.get(
      `${API_URL}/thales/networks/${NETWORK_ID}/markets/${MARKET_ADDRESS}/buy-quote?position=${POSITION}&buyIn=${BUY_IN}`
    );
    const quoteData = quoteResponse.data;
    console.log("Quote data", quoteData);

    // convert payout got from API to BigNumber
    const parsedPayout = ethers.utils.parseEther(quoteData.payout.toString());
    // convert actual buy-in amount got from API to BigNumber
    // actualBuyInCollateralAmount is different from BUY_IN due to the contract architecture having positions amount as input and not buy-in amount
    const parsedActualBuyInCollateralAmount = ethers.utils.parseEther(
      quoteData.actualBuyInCollateralAmount.toString()
    );
    // convert slippage tolerance to BigNumber
    const parsedSlippage = ethers.utils.parseEther(SLIPPAGE.toString());

    // call buyFromAMM method on Thales AMM contract
    const tx = await amm.buyFromAMM(
      MARKET_ADDRESS,
      POSITION,
      parsedPayout,
      parsedActualBuyInCollateralAmount,
      parsedSlippage,
      {
        type: 2,
        maxPriorityFeePerGas: w3utils.toWei("0.00000000000000001"),
      }
    );
    // wait for the result
    const txResult = await tx.wait();
    console.log(
      `Successfully bought from AMM. Transaction hash: ${txResult.transactionHash}`
    );
  } catch (e) {
    console.log("Failed to buy from AMM", e);
  }
};

buyFromAmm();

Buy a IN/OUT position

Let's say someone wants to buy IN positional tokens on the BTC market with a range 34000-38000 on 7th November 2023 with a buy-in amount of 100 sUSD:

Integration with Thales API and Ranged AMM contract should include the following steps:

  1. Get a buy quote for the market from Thales API

  2. Get a Ranged AMM contract address for a specific network from Thales contracts

  3. Get a Ranged AMM contract ABI from Thales contract repository contract repository

  4. Create Ranged AMM contract instance

  5. Call buyFromAmm method on Ranged AMM contract with input parameters fetched from Thales API in step #1

The JS code snippet below implements these steps:

import { ethers } from "ethers";
import w3utils from "web3-utils";
import axios from "axios";
import dotenv from "dotenv";
import rangedAmmContractAbi from "./rangedAmmContractAbi.js"; // RangedAMM contract ABI

dotenv.config();

const API_URL = "https://api.thalesmarket.io"; // base API URL
const NETWORK_ID = 10; // optimism network ID
const NETWORK = "optimism"; // optimism network
const RANGED_AMM_CONTRACT_ADDRESS =
  "0x2d356b114cbCA8DEFf2d8783EAc2a5A5324fE1dF"; // RangedAMM contract address on optimism
const MARKET_ADDRESS = "0x5a268e454D7877F73531b54FF81Cd0C329C4b97e"; // address of BTC market with range 34000-38000 at 2023-11-07
const POSITION = 1; // select OUT position
const BUY_IN = 100; // 100 sUSD
const SLIPPAGE = 0.02; // slippage 2%

// create instance of Infura provider for optimism network
const provider = new ethers.providers.InfuraProvider(
  { chainId: Number(NETWORK_ID), name: NETWORK },
  process.env.INFURA
);

// create wallet instance for provided private key and provider
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

// create instance of Ranged AMM contract
const rangedAMM = new ethers.Contract(
  RANGED_AMM_CONTRACT_ADDRESS,
  rangedAmmContractAbi,
  wallet
);

const buyFromRangedAmm = async () => {
  try {
    // get a buy quote from Thales API for provided market, position and buy-in amount on optimism network
    const quoteResponse = await axios.get(
      `${API_URL}/thales/networks/${NETWORK_ID}/markets/${MARKET_ADDRESS}/buy-quote?position=${POSITION}&buyIn=${BUY_IN}`
    );
    const quoteData = quoteResponse.data;
    console.log("Quote data", quoteData);

    // convert payout got from API to BigNumber
    const parsedPayout = ethers.utils.parseEther(quoteData.payout.toString());
    // convert actual buy-in amount got from API to BigNumber
    // actualBuyInCollateralAmount is different from BUY_IN due to the contract architecture having positions amount as input and not buy-in amount
    const parsedActualBuyInCollateralAmount = ethers.utils.parseEther(
      quoteData.actualBuyInCollateralAmount.toString()
    );
    // convert slippage tolerance to BigNumber
    const parsedSlippage = ethers.utils.parseEther(SLIPPAGE.toString());

    // call buyFromAMM method on Ranged AMM contract
    const tx = await rangedAMM.buyFromAMM(
      MARKET_ADDRESS,
      POSITION,
      parsedPayout,
      parsedActualBuyInCollateralAmount,
      parsedSlippage,
      {
        type: 2,
        maxPriorityFeePerGas: w3utils.toWei("0.00000000000000001"),
      }
    );
    // wait for the result
    const txResult = await tx.wait();
    console.log(
      `Successfully bought from Ranged AMM. Transaction hash: ${txResult.transactionHash}`
    );
  } catch (e) {
    console.log("Failed to buy from Ranged AMM", e);
  }
};

buyFromRangedAmm();

Last updated