Original text from Pavel Naydanov

Compiled by | Odaily Planet Daily Golem (@web3_golem)

超详细揭秘Polymarket背后的技术实现方式

Editor's Note: Polymarket gained more attention in this U.S. election, not only because the cumulative trading volume of prediction topics surpassed $3.6 billion, but also because it successfully predicted Trump's victory earlier than polls and traditional media, making people more aware that Polymarket is not just a betting site but will become a more authentic and reliable 'news site' (recommended reading: (Vitalik's new article: From Prediction Markets to Information Finance)). Polymarket may be the most eye-catching 'sight' in this round of blockchain innovation.

So, how is Polymarket, which has significant 'blockchain revolutionary' implications, technically realized? Smart contract developer Pavel Naydanov provides a detailed breakdown and explanation of the technology adopted by Polymarket, which is enlightening for developers, especially newcomers building prediction markets. Odaily Planet Daily compiles the parts related to technical implementation as follows, and let us now delve into the technical details of the protocol.

CTF: Tokenizing outcomes

All event outcomes on Polymarket are tokenized:

  • Such tokens can be referred to as Share tokens;

  • Shares are purchased with base assets, making them fully collateralized;

  • Shares can be sold for base assets.

Share tokens are implemented based on the Gnosis Conditional Token Framework (CTF), which has proven its effectiveness and has been tested across various protocols, supporting up to 256 outcomes per event.

Each prediction is identified in CTF, for which they are assigned a unique condition ID, composed of the hash values of three parameters:

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

  • Question ID: The prediction identifier set by the creator of the prediction question. This can be a simple counter that increments for each new prediction or a more complex scheme using hashes of text and other data;

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

The following diagram visually illustrates how the CTF (Conditional Token Framework) works:

超详细揭秘Polymarket背后的技术实现方式

Users provide base assets when betting and receive Share tokens, known as conditional tokens in CTF. After the oracle determines the prediction, users can claim rewards from CTF based on the prediction outcome.

When users receive conditional tokens, they are considered to have determined a specific position. In CTF, positions represent a set of combinations of possible outcomes for each prediction. CTF generates these positions for each prediction, with each position corresponding to one of the possible combinations of outcomes that users can choose.

For example:

What is the highest-grossing movie of 2024?

  • Guardians of the Galaxy Vol. 2

  • Deadpool 3

  • Joker 2

  • Despicable Me 4

  • Dune: Part Two

  • Mad Max: Furiosa

  • Others

Users can vote that (Guardians of the Galaxy Vol. 2) will become the highest-grossing movie or that (Dune: Part Two) absolutely will not be the highest-grossing movie of 2024. This combination of predictions will be considered their position.

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 one position. These mechanisms allow users to flexibly manage their positions.

CTF provides four important advantages for Polymarket:

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

  • A flexible system has been implemented that combines users' votes into various positions;

  • The responsibility for calculating results based on the oracle's signals is delegated to CTF;

  • Rewards are calculated based on the number of Share tokens for the winning outcome.

It is also worth mentioning that the CTF allows for organizing related activities where users' positions can be merged. However, there are currently no such examples on Polymarket. For more information about CTF, you can refer to the official documentation.

Order Mechanism

超详细揭秘Polymarket背后的技术实现方式

To make a purchase, the Polymarket interface offers three types of orders:

  • Market - Buy immediately at the current market price;

  • Limit - Delayed orders that allow you to specify the price to buy after it reaches that price;

  • AMM - Purchase at a price automatically determined similarly to a decentralized exchange, based on the reserve amounts in the pool.

Currently, the AMM order functionality seems to be ineffective, as no predictions allowing purchases through AMM have been found. A comment from a user in Polymarket's Discord somewhat explains this situation.

超详细揭秘Polymarket背后的技术实现方式

AMM is outdated.

According to Polymarket's documentation, AMM is developed as part of the Conditional Token Framework's smart contracts. Therefore, AMM is used to determine the purchase price of Share tokens. This fundamental mechanism requires liquidity to ensure stable pricing and reduce volatility. Liquidity providers need economic incentives, receiving rewards from each purchase to maintain system operation.

Initially, Polymarket may have been entirely based on CTF, using AMM to determine prices. However, over time, the protocol has developed a hybrid solution with an order book, where two other types of orders (limit and market orders) began to operate on this customized solution. This solution is called CLOB (Central Limit Order Book) or BLOB (Binary Limit Order Book).

CLOB and BLOB

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

Without further ado, the system is illustrated in the following diagram:

超详细揭秘Polymarket背后的技术实现方式

Users create orders to be executed, which can be limit orders or market orders; operators match user orders and initiate 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 orders are stored off-chain before execution, the terms of the order can be adjusted quickly and free of charge, or even completely canceled.

However, everything related to order books and order matching can only be accessed via API. For convenience, Polymarket provides two clients: one using JavaScript and one using Python.

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

超详细揭秘Polymarket背后的技术实现方式

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

Smart contract

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

超详细揭秘Polymarket背后的技术实现方式

Most of these are small smart contracts with limited functionality:

  • BaseExchange.sol: Abstract smart contract that implements the ability to receive ERC-1155 tokens and is also responsible for preventing reentrancy attacks;

  • Auth.sol: Role manager, defines validation functions and modifiers to set roles, admin and operator of CTFExchange.sol;

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

  • Fees.sol: Defines protocol fees;

  • Pausable.sol: Defines the ability to pause smart contract operations, a centralized form adopted by the protocol in unforeseen circumstances. Applicable only to admin roles;

  • AssetOperation.sol: Defines operations for base assets and CTF. Includes transfers, splits, and merges of positions;

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

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

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

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

  • fillOrder() — Executes an order between the user creating the order and the user-selected listing (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.

超详细揭秘Polymarket背后的技术实现方式

Regardless of how the call enters the smart contract, the outcome is always the same: two users will exchange tokens based on their orders.

Protocol Fees

Fees are charged based on the output asset. For binary predictions, fees are symmetrical, meaning: if a user sells tokens at $0.99, they will pay the same fee as the buyer who purchases tokens at $0.01.

The calculation formula is straightforward, taken from the official documentation:

超详细揭秘Polymarket背后的技术实现方式

Liquidity Reward Program

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

In order for order book-based exchanges to function, someone needs to create limit orders, which provide liquidity that allows market orders to be executed immediately. Users who create limit orders are called market makers. The 'tightness' of limit orders to market prices directly affects the speed of market order execution and increases trading volume, which is undoubtedly beneficial for end users. Additionally, the greater the liquidity, the harder it is to manipulate the market.

To ensure sufficient liquidity, Polymarket has established a special reward program to incentivize users to create limit orders. The closer the limit order is to the average market price, the higher the reward. Rewards will be automatically paid out daily at midnight (UTC).

The system is modeled after dYdX; for more information, you can refer to the original dYdX liquidity incentive program and Polymarket's detailed liquidity reward calculation formula.

Oracle

Oracles are used to provide prediction outcomes — whether the event occurs or not. The oracle is one of the most critical components of the protocol, but it is a third-party service, not the Polymarket team, known as UMA.

UMA is a decentralized oracle specifically designed to record any kind of data on the blockchain, except for unverifiable data. This oracle is optimistic, assuming data is correct by default unless disputed. UMA has its own arbitration system to resolve disputes, where arbitrators are real people — participants in the UMA ecosystem, particularly UMA token holders. This system is known as DVM (Data Verification Mechanism).

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

超详细揭秘Polymarket背后的技术实现方式

  1. Statement: Predictions are added to the oracle with rewards. Anyone who successfully disputes the outcome of a prediction can claim the reward;

  2. Challenge period: During this period, anyone can contest the prediction outcomes. If no challenges occur and the time expires, the prediction outcome is considered ready for final settlement, indicating its accuracy;

  3. Dispute: Any participant in the protocol can contest the outcome, whether to claim a reward or for fairness. In reality, this situation is rare, as game theory suggests that most participants 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 receive rewards for participating in the vote.

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

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

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

  2. Participants contesting the prediction results will also provide collateral. If they are correct, they will recover their collateral and receive rewards; otherwise, they will lose their collateral. This incentivizes participants to only challenge those results they are confident are wrong.

  3. Participants resolving disputes. They must stake UMA tokens and will receive rewards for resolving disputes. If they vote incorrectly or do not vote at all, they will lose part of their staked balance; otherwise, they will receive rewards. There is no way to slack off.

It is particularly noteworthy that the voting process in disputes is divided into two phases using a commit/reveal scheme:

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

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

This two-phase voting process prevents voters from colluding to discredit the oracle or attack services relying on prediction outcomes. At the same time, prediction outcomes can be contested multiple times, in which case UMA allows the decision-making process to restart after previous disputes are resolved.

The process for initiating a dispute is as follows:

超详细揭秘Polymarket背后的技术实现方式

Conclusion

The seemingly simple betting and prediction system of Polymarket actually consists of three main modules, each developed by different protocols and teams:

  • CTF (Conditional Token Framework): Manages combinations, positions, and Shares in predictions. This flexible framework created by Gnosis is very suitable for prediction markets.

  • CLOB (Central Limit Order Book): Polymarket's internal solution for implementing order books and limit orders. CLOB allows users to effectively 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 outcomes via blockchain.

While Polymarket is a betting system, technically, the protocol successfully combines technologies from different projects, making it particularly attractive to developers.

Related Reading

How long will the buzz around Polymarket and prediction markets last after the U.S. elections?

How does Polymarket outperform traditional polling in elections?