Skip to content

Commit 65e62b6

Browse files
committed
basic setup
0 parents  commit 65e62b6

File tree

223 files changed

+42436
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

223 files changed

+42436
-0
lines changed

.editorconfig

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
root = true
2+
3+
[*]
4+
indent_style = space
5+
indent_size = 2
6+
end_of_line = lf
7+
charset = utf-8
8+
trim_trailing_whitespace = true
9+
insert_final_newline = true
10+
11+
[*.sol]
12+
indent_size = 4
13+
14+
[*.md]
15+
trim_trailing_whitespace = false

.gitignore

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
node_modules/
2+
typechain/
3+
env.json
4+
.tmp-addresses*.json
5+
data/gmxMigration
6+
flattened
7+
8+
#Hardhat files
9+
cache
10+
artifacts

LICENSE

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2016-2020 zOS Global Limited
4+
5+
Permission is hereby granted, free of charge, to any person obtaining
6+
a copy of this software and associated documentation files (the
7+
"Software"), to deal in the Software without restriction, including
8+
without limitation the rights to use, copy, modify, merge, publish,
9+
distribute, sublicense, and/or sell copies of the Software, and to
10+
permit persons to whom the Software is furnished to do so, subject to
11+
the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included
14+
in all copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17+
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Gambit Contracts
2+
Contracts for the GMT Token and GMT Treasury.
3+
4+
## Install Dependencies
5+
If npx is not installed yet:
6+
`npm install -g npx`
7+
8+
Install packages:
9+
`npm i`
10+
11+
## Compile Contracts
12+
`npx hardhat compile`
13+
14+
## Run Tests
15+
`npx hardhat test`
16+
17+
## Vault
18+
The Vault contract handles buying USDG, selling USDG, swapping, increasing positions, decreasing positions and liquidations.
19+
Overview: https://gambit.gitbook.io/gambit/
20+
21+
### Buying USDG
22+
- USDG can be bought with any whitelisted token
23+
- The oracle price is used to determine the amount of USDG that should be minted to the receiver, with 1 USDG being valued at 1 USD
24+
- Fees are collected based on `swapFeeBasisPoints`
25+
- `usdgAmounts` is increased to track the USDG debt of the token
26+
- `poolAmounts` is increased to track the amount of tokens that can be used for swaps or borrowed for margin trading
27+
28+
### Selling USDG
29+
- USDG can be sold for any whitelisted token
30+
- The oracle price is used to determine the amount of tokens that should be sent to the receiver
31+
- For non-stableTokens, the amount of tokens sent out is additionally capped by the redemption collateral
32+
- To calculate the redemption collateral:
33+
- Convert the value in `guaranteedUsd[token]` from USD to tokens
34+
- Add `poolAmounts[token]`
35+
- Subtract `reservedAmounts[token]`
36+
- The reason for this calculation is because traders can open long positions by borrowing non-stable whitelisted tokens, when these tokens are borrowed the USD value in `guaranteedUsd[token]` is guaranteed until the positions are closed or liquidated
37+
- `reservedAmounts[token]` tracks the amount of tokens in the pool reserved for open positions
38+
- The redemption amount is capped by: `(USDG sold) / (USDG debt) * (redemption collateral) * (redemptionBasisPoints[token]) / BASIS_POINTS_DIVISOR`
39+
- redemptionBasisPoints can be adjusted to allow a larger or smaller amount of redemption
40+
- Fees are collected based on `swapFeeBasisPoints`
41+
- `usdgAmounts` is decreased to reduce the USDG debt of the token
42+
- `poolAmounts` is decreased to reflect the reduction in available collateral for redemption
43+
44+
### Swap
45+
- Any whitelisted tokens can be swapped for one another
46+
- The oracle prices are used to determine the amount of tokens that should be sent to the receiver
47+
- USDG debt is transferred from the _tokenOut to the _tokenIn
48+
- Fees are collected based on `swapFeeBasisPoints`
49+
- `poolAmounts` are updated to reflect the change in tokens
50+
51+
### IncreasePosition
52+
- Traders can long and short whitelisted tokens
53+
- For longs, the collateral token must be the same as the index token (the token being longed)
54+
- For shorts, the collateral token must be a stableToken and the index token must not be a stableToken
55+
- For both longs and shorts, the token borrowed from the pool is based on the collateral token
56+
- Fees are collected based on `marginFeeBasisPoints` and funding rates
57+
- Funding rates are calculated based on the `fundingRateFactor` and utilisation of the pool for the token being borrowed
58+
- `reservedAmounts[token]` is increased to ensure there are sufficient tokens to pay profits on the position
59+
- For longs:
60+
- `guaranteedUsd[token]` is updated based on the difference between the position size and the collateral
61+
- `poolAmounts[token]` is increased by the collateral received and considered as part of the pool
62+
- For shorts:
63+
- `guaranteedUsd[token]` is not updated as the collateral token is a stableToken, and no USD amount is additionally guaranteed
64+
- `poolAmounts[token]` is not increased as the collateral is not considered as part of the pool
65+
66+
### DecreasePosition
67+
- `reservedAmounts[token]` is decreased proportional to the decrease in position size
68+
- For longs:
69+
- The `guaranteedUsd[token]` is updated based on the new difference between the position size and the collateral
70+
- `poolAmounts[token]` is decreased by the amount of USD sent out, since the position's collateral and the position's size are treated as a part of the pool
71+
- For shorts:
72+
- `poolAmounts[token]` is decreased if there are realised profits for the position
73+
- `poolAmounts[token]` is increased if there are realised losses for the position
74+
75+
### LiquidatePosition
76+
- Any user can liquidate a position if the remaining collateral after losses is lower than `liquidationFeeUsd` or if the `maxLeverage` is exceeded
77+
- `reservedAmounts[token]` is decreased since it is no longer needed for the position
78+
- For longs:
79+
- `guaranteedUsd[token]` is decreased based on the different between the position size and the collateral
80+
- For shorts:
81+
- `poolAmounts[token]` is increased to reflect the additional collateral from the position's losses
82+
83+
## Front-Running Protection
84+
Oracle results can be known before the result is finalised on-chain.
85+
86+
This means that a trader could observe oracle results in the mempool or otherwise and enter a favourable position before the result is finalised.
87+
88+
Over time, this could lead to losses in assets for the system.
89+
90+
To guard against this attack vector, the last three oracle results are sampled to determine prices.
91+
92+
This reduces the attack surface as minor fluctuations cannot be exploited for profits.
93+
94+
Additionally, a `minProfitBasisPoints` configuration is allowed per token.
95+
96+
If the oracle is updated on every 0.5% price movement, the `minProfitBasisPoints` for the token could be set to 0.75%.
97+
This means that if the profit on a position is less than 0.75%, then the profit would be considered to be 0.
98+
99+
For buying USDG, selling USDG and swaps, a fee of 0.3% would make trades across a 0.5% price movement unprofitable.
100+
101+
## Governance
102+
Governance will be set to a timelock contract which would require actions to be broadcasted 5 days in advance before they can be executed.
103+
104+
This timelock contract will be upgraded to a DAO based contract once the system is stable.

