A detailed look at the technology behind Polymarket

avatar
ODAILY
11-11
This article is machine translated
Show original

The original text is from Pavel Naydanov

Compiled | Odaily Golem(@web3_golem

Editor's Note: Polymarket has gained more attention in the recent US election, not only because the cumulative trading volume of the prediction topics has exceeded $3.6 billion, but also because it successfully predicted Trump's victory earlier and more accurately than polls and traditional media (recommended reading:《Vitalik's New Article: From Prediction Markets to Information Finance》). Polymarket may be the most brilliant "landscape" in this round of blockchain innovation.

So, how is the technologically "revolutionary" Polymarket implemented? Smart contract developer Pavel Naydanov has carefully dissected and explained the technologies used by Polymarket, which is of enlightening significance for developers (especially the rising stars in building prediction markets). Odaily will compile the part involving technical implementation, and let's dive into the technical details of the protocol in the following.

CTF: Tokenizing Outcomes

All event outcomes on Polymarket are tokenized:

  • Such tokens can be called Share tokens;

  • Shares are purchased with the underlying asset, so they are fully collateralized;

  • Shares can be sold to receive the underlying asset.

Share tokens are implemented using the Gnosis Conditional Tokens Framework (CTF), an ERC-1155 framework that has proven its effectiveness and has been tested across multiple protocols, with the ability to support up to 256 outcomes per event.

Each prediction is identified in the CTF by a unique condition ID, composed of a hash of three parameters:

  • Oracle: the address of the oracle that will determine the event outcome, ensuring that only the specified oracle can settle the prediction;

  • Question ID: the prediction identifier, set by the creator of the prediction question. This can be a simple counter, incrementing the previous prediction question, or a more complex scheme using text and other data hashes;

  • outcomeSlotCount: the number of possible outcomes for the prediction.

The diagram below illustrates how the CTF (Conditional Tokens Framework) works:

Users provide the underlying asset when placing a bet and receive Share tokens, referred to as conditional tokens in the CTF. After the oracle determines the prediction outcome, users can claim their rewards from the CTF based on the prediction result.

When users receive conditional tokens, they are considered to have taken a specific position. In the CTF, a position represents a combination of possible outcome combinations for each prediction. The CTF generates these positions, each corresponding to one of the possible outcome combinations that users can choose from.

For example:

What will be the highest-grossing movie of 2024?

  • Inside Out 2

  • Deadpool 3

  • Joker 2

  • Despicable Me 4

  • Dune 2

  • Mad Max 4

  • Other

A user can vote that "Inside Out 2" will be the highest-grossing movie, or that "Dune 2" will definitely not be the highest-grossing movie of 2024. This prediction combination will be considered their position.

The CTF provides two interesting mechanisms for handling positions: splitting and merging. The splitting mechanism allows a single position to be divided into multiple separate outcomes, while merging combines different outcomes into a single position. These mechanisms allow users to flexibly manage their positions.

The CTF provides four key advantages for Polymarket:

  • Share tokens can be used to confirm users' votes on specific prediction outcomes;

  • It implements a flexible system to aggregate users' votes into various positions;

  • It delegates the responsibility of outcome calculation to the CTF based on the oracle's signal;

  • It calculates rewards based on the number of winning result Share tokens.

Additionally, it's worth noting that the CTF allows organizing related activities where users' positions can be merged. However, there are no such examples on Polymarket yet. To learn more aboutCTF, you can refer to theofficial documentation.

Order Mechanism

For making purchases, the Polymarket interface provides three types of orders:

  • Market - Buy immediately at the current market price;

  • Limit - A delayed order that allows you to specify the price at which to buy;

  • AMM - Buy at a price automatically determined similar to a decentralized exchange, based on the reserves in the pool.

Currently, the AMM order functionality seems to be non-functional, as no way to purchase predictions through AMM has been found. A comment from a user on Polymarket's Discord provides some explanation for this situation.

AMM is outdated

According to Polymarket's documentation, the AMM was developed as part of the Conditional Tokens Framework smart contracts. Therefore, the AMM was used to determine the purchase price of Share tokens. This basic mechanism requires liquidity to ensure stable pricing and reduce volatility. Liquidity providers need economic incentives to earn rewards from each purchase to keep the system running.

It's possible that Polymarket was initially entirely based on the CTF, using the AMM to determine prices. But over time, the protocol developed a hybrid solution with an order book, and the other two order types (limit and market) started working on this custom solution.

CLOB and BLOB

CLOB (Central Limit Order Book) or BLOB (Binary Limit Order Book) is a system that represents a hybrid decentralized order book. In this system, dedicated operators are responsible for handling order matching and triggering the execution of smart contracts.

Without going into too much detail, the system is as shown in the diagram below:

Users create the orders they want to execute, which can be limit orders or market orders; the operators match the user orders and initiate the execution on the smart contract, creating an order means creating a data structure signed with the user's private key according to the EIP-712 standard. Since the orders are stored off-chain before execution, they can be quickly and freely adjusted or even completely canceled.

However, all content related to the order book and order matching can only be accessed through the API, for convenience, Polymarket provides two client implementations: one using JavaScript, and one using Python.

However, the Exchange.sol smart contract is public, responsible for creating user positions in the CTF. It also allows for the management of user positions and the transfer of assets between them, ensuring the security and transparency within the protocol.

The smart contract has been audited, with the audit report attached to the repository.

Smart Contract

The Exchange smart contract actually has a more specific name, CTFExchange.sol. It is not very large, only about 100 lines of code, but it does have a significant number of dependencies.

Most of these are small smart contracts that implement limited functionality:

  • BaseExchange.sol: An abstract smart contract that implements the ability to receive ERC-1155 tokens, and also responsible for preventing re-entrancy attacks;

  • Auth.sol: A role manager, defining the verification functions and modifiers to set the roles, the admin and operator of CTFExchange.sol;

  • Assets.sol: Defines two types of assets, the base asset (collateral) and the CTF address;

  • Fees.sol: Defines the protocol fees;

  • Pausable.sol: Defines the ability to pause the operations of the smart contract, a centralized form that the protocol agrees to adopt in the event of unforeseen circumstances. Only applicable to the admin role;

  • AssetOperation.sol: Defines the operations on the base asset and CTF. Including the transfer, splitting, and merging of positions;

  • Signature.sol: Defines the code for verifying the user signatures used when validating orders;

  • Hashing.sol: Defines the hash values of the order parameters, used for signature verification;

  • Registry.sol: Defines the process of registering predictions in the system and registering tokens for predictions.

All the content related to the actual execution of orders is implemented in the smart contract Trading.sol.Traversing the code and studying the smart contracts is also quite straightforward. The structure clearly defines the entry points through functions:

  • fillOrder() — Executes an order between the user who created the order and the user who selected the order (another order);

  • fillOrders() — Same as fillOrder(), but for a list of orders;

  • matchOrders() — The operator selects two different orders and executes them.

All the above functions can only be called by the operator.

Regardless of how the call enters the smart contract, the result is always the same: two users will exchange tokens according to their orders.

Protocol Fees

Fees are charged based on the output assets. For binary predictions, the fees are symmetric, meaning that: if a user sells a token for $0.99, they will pay the same fee as the buyer who buys the token for $0.01.

The calculation formula is quite simple, taken from the official documentation:

Liquidity Rewards Program

The overall goal of this program is to incentivize market liquidity.

For an order book-based exchange to function, there need to be people creating limit orders, and these limit orders provide the liquidity that allows market orders to be executed immediately. The users who create limit orders are called market makers. The tighter the limit orders are to the market price, the faster market orders can be executed, and the higher the trading volume, which is undoubtedly beneficial for the end-users. Furthermore, the greater the liquidity, the more difficult it is to manipulate the market.

To ensure sufficient liquidity, Polymarket has developed a special rewards program to incentivize users to create limit orders. The closer the limit orders are to the average market price, the higher the reward. The rewards will be paid automatically at midnight (UTC) every day.

The system is modeled after dYdX, and for more information, you can check the original dYdX Liquidity Incentive Program and Polymarket's detailed Liquidity Rewards Calculation Formula.

Oracles

Oracles are used to provide the prediction results — whether the event occurred or not. Oracles are one of the most critical components of the protocol, but they are provided by a third-party service, not the Polymarket team, and this oracle is called UMA.

UMA is a decentralized oracle, specifically designed to record any type of data on the blockchain, except for unverifiable data. The oracle is optimistic, meaning the data is assumed to be correct unless there is a dispute. UMA has its own arbitration system to resolve disputes, with arbitrators being real people — participants in the UMA ecosystem, particularly UMA token holders. This system is called the DVM (Data Verification Mechanism).

The following process is used to determine the prediction result and record it on the blockchain:

  1. Statement: The prediction, along with a reward, is added to the oracle. Anyone who successfully challenges the prediction result can claim the reward;

  2. Challenge period: A period during which anyone can challenge the prediction result. If no challenge occurs and the time expires, the prediction result is considered ready for final settlement, indicating its accuracy;

  3. Dispute: Any protocol participant can dispute the result, whether to claim the reward or for fairness. In reality, this rarely happens, as game theory suggests that most participants will behave honestly.

  4. Voting: If a dispute is initiated, UMA token holders will vote to resolve the dispute. UMA is the protocol token used for voting, and participants are rewarded for participating in the vote.

  5. Settlement: The final stage is the settlement process, where the data is actually recorded on the blockchain. After this, the prediction result can be considered reliable.

The entire protocol is based on game theory, and any malicious behavior by participants is economically disadvantageous.

  1. Participants who submit prediction results for voting provide collateral to the smart contract. If their results are challenged, they will lose the collateral; otherwise, they will retrieve the collateral and receive a reward. This creates a strong incentive to only submit accurate results.

  2. Participants who object to the prediction results also provide collateral. If they are correct, they will retrieve the collateral and receive a reward; otherwise, they will lose the collateral. This incentivizes participants to only challenge results they are confident are incorrect.

  3. Dispute-resolving participants. They must stake UMA tokens and will receive a reward for resolving the dispute. If they vote incorrectly or do not vote at all, they will lose a portion of their staked balance; otherwise, they will receive a reward. There is no way to slack off.

Particularly noteworthy is that the voting process in the dispute uses a commit/reveal scheme in two stages:

  1. Commit: Participants secretly vote by submitting the hash of their vote to the smart contract, meaning no one can identify how they voted by just looking at the hash.

  2. Reveal: After the voting phase, participants reveal their votes, and the smart contract verifies that they match the previously submitted hash.

This two-stage voting process prevents voters from colluding to discredit the oracle or attack services that rely on the prediction results. Additionally, the prediction results can be challenged multiple times, in which case UMA allows the decision process to be restarted after the previous dispute is resolved.

The dispute initiation process is as follows:

Conclusion

Polymarket, which appears to be a simple betting and prediction system, actually contains three main modules, each developed by different protocols and teams:

  • CTF (Conditional Token Framework): Manages the positions, shares, and portfolios in the predictions, a flexible framework created by Gnosis that is well-suited for prediction markets.

  • CLOB (Centralized Limit Order Book): Polymarket's internal solution for implementing the order book and limit orders. CLOB allows users to efficiently participate in the ecosystem and helps aggregate liquidity.

  • UMA: A decentralized oracle with a unique dispute resolution arbitration system. UMA is the core of the system, transmitting prediction results via the blockchain.

While Polymarket is a betting system, from a technical standpoint, the protocol successfully combines technologies from different projects, which is particularly appealing to developers.

Related Reading

How long will the Polymarket and prediction market hype last after the US election?

How did Polymarket outperform traditional election polls?

Source
Disclaimer: The content above is only the author's opinion which does not represent any position of Followin, and is not intended as, and shall not be understood or construed as, investment advice from Followin.
Like
Add to Favorites
Comments