-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicSvgNft.sol
97 lines (81 loc) · 3.29 KB
/
DynamicSvgNft.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "base64-sol/base64.sol";
import "hardhat/console.sol";
error ERC721Metadata__URI_QueryFor_NonExistentToken();
contract DynamicSvgNft is ERC721, Ownable {
uint256 private s_tokenCounter;
string private s_lowImageURI;
string private s_highImageURI;
mapping(uint256 => int256) private s_tokenIdToHighValues;
AggregatorV3Interface internal immutable i_priceFeed;
event CreatedNFT(uint256 indexed tokenId, int256 highValue);
constructor(
address priceFeedAddress,
string memory lowSvg,
string memory highSvg
) ERC721("Dynamic SVG NFT", "DSN") {
s_tokenCounter = 0;
i_priceFeed = AggregatorV3Interface(priceFeedAddress);
// setLowSVG(lowSvg);
// setHighSVG(highSvg);
s_lowImageURI = svgToImageURI(lowSvg);
s_highImageURI = svgToImageURI(highSvg);
}
function mintNft(int256 highValue) public {
s_tokenIdToHighValues[s_tokenCounter] = highValue;
_safeMint(msg.sender, s_tokenCounter);
s_tokenCounter = s_tokenCounter + 1;
emit CreatedNFT(s_tokenCounter, highValue);
}
string memory baseURL = "data:image/svg+xml;base64,";
string memory svgBase64Encoded = Base64.encode(bytes(string(abi.encodePacked(svg))));
return string(abi.encodePacked(baseURL, svgBase64Encoded));
}
function _baseURI() internal pure override returns (string memory) {
return "data:application/json;base64,";
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) {
revert ERC721Metadata__URI_QueryFor_NonExistentToken();
}
(, int256 price, , , ) = i_priceFeed.latestRoundData();
string memory imageURI = s_lowImageURI;
if (price >= s_tokenIdToHighValues[tokenId]) {
imageURI = s_highImageURI;
}
return
string(
abi.encodePacked(
_baseURI(),
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name(),
'", "description":"An NFT that changes based on the Chainlink Feed", ',
'"attributes": [{"trait_type": "coolness", "value": 100}], "image":"',
imageURI,
'"}'
)
)
)
)
);
}
function getLowSVG() public view returns (string memory) {
return s_lowImageURI;
}
function getHighSVG() public view returns (string memory) {
return s_highImageURI;
}
function getPriceFeed() public view returns (AggregatorV3Interface) {
return i_priceFeed;
}
function getTokenCounter() public view returns (uint256) {
return s_tokenCounter;
}
}