audits/ABDK_Audit_Review.txt

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The major issues raised in the ABDK Audit have been resolved.
2+
3+
1. CVF-42, CVF-51: The mentioned functions have been removed, the intention of these functions was to support future features. We have decided to keep the supported features compact, when new features are needed the new code will be sent for another audit
4+
5+
2. CVF-87: The function is meant to be re-callable, token whitelisting is currently controlled by a Timelock contract with a delay of 5 days: https://bscscan.com/address/0x330EeF6b9B1ea6EDd620C825c9919DC8b611d5d5
6+
7+
3. CVF-90: The returned value was not affecting any behaviour, but for correctness it has been fixed: https://github.com/xvi10/gambit-contracts/blob/master/contracts/core/Vault.sol#L310
8+
9+
4. CVF-130: The spread between prices is assumed to be small, it is large only if the prices are volatile, in which case, a larger spread is desirable to protect the assets in the system

audits/ABDK_Gambit_Solidity.pdf

1.09 MB
Binary file not shown.

contracts/access/Governable.sol

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// SPDX-License-Identifier: MIT
2+
3+
pragma solidity 0.6.12;
4+
5+
contract Governable {
6+
address public gov;
7+
8+
constructor() public {
9+
gov = msg.sender;
10+
}
11+
12+
modifier onlyGov() {
13+
require(msg.sender == gov, "Governable: forbidden");
14+
_;
15+
}
16+
17+
function setGov(address _gov) external onlyGov {
18+
gov = _gov;
19+
}
20+
}

contracts/access/TokenManager.sol

