-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguide.mdf
More file actions
295 lines (235 loc) · 10.7 KB
/
Copy pathguide.mdf
File metadata and controls
295 lines (235 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# Futarchy Technical Documentation & Sushiswap Integration Guide
## Table of Contents
1. [System Overview](#system-overview)
2. [Smart Contracts](#smart-contracts)
- [Contract Addresses](#contract-addresses)
- [Contract ABIs](#contract-abis)
3. [Token Standards](#token-standards)
4. [Core Operations](#core-operations)
- [Adding Collateral (Split & Wrap)](#adding-collateral-split-wrap)
- [Position Merging](#position-merging)
5. [Contract Interactions](#contract-interactions)
6. [Sushiswap Integration and Swap Process](#sushiswap-integration-and-swap-process)
- [Fetching Swap Route Data](#fetching-swap-route-data)
- [Executing the Swap](#executing-the-swap)
- [Route Data Structure](#route-data-structure)
7. [Integration Example](#integration-example)
8. [Error Handling](#error-handling)
9. [Best Practices and Security](#best-practices-and-security)
---
## 1. System Overview
The Futarchy system is a prediction market platform built on the Gnosis Chain. It enables users to trade on outcomes using a combination of ERC1155 and ERC20 tokens. The system employs advanced mechanisms such as splitting positions into YES/NO tokens and wrapping these positions to make them fungible, allowing trading via decentralized exchanges such as SushiSwap.
## 2. Smart Contracts
### Contract Addresses
- **Conditional Tokens Contract:** `0xCeAfDD6bc0bEF976fdCd1112955828E00543c0Ce`
- **Wrapper Service Contract:** `0xc14f5d2B9d6945EF1BA93f8dB20294b90FA5b5b1`
- **Futarchy Router Contract:** `0x7495a583ba85875d59407781b4958ED6e0E1228f`
- **SushiSwap V2 Router:** `0xf2614A233c7C3e7f08b1F887Ba133a13f1eb2c55`
- **Base Currency Token (sDAI):** `0xaf204776c7245bF4147c2612BF6e5972Ee483701`
- **Base Company Token (GNO):** `0x9C58BAcC331c9aa871AFD802DB6379a98e80CEdb`
### Contract ABIs
#### Conditional Tokens ABI
```javascript
[
'function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] partition, uint amount) external',
'function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] partition, uint amount) external',
'function isApprovedForAll(address owner, address operator) external view returns (bool)',
'function setApprovalForAll(address operator, bool approved) external',
'function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) external'
]
```
#### Wrapper Service ABI
```javascript
[
'function wrap(address multiToken, uint256 tokenId, uint256 amount, address recipient, bytes data) external',
'function unwrap(address multiToken, uint256 tokenId, uint256 amount, address recipient, bytes data) external'
]
```
#### Futarchy Router ABI
```javascript
[
'function splitPosition(address proposal, address collateralToken, uint256 amount) external',
'function mergePositions(address proposal, address collateralToken, uint256 amount) external'
]
```
#### ERC20 ABI
```javascript
[
'function approve(address spender, uint256 amount) external returns (bool)',
'function allowance(address owner, address spender) external view returns (uint256)',
'function balanceOf(address account) external view returns (uint256)',
'function transfer(address recipient, uint256 amount) external returns (bool)',
'function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)'
]
```
#### ERC1155 ABI
```javascript
[
'function balanceOf(address account, uint256 id) external view returns (uint256)',
'function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) external'
]
```
---
## 3. Token Standards
- **ERC1155:** Used for representing the raw YES/NO positions in the system. These tokens allow batch operations and represent non-fungible position IDs.
- **ERC20:** Wrapped tokens generated from splitting positions. They are fungible and can be traded on decentralized exchanges.
---
## 4. Core Operations
### Adding Collateral (Split & Wrap)
The new version simplifies the process by combining position splitting and wrapping into a single operation. When you add collateral, it automatically splits your base token (e.g., sDAI or GNO) into YES and NO positions and wraps them into tradeable ERC20 tokens in one transaction.
```javascript
// Example: Adding collateral (splits and wraps in one step)
async function addCollateral(amount) {
const amountWei = ethers.utils.parseEther(amount);
// Approve base token for Futarchy Router
await baseToken.approve(FUTARCHY_ROUTER_ADDRESS, amountWei);
// Execute split and wrap via Futarchy Router
await futarchyRouter.splitPosition(MARKET_ADDRESS, baseTokenAddress, amountWei);
}
```
### Position Merging (Collateral Removal)
Merging combines YES and NO positions back into the original base token in a single transaction.
```javascript
// Example: Merging YES/NO positions
async function mergePositions(amount) {
const amountWei = ethers.utils.parseEther(amount);
// Approve wrapped YES and NO tokens
await yesToken.approve(FUTARCHY_ROUTER_ADDRESS, amountWei);
await noToken.approve(FUTARCHY_ROUTER_ADDRESS, amountWei);
// Merge positions via Futarchy Router
await futarchyRouter.mergePositions(MARKET_ADDRESS, baseTokenAddress, amountWei);
}
```
---
## 5. Contract Interactions
### Approval Flow
Before interacting with the contracts, it is essential to ensure that the user has approved the appropriate token allowances.
```javascript
async function handleTokenApproval(tokenAddress, spenderAddress, amount) {
const tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, signer);
const currentAllowance = await tokenContract.allowance(userAddress, spenderAddress);
if (currentAllowance.lt(amount)) {
await tokenContract.approve(spenderAddress, ethers.constants.MaxUint256);
}
}
```
### Balance Checking
It is important to check both ERC20 and ERC1155 balances before performing operations.
```javascript
async function checkBalances(userAddress) {
// ERC1155: Get balance for positions
const positionIds = [yesPositionId, noPositionId];
const balances = await conditionalTokens.balanceOfBatch(Array(2).fill(userAddress), positionIds);
// ERC20: Get wrapped token balances
const wrappedYesBalance = await yesToken.balanceOf(userAddress);
const wrappedNoBalance = await noToken.balanceOf(userAddress);
}
```
---
## 6. Sushiswap Integration and Swap Process
Sushiswap is used for swapping between the different position tokens within the Futarchy system. This integration is handled using two core functions:
### Fetching Swap Route Data
The `fetchSushiSwapRoute` function fetches optimal route data from the Sushiswap V5 API.
```javascript
const fetchSushiSwapRoute = async ({
tokenIn,
tokenOut,
amount,
userAddress,
feeReceiver,
options = { maxSlippage: '0.005', gasPrice: '1000000008', fee: '0.0025' }
}) => {
// Constructs API URL and fetches swap route data
// Returns an object containing:
// transferValueTo, amountValueTransfer, tokenIn, amountIn, tokenOut, amountOutMin, to, and route (encoded route bytes)
};
```
### Executing the Swap
Once the route data is obtained, the `executeSushiSwapRoute` function performs the swap execution using the Sushiswap V5 router.
```javascript
const executeSushiSwapRoute = async ({
signer,
routerAddress,
routeData,
options = { gasLimit: 400000, gasPrice: ethers.utils.parseUnits('0.97', 'gwei') }
}) => {
// Executes the swap by calling processRouteWithTransferValueOutput on the Sushiswap V2 router
// Returns a transaction receipt after waiting for confirmation
};
```
### Route Data Structure
The route data returned from the API has the following structure:
```javascript
interface RouteData {
transferValueTo: string, // Fee receiver address
amountValueTransfer: BigNumber, // Fee amount
tokenIn: string, // Input token address
amountIn: BigNumber, // Input amount
tokenOut: string, // Output token address
amountOutMin: BigNumber, // Minimum output amount
to: string, // Recipient address
route: string // Encoded route bytes
}
```
The encoded route bytes contain detailed information about the swap path, including the number of hops, token addresses, pool types, fees, and protocol identifiers.
---
## 7. Integration Example
```javascript
async function swapPositionTokens(tokenIn, tokenOut, amount, userAddress) {
try {
// 1. Fetch the optimal swap route
const routeData = await fetchSushiSwapRoute({
tokenIn,
tokenOut,
amount: ethers.utils.parseEther(amount),
userAddress,
feeReceiver: FEE_RECEIVER_ADDRESS
});
// 2. Approve the router to spend the input token if necessary
await handleTokenApproval(routeData.tokenIn, SUSHISWAP_V2_ROUTER, routeData.amountIn);
// 3. Execute the swap
const tx = await executeSushiSwapRoute({
signer,
routerAddress: SUSHISWAP_V2_ROUTER,
routeData
});
await tx.wait();
return tx;
} catch (error) {
handleSwapError(error);
}
}
```
---
## 8. Error Handling
Proper error handling is crucial to ensure a robust integration.
```javascript
function handleSwapError(error) {
if (error.message.includes('INSUFFICIENT_OUTPUT_AMOUNT')) {
throw new Error('Slippage too high, try increasing slippage tolerance');
}
if (error.message.includes('EXCESSIVE_INPUT_AMOUNT')) {
throw new Error('Trade size too large for available liquidity');
}
if (error.message.includes('user rejected')) {
throw new Error('Transaction rejected by user');
}
console.error('Swap failed:', error);
throw new Error('Swap failed: ' + error.message);
}
```
---
## 9. Best Practices and Security
### Best Practices
- **Balance Checks:** Always verify token balances before initiating any operation.
- **Approval Management:** Check existing allowances and only request approval if necessary.
- **Gas Optimization:** Set appropriate gas limits and monitor gas prices for efficient transactions.
- **Slippage Protection:** Use reasonable slippage tolerances, e.g., 0.5% to 1%.
- **Modular Functions:** Implement modular and reusable functions like `handleTokenApproval` for consistency.
### Security Considerations
- **Input Validation:** Ensure that all user inputs are validated (e.g., amount is positive and within allowed limits).
- **Allowance Revocation:** Revoke token allowances if they are no longer needed to reduce risk exposure.
- **Transaction Monitoring:** Wait for transaction confirmations and handle failures gracefully using try-catch blocks.
- **Audit:** Regularly audit smart contract interactions and approval logic.
---
This document provides a comprehensive guide on the technical aspects of the Futarchy system and its integration with Sushiswap. Refer to the source code for further implementation details and testing scenarios.