-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefifaTokenUriResolver.sol
288 lines (250 loc) · 13.8 KB
/
DefifaTokenUriResolver.sol
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import "lib/base64/base64.sol";
import {PRBMath} from "@paulrberg/contracts/math/PRBMath.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {JBTokens} from "@jbx-protocol/juice-contracts-v3/contracts/libraries/JBTokens.sol";
import {IJB721TokenUriResolver} from "@jbx-protocol/juice-721-delegate/contracts/interfaces/IJB721TokenUriResolver.sol";
import {JBIpfsDecoder} from "@jbx-protocol/juice-721-delegate/contracts/libraries/JBIpfsDecoder.sol";
import {JB721Tier} from "@jbx-protocol/juice-721-delegate/contracts/structs/JB721Tier.sol";
import {ITypeface} from "lib/typeface/contracts/interfaces/ITypeface.sol";
import {IDefifaDelegate} from "./interfaces/IDefifaDelegate.sol";
import {IDefifaTokenUriResolver} from "./interfaces/IDefifaTokenUriResolver.sol";
import {DefifaFontImporter} from "./libraries/DefifaFontImporter.sol";
import {DefifaGamePhase} from "./enums/DefifaGamePhase.sol";
/// @title DefifaTokenUriResolver
/// @notice Standard Token URIs for Defifa games.
contract DefifaTokenUriResolver is IDefifaTokenUriResolver, IJB721TokenUriResolver {
using Strings for uint256;
using SafeMath for uint256;
//*********************************************************************//
// -------------------- private constant properties ------------------ //
//*********************************************************************//
/// @notice The fidelity of the decimal returned in the NFT image.
uint256 private constant _IMG_DECIMAL_FIDELITY = 3;
//*********************************************************************//
// --------------- public immutable stored properties ---------------- //
//*********************************************************************//
/// @notice The typeface of the SVGs.
ITypeface public immutable override typeface;
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
constructor(ITypeface _typeface) {
typeface = _typeface;
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/// @notice The metadata URI of the provided token ID.
/// @dev Defer to the token's tier IPFS URI if set.
/// @param _nft The address of the nft the token URI should be oriented to.
/// @param _tokenId The ID of the token to get the tier URI for.
/// @return The token URI corresponding with the tier.
function tokenUriOf(address _nft, uint256 _tokenId) external view override returns (string memory) {
// Keep a reference to the delegate.
IDefifaDelegate _delegate = IDefifaDelegate(_nft);
// Get the game ID.
uint256 _gameId = _delegate.projectId();
// Keep a reference to the game phase text.
string memory _gamePhaseText;
// Keep a reference to the rarity text;
string memory _rarityText;
// Keep a reference to the rarity text;
string memory _valueText;
// Keep a reference to the game's name.
string memory _title = _delegate.name();
// Keep a reference to the tier's name.
string memory _team;
// Keep a reference to the SVG parts.
string[] memory parts = new string[](4);
// Keep a reference to the pot.
string memory _potText;
{
// Get a reference to the tier.
JB721Tier memory _tier = _delegate.store().tierOfTokenId(address(_delegate), _tokenId, false);
// Set the tier's name.
_team = _delegate.tierNameOf(_tier.id);
// Check to see if the tier has a URI. Return it if it does.
if (_tier.encodedIPFSUri != bytes32(0)) {
return JBIpfsDecoder.decode(_delegate.baseURI(), _tier.encodedIPFSUri);
}
parts[0] = string("data:application/json;base64,");
parts[1] = string(
abi.encodePacked(
'{"name":"',
_team,
'", "id": "',
_tier.id.toString(),
'","description":"Team: ',
_team,
", ID: ",
_tier.id.toString(),
'.","image":"data:image/svg+xml;base64,'
)
);
{
// Get a reference to the game phase.
DefifaGamePhase _gamePhase = _delegate.gamePhaseReporter().currentGamePhaseOf(_gameId);
// Keep a reference to the game pot.
(uint256 _gamePot, address _gamePotToken, uint256 _gamePotDecimals) =
_delegate.gamePotReporter().currentGamePotOf(_gameId, false);
// Include the amount redeemed.
_gamePot = _gamePot + _delegate.amountRedeemed();
// Set the pot text.
_potText = _formatBalance(_gamePot, _gamePotToken, _gamePotDecimals, _IMG_DECIMAL_FIDELITY);
if (_gamePhase == DefifaGamePhase.NO_CONTEST) {
_gamePhaseText = "No contest. Refunds open.";
} else if (_gamePhase == DefifaGamePhase.NO_CONTEST_INEVITABLE) {
_gamePhaseText = "No contest inevitable. Refunds open.";
} else if (_gamePhase == DefifaGamePhase.COUNTDOWN) {
_gamePhaseText = "Minting starts soon.";
} else if (_gamePhase == DefifaGamePhase.MINT) {
_gamePhaseText = "Minting and refunds are open.";
} else if (_gamePhase == DefifaGamePhase.REFUND) {
_gamePhaseText = "Minting is over. Refunds are ending.";
} else if (_gamePhase == DefifaGamePhase.SCORING) {
_gamePhaseText = "Awaiting scorecard approval.";
} else if (_gamePhase == DefifaGamePhase.COMPLETE) {
_gamePhaseText = "Scorecard locked in. Burn to claim reward.";
}
// Keep a reference to the number of tokens outstanding from this tier.
uint256 _totalMinted = _tier.initialQuantity - _tier.remainingQuantity;
if (_gamePhase == DefifaGamePhase.MINT) {
_rarityText = string(
abi.encodePacked(_totalMinted.toString(), _totalMinted == 1 ? " card so far" : " cards so far")
);
} else {
_rarityText = string(
abi.encodePacked(
_totalMinted.toString(), _totalMinted == 1 ? " card in existence" : " cards in existence"
)
);
}
if (_gamePhase == DefifaGamePhase.SCORING || _gamePhase == DefifaGamePhase.COMPLETE) {
uint256 _potPortion = PRBMath.mulDiv(
_gamePot, _delegate.redemptionWeightOf(_tokenId), _delegate.TOTAL_REDEMPTION_WEIGHT()
);
_valueText = !_delegate.redemptionWeightIsSet()
? "Awaiting scorecard..."
: _formatBalance(_potPortion, _gamePotToken, _gamePotDecimals, _IMG_DECIMAL_FIDELITY);
} else {
_valueText = _formatBalance(_tier.price, _gamePotToken, _gamePotDecimals, _IMG_DECIMAL_FIDELITY);
}
}
}
parts[2] = Base64.encode(
abi.encodePacked(
'<svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">',
'<style>@font-face{font-family:"Capsules-500";src:url(data:font/truetype;charset=utf-8;base64,',
DefifaFontImporter.getSkinnyFontSource(typeface),
');format("opentype");}',
'@font-face{font-family:"Capsules-700";src:url(data:font/truetype;charset=utf-8;base64,',
DefifaFontImporter.getBeefyFontSource(typeface),
');format("opentype");}',
"text{white-space:pre-wrap; width:100%; }</style>",
'<rect width="100%" height="100%" fill="#181424"/>',
'<text x="10" y="30" style="font-size:16px; font-family: Capsules-500; font-weight:500; fill: #c0b3f1;">GAME: ',
_gameId.toString(),
" | POT: ",
_potText,
" | CARDS: ",
_delegate.store().totalSupplyOf(address(_delegate)).toString(),
"</text>",
'<text x="10" y="50" style="font-size:16px; font-family: Capsules-500; font-weight:500; fill: #ed017c;">',
_gamePhaseText,
"</text>",
'<text x="10" y="85" style="font-size:26px; font-family: Capsules-500; font-weight:500; fill: #c0b3f1;">',
_getSubstring(_title, 0, 30),
"</text>",
'<text x="10" y="120" style="font-size:26px; font-family: Capsules-500; font-weight:500; fill: #c0b3f1;">',
_getSubstring(_title, 30, 60),
"</text>",
'<text x="10" y="205" style="font-size:80px; font-family: Capsules-700; font-weight:700; fill: #fea282;">',
bytes(_getSubstring(_team, 20, 30)).length != 0 && bytes(_getSubstring(_team, 10, 20)).length != 0
? _getSubstring(_team, 0, 10)
: "",
"</text>",
'<text x="10" y="295" style="font-size:80px; font-family: Capsules-700; font-weight:700; fill: #fea282;">',
bytes(_getSubstring(_team, 20, 30)).length != 0
? _getSubstring(_team, 10, 20)
: bytes(_getSubstring(_team, 10, 20)).length != 0 ? _getSubstring(_team, 0, 10) : "",
"</text>",
'<text x="10" y="385" style="font-size:80px; font-family: Capsules-700; font-weight:700; fill: #fea282;">',
bytes(_getSubstring(_team, 20, 30)).length != 0
? _getSubstring(_team, 20, 30)
: bytes(_getSubstring(_team, 10, 20)).length != 0
? _getSubstring(_team, 10, 20)
: _getSubstring(_team, 0, 10),
"</text>",
'<text x="10" y="430" style="font-size:16px; font-family: Capsules-500; font-weight:500; fill: #c0b3f1;">TOKEN ID: ',
_tokenId.toString(),
"</text>",
'<text x="10" y="455" style="font-size:16px; font-family: Capsules-500; font-weight:500; fill: #c0b3f1;">RARITY: ',
_rarityText,
"</text>",
'<text x="10" y="480" style="font-size:16px; font-family: Capsules-500; font-weight:500; fill: #c0b3f1;">BACKED BY: ',
_valueText,
"</text>",
"</svg>"
)
);
parts[3] = string('"}');
return string.concat(parts[0], Base64.encode(abi.encodePacked(parts[1], parts[2], parts[3])));
}
/// @notice Gets a substring.
/// @dev If the first character is a space, it is not included.
/// @param _str The string to get a substring of.
/// @param _startIndex The first index of the substring from within the string.
/// @param _endIndex The last index of the string from within the string.
/// @return substring The substring.
function _getSubstring(string memory _str, uint256 _startIndex, uint256 _endIndex)
internal
pure
returns (string memory substring)
{
bytes memory _strBytes = bytes(_str);
if (_startIndex >= _strBytes.length) return "";
if (_endIndex > _strBytes.length) _endIndex = _strBytes.length;
_startIndex = _strBytes[_startIndex] == bytes1(0x20) ? _startIndex + 1 : _startIndex;
if (_startIndex >= _endIndex) return "";
bytes memory _result = new bytes(_endIndex-_startIndex);
for (uint256 _i = _startIndex; _i < _endIndex;) {
_result[_i - _startIndex] = _strBytes[_i];
unchecked {
++_i;
}
}
return string(_result);
}
/// @notice Formats a balance from a fixed point number to a string.
/// @param _amount The fixed point amount.
/// @param _token The token the amount is in.
/// @param _decimals The number of decimals in the fixed point amount.
/// @param _fidelity The number of decimals that should be returned in the formatted string.
/// @return The formatted balance.
function _formatBalance(uint256 _amount, address _token, uint256 _decimals, uint256 _fidelity)
internal
view
returns (string memory)
{
bool _isEth = _token == JBTokens.ETH;
uint256 _fixedPoint = 10 ** _decimals;
// Convert amount to a decimal format
string memory _integerPart = _amount.div(_fixedPoint).toString();
uint256 _remainder = _amount.mod(_fixedPoint);
uint256 _scaledRemainder = _remainder.mul(10 ** _fidelity);
uint256 _decimalPart = _scaledRemainder.div(_fixedPoint);
// Pad with zeros if necessary
string memory _decimalPartStr = _decimalPart.toString();
while (bytes(_decimalPartStr).length < _fidelity) {
_decimalPartStr = string(abi.encodePacked("0", _decimalPartStr));
}
// Concatenate the strings
return _isEth
? string(abi.encodePacked("\u039E", _integerPart, ".", _decimalPartStr))
: string(abi.encodePacked(_integerPart, ".", _decimalPartStr, " ", IERC20Metadata(_token).symbol()));
}
}