-
Couldn't load subscription status.
- Fork 3.3k
-
Currently there are no tests for these functions in the test file for the DynamicSvgNft contract. I did some research and came up with a couple of functions to create the image and token URIs off-chain using ethers@^5.5.4. These are the functions:
createImageUrifunction:
const createImageUri = (svg) => { const baseImageUri = "data:image/svg+xml;base64," const solidityEncodePacked = ethers.utils.solidityPack(["string"], [svg]) // equivalent to `bytes(string(abi.encodePack(svg)))` const base64Encode = ethers.utils.base64.encode(solidityEncodePacked) // equivalent to `Base64.encode(bytes(string(abi.encodePacked(svg))))` // equivalent to `abi.encodePacked(baseURL, svgBase64Encoded)` const bytesImageUri = ethers.utils.solidityPack( ["string", "string"], [baseImageUri, base64Encode] ) const stringImageUri = ethers.utils.toUtf8String(bytesImageUri) // equivalent to typecasting the result to string as shown in the contract: `string(abi.encodePacked(baseURL, svgBase64Encoded))` return stringImageUri }
createTokenUrifunction:
const createTokenUri = (name, imageUri) => { const baseTokenUri = "data:application/json;base64," const solidityEncodePacked = ethers.utils.solidityPack( ["string", "string", "string", "string", "string", "string"], [ '{"name":"', name, '", "description":"An NFT that changes based on the Chainlink Feed", ', '"attributes": [{"trait_type": "coolness", "value": 100}], "image":"', imageUri, '"}', ] ) const base64Encode = ethers.utils.base64.encode(solidityEncodePacked) const bytesTokenUri = ethers.utils.solidityPack( ["string", "string"], [baseTokenUri, base64Encode] ) const stringTokenUri = ethers.utils.toUtf8String(bytesTokenUri) return stringTokenUri }
Possible implementation:
To avoid polluting the test file I would create a createUris.js file inside the utils folder with the functions in it and import them from there.
At the beginning of the test suite I would read both svg files:
const lowSvg = fs.readFileSync("./images/dynamicNft/frown.svg", { encoding: "utf8" }) const highSvg = fs.readFileSync("./images/dynamicNft/happy.svg", { encoding: "utf8" })
Finally in any test case I would call the functions and pass the arguments, example:
// ... const tokenURI = await dynamicSvgNft.tokenURI(0) // after minting NFT const highImageUri = createImageUri(highSvg) // create image URI const highTokenUri = createTokenUri("Dynamic SVG NFT", highImageUri) // create token URI by passing the image URI assert.equal(tokenURI, highTokenUri) // assert
Hopefully the comments aren't too complex to understand and this post might serve as a reference for future readers that could be interested in testing these functions.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1