⚙️Speed Markets integration

Speed Markets API

In order to ensure easy integration with external partners Speed Markets API is created. API returns all required data to interact with Speed Markets AMM contract. Using Speed Markets API endpoints someone can get data about:

  • Buy

  • User claimable markets

  • Resolve markets (single or multiple markets)

  • Resolve market with different collateral (single market)

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 Speed Markets contract. Depending on whether someone wants to buy a position or resolve a market (claim win) integration should be done with Speed Markets AMM contract.

The next sections describe integration with Speed Markets API and Speed Markets contract together with JS code examples.

Buy a UP/DOWN position

Let's say someone wants to buy UP position on the BTC market with a current strike price ($ 63,622.56) in 10 minutes from market creation and with a buy-in amount of 5 sUSD:

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

  1. Get a buy parameters for the market from Speed Markets API

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

  3. Get a Speed Markets AMM contract ABI from Speed Markets AMM contract repository

  4. Create Speed Markets AMM contract instance

  5. Call createNewMarket or createNewMarketWithDifferentCollateral method on Speed Markets AMM contract with input parameters fetched from Speed Markets API in step #1

The JS code snippet below implements these steps:

const ethers = require('ethers');
const fetch = require('node-fetch');
const dotenv = require('dotenv');

// SpeedMarketsAMM contract ABI
const { speedAMMContract } = require('./speedAmmContractAbi.js');

dotenv.config();

const API_URL = 'https://api.thalesmarket.io'; // base API URL
const NETWORK_ID = 10; // optimism network ID
const NETWORK = 'optimism'; // optimism network
// SpeedMarketsAMM contract address on optimism
const AMM_CONTRACT_ADDRESS = '0xE16B8a01490835EC1e76bAbbB3Cadd8921b32001'; 

const ASSET = 'BTC';
const DIRECTION = 'UP';
const COLLATERAL = 'sUSD';
const BUY_IN = 5; // 5 sUSD
const DELTA_TIME = 600; // 10 min

// 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 Speed AMM contract
const speedAmm = new ethers.Contract(AMM_CONTRACT_ADDRESS, speedAMMContract.abi, wallet);

const createNewMarket = async () => {
    try {
        // Get contract method (createNewMarket/createNewMarketWithDifferentCollateral) parameters from Speed Markets API
        // for provided asset, direction, buy-in amount, collateral and delta time on optimism network
        const buyResponse = await fetch(
            `${API_URL}/speed-markets/networks/${NETWORK_ID}/buy/?asset=${ASSET}&direction=${DIRECTION}&buyin=${BUY_IN}&collateral=${COLLATERAL}&deltaTimeSec=${DELTA_TIME}`
        );

        const buyData = await buyResponse.json();
        console.log('Buy data', buyData);

        let tx;
        if (buyData.methodName == 'createNewMarketWithDifferentCollateral') {
            // call createNewMarketWithDifferentCollateral method on Speed Markets AMM contract
            tx = await speedAmm.createNewMarketWithDifferentCollateral(
                buyData.asset,
                buyData.strikeTime,
                buyData.delta,
                buyData.direction,
                buyData.priceUpdateData,
                buyData.collateral,
                buyData.collateralAmount,
                buyData.isEth,
                buyData.referrer,
                buyData.skewImpact,
                {
                    value: buyData.value,
                    type: 2,
                    maxPriorityFeePerGas: 10, // 10 wei
                }
            );
        } else {
            // call createNewMarket method on Speed Markets AMM contract
            tx = await speedAmm.createNewMarket(
                buyData.asset,
                buyData.strikeTime,
                buyData.delta,
                buyData.direction,
                buyData.buyinAmount,
                buyData.priceUpdateData,
                buyData.referrer,
                buyData.skewImpact,
                { value: buyData.value, type: 2, maxPriorityFeePerGas: 10 } // 10 wei
            );
        }

        // wait for the result
        const txResult = await tx.wait();
        console.log(`Successfully bought from Speed AMM. Transaction hash: ${txResult.transactionHash}`);
    } catch (e) {
        console.log('Failed to buy from Speed AMM', e);
    }
};

createNewMarket();

Resolve market(s)

Let's say someone wants to claim winnings on two markets (resolve markets) in sUSD:

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

  1. Get a resolve parameters for the markets from Speed Markets API

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

  3. Get a Speed Markets AMM contract ABI from Speed Markets AMM contract repository

  4. Get a user claimable markets from Speed Markets API

  5. Create Speed Markets AMM contract instance

  6. Call resolveMarketsBatch method on Speed Markets AMM contract with input parameters fetched from Speed Markets API in step #1

The JS code snippet below implements these steps:

const ethers = require('ethers');
const fetch = require('node-fetch');
const dotenv = require('dotenv');
// SpeedMarketsAMM contract ABI
const { speedAMMContract } = require('./speedAmmContractAbi.js'); 

dotenv.config();

const API_URL = 'https://api.thalesmarket.io'; // base API URL
const NETWORK_ID = 10; // optimism network ID
const NETWORK = 'optimism'; // optimism network
// SpeedMarketsAMM contract address on optimism
const AMM_CONTRACT_ADDRESS = '0xE16B8a01490835EC1e76bAbbB3Cadd8921b32001'; 

// Speed markets addresses to resolve
const MARKET_1 = '0x5ef786087d122b9056f351Cf3B52E5A7B0d5277D'; 
const MARKET_2 = '0x2542906FE4701A8c930427c2ff6Db1C948B91571';

// 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 Speed AMM contract
const speedAmm = new ethers.Contract(AMM_CONTRACT_ADDRESS, speedAMMContract.abi, wallet);

const resolveMarkets = async () => {
    try {
        // Get contract method (resolveMarketsBatch) parameters from Speed Markets API
        // for provided market address on optimism network
        const resolveResponse = await fetch(
            `${API_URL}/speed-markets/networks/${NETWORK_ID}/resolve?markets[]=${MARKET_1}&markets[]=${MARKET_2}`
        );

        const resolveData = await resolveResponse.json();
        console.log('Resolve data', resolveData);

        // call resolveMarketsBatch method on Speed Markets AMM contract
        const tx = await speedAmm.resolveMarketsBatch(
            resolveData.markets, 
            resolveData.priceUpdateData, 
            {
                value: resolveData.value,
                type: 2,
                maxPriorityFeePerGas: 10, // 10 wei
            }
        );

        // wait for the result
        const txResult = await tx.wait();
        console.log(`Successfully resolved market on Speed AMM. Transaction hash: ${txResult.transactionHash}`);
    } catch (e) {
        console.log('Failed to resolve market on Speed AMM', e);
    }
};

resolveMarkets();

Resolve market with different collateral

If someone wants to claim winning in different collateral than default one for a network (resolve market) process is the same as previous one, just using appropriate API and contract method. Corresponding API is "Resolve market with different collateral" and contract method resolveMarketWithOfframp. Currently batch is not available for claim with different collateral.

Last updated