+197
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
//SPDX-License-Identifier: MIT
2+
3+
pragma solidity 0.6.12;
4+
5+
import "../libraries/math/SafeMath.sol";
6+
import "../libraries/token/IERC20.sol";
7+
import "../libraries/token/ERC721/IERC721.sol";
8+
import "../libraries/utils/ReentrancyGuard.sol";
9+
10+
import "../peripherals/interfaces/ITimelock.sol";
11+
12+
contract TokenManager is ReentrancyGuard {
13+
using SafeMath for uint256;
14+
15+
bool public isInitialized;
16+
17+
uint256 public actionsNonce;
18+
uint256 public minAuthorizations;
19+
20+
address public admin;
21+
22+
address[] public signers;
23+
mapping (address => bool) public isSigner;
24+
mapping (bytes32 => bool) public pendingActions;
25+
mapping (address => mapping (bytes32 => bool)) public signedActions;
26+
27+
event SignalApprove(address token, address spender, uint256 amount, bytes32 action, uint256 nonce);
28+
event SignalApproveNFT(address token, address spender, uint256 tokenId, bytes32 action, uint256 nonce);
29+
event SignalApproveNFTs(address token, address spender, uint256[] tokenIds, bytes32 action, uint256 nonce);
30+
event SignalSetAdmin(address target, address admin, bytes32 action, uint256 nonce);
31+
event SignalPendingAction(bytes32 action, uint256 nonce);
32+
event SignAction(bytes32 action, uint256 nonce);
33+
event ClearAction(bytes32 action, uint256 nonce);
34+
35+
constructor(uint256 _minAuthorizations) public {
36+
admin = msg.sender;
37+
minAuthorizations = _minAuthorizations;
38+
}
39+
40+
modifier onlyAdmin() {
41+
require(msg.sender == admin, "TokenManager: forbidden");
42+
_;
43+
}
44+
45+
modifier onlySigner() {
46+
require(isSigner[msg.sender], "TokenManager: forbidden");
47+
_;
48+
}
49+
50+
function initialize(address[] memory _signers) public virtual onlyAdmin {
51+
require(!isInitialized, "TokenManager: already initialized");
52+
isInitialized = true;
53+
54+
signers = _signers;
55+
for (uint256 i = 0; i < _signers.length; i++) {
56+
address signer = _signers[i];
57+
isSigner[signer] = true;
58+
}
59+
}
60+
61+
function signersLength() public view returns (uint256) {
62+
return signers.length;
63+
}
64+
65+
function signalApprove(address _token, address _spender, uint256 _amount) external nonReentrant onlyAdmin {
66+
actionsNonce++;
67+
uint256 nonce = actionsNonce;
68+
bytes32 action = keccak256(abi.encodePacked("approve", _token, _spender, _amount, nonce));
69+
_setPendingAction(action, nonce);
70+
emit SignalApprove(_token, _spender, _amount, action, nonce);
71+
}
72+
73+
function signApprove(address _token, address _spender, uint256 _amount, uint256 _nonce) external nonReentrant onlySigner {
74+
bytes32 action = keccak256(abi.encodePacked("approve", _token, _spender, _amount, _nonce));
75+
_validateAction(action);
76+
require(!signedActions[msg.sender][action], "TokenManager: already signed");
77+
signedActions[msg.sender][action] = true;
78+
emit SignAction(action, _nonce);
79+
}
80+
81+
function approve(address _token, address _spender, uint256 _amount, uint256 _nonce) external nonReentrant onlyAdmin {
82+
bytes32 action = keccak256(abi.encodePacked("approve", _token, _spender, _amount, _nonce));
83+
_validateAction(action);
84+
_validateAuthorization(action);
85+
86+
IERC20(_token).approve(_spender, _amount);
87+
_clearAction(action, _nonce);
88+
}
89+
90+
function signalApproveNFT(address _token, address _spender, uint256 _tokenId) external nonReentrant onlyAdmin {
91+
actionsNonce++;
92+
uint256 nonce = actionsNonce;
93+
bytes32 action = keccak256(abi.encodePacked("approveNFT", _token, _spender, _tokenId, nonce));
94+
_setPendingAction(action, nonce);
95+
emit SignalApproveNFT(_token, _spender, _tokenId, action, nonce);
96+
}
97+
98+
function signApproveNFT(address _token, address _spender, uint256 _tokenId, uint256 _nonce) external nonReentrant onlySigner {
99+
bytes32 action = keccak256(abi.encodePacked("approveNFT", _token, _spender, _tokenId, _nonce));
100+
_validateAction(action);
101+
require(!signedActions[msg.sender][action], "TokenManager: already signed");
102+
signedActions[msg.sender][action] = true;
103+
emit SignAction(action, _nonce);
104+
}
105+
106+
function approveNFT(address _token, address _spender, uint256 _tokenId, uint256 _nonce) external nonReentrant onlyAdmin {
107+
bytes32 action = keccak256(abi.encodePacked("approveNFT", _token, _spender, _tokenId, _nonce));
108+
_validateAction(action);
109+
_validateAuthorization(action);
110+
111+
IERC721(_token).approve(_spender, _tokenId);
112+
_clearAction(action, _nonce);
113+
}
114+
115+
function signalApproveNFTs(address _token, address _spender, uint256[] memory _tokenIds) external nonReentrant onlyAdmin {
116+
actionsNonce++;
117+
uint256 nonce = actionsNonce;
118+
bytes32 action = keccak256(abi.encodePacked("approveNFTs", _token, _spender, _tokenIds, nonce));
119+
_setPendingAction(action, nonce);
120+
emit SignalApproveNFTs(_token, _spender, _tokenIds, action, nonce);
121+
}
122+
123+
function signApproveNFTs(address _token, address _spender, uint256[] memory _tokenIds, uint256 _nonce) external nonReentrant onlySigner {
124+
bytes32 action = keccak256(abi.encodePacked("approveNFTs", _token, _spender, _tokenIds, _nonce));
125+
_validateAction(action);
126+
require(!signedActions[msg.sender][action], "TokenManager: already signed");
127+
signedActions[msg.sender][action] = true;
128+
emit SignAction(action, _nonce);
129+
}
130+
131+
function approveNFTs(address _token, address _spender, uint256[] memory _tokenIds, uint256 _nonce) external nonReentrant onlyAdmin {
132+
bytes32 action = keccak256(abi.encodePacked("approveNFTs", _token, _spender, _tokenIds, _nonce));
133+
_validateAction(action);
134+
_validateAuthorization(action);
135+
136+
for (uint256 i = 0 ; i < _tokenIds.length; i++) {
137+
IERC721(_token).approve(_spender, _tokenIds[i]);
138+
}
139+
_clearAction(action, _nonce);
140+
}
141+
142+
function signalSetAdmin(address _target, address _admin) external nonReentrant onlySigner {
143+
actionsNonce++;
144+
uint256 nonce = actionsNonce;
145+
bytes32 action = keccak256(abi.encodePacked("setAdmin", _target, _admin, nonce));
146+
_setPendingAction(action, nonce);
147+
signedActions[msg.sender][action] = true;
148+
emit SignalSetAdmin(_target, _admin, action, nonce);
149+
}
150+
151+
function signSetAdmin(address _target, address _admin, uint256 _nonce) external nonReentrant onlySigner {
152+
bytes32 action = keccak256(abi.encodePacked("setAdmin", _target, _admin, _nonce));
153+
_validateAction(action);
154+
require(!signedActions[msg.sender][action], "TokenManager: already signed");
155+
signedActions[msg.sender][action] = true;
156+
emit SignAction(action, _nonce);
157+
}
158+
159+
function setAdmin(address _target, address _admin, uint256 _nonce) external nonReentrant onlySigner {
160+
bytes32 action = keccak256(abi.encodePacked("setAdmin", _target, _admin, _nonce));
161+
_validateAction(action);
162+
_validateAuthorization(action);
163+
164+
ITimelock(_target).setAdmin(_admin);
165+
_clearAction(action, _nonce);
166+
}
167+
168+
function _setPendingAction(bytes32 _action, uint256 _nonce) private {
169+
pendingActions[_action] = true;
170+
emit SignalPendingAction(_action, _nonce);
171+
}
172+
173+
function _validateAction(bytes32 _action) private view {
174+
require(pendingActions[_action], "TokenManager: action not signalled");
175+
}
176+
177+
function _validateAuthorization(bytes32 _action) private view {
178+
uint256 count = 0;
179+
for (uint256 i = 0; i < signers.length; i++) {
180+
address signer = signers[i];
181+
if (signedActions[signer][_action]) {
182+
count++;
183+
}
184+
}
185+
186+
if (count == 0) {
187+
revert("TokenManager: action not authorized");
188+
}
189+
require(count >= minAuthorizations, "TokenManager: insufficient authorization");
190+
}
191+
192+
function _clearAction(bytes32 _action, uint256 _nonce) private {
193+
require(pendingActions[_action], "TokenManager: invalid _action");
194+
delete pendingActions[_action];
195+
emit ClearAction(_action, _nonce);
196+
}
197+
}

0 commit comments

Comments
 (0)