-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathSvgnftContract.sol
84 lines (71 loc) · 2.82 KB
/
SvgnftContract.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
// 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 SvgNft is ERC721, Ownable {
uint256 private s_tokenCounter;
string private s_ImageURI;
mapping(uint256 => int256) private s_tokenIdToHighValues;
event CreatedNFT(uint256 indexed tokenId);
constructor(string memory Svg) ERC721("Dynamic SVG NFT", "DSN") {
s_tokenCounter = 0;
s_ImageURI = svgToImageURI(Svg);
}
function safeMintNFT() public {
_safeMint(msg.sender, s_tokenCounter);
s_tokenCounter = s_tokenCounter + 1;
emit CreatedNFT(s_tokenCounter, highValue);
}
// You could also just upload the raw SVG and have solildity convert it!
function svgToImageURI(
string memory svg
) public pure returns (string memory) {
// example:
// '<svg width="500" height="500" viewBox="0 0 285 350" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill="black" d="M150,0,L75,200,L225,200,Z"></path></svg>'
// would return ""
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();
}
string memory imageURI = s_ImageURI;
return
string(
abi.encodePacked(
_baseURI(),
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name(), // You can add whatever name here
'", "description":"An NFT that changes based on the Chainlink Feed", ',
'"attributes": [{"trait_type": "coolness", "value": 100}], "image":"',
imageURI,
'"}'
)
)
)
)
);
}
function getSVG() public view returns (string memory) {
return s_ImageURI;
}
function getTokenCounter() public view returns (uint256) {
return s_tokenCounter;
}
}