Skip to content

Instantly share code, notes, and snippets.

@tangert
Last active January 13, 2022 19:35
Show Gist options
  • Save tangert/1eceaf04f2877d84fb0e10681b39d7e3 to your computer and use it in GitHub Desktop.
Save tangert/1eceaf04f2877d84fb0e10681b39d7e3 to your computer and use it in GitHub Desktop.
Solidity SVG + Hardhat Hot Reloading Server
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract Renderer {
constructor() {
console.log("Deploying render test");
}
function render() public view returns (string memory) {
string memory ownerAddress = Strings.toHexString(
uint256(uint160(msg.sender))
);
return
string(
abi.encodePacked(
'<svg xmlns="http://www.w3.org/2000/svg" width="360" height="360">',
'<rect x="0" y="0" width="100%" height="100%" fill="blue"></rect>',
'<text x="20" y="40" fill="white" font-size="20px">',
ownerAddress,
"</text>",
"</svg>"
)
);
}
}
// Extremely naive implementation of "hot reloading" (basically just autorefreshing) a web server that compiles a solidity contract with Hardhat, then outputs the rendered string into HTML.
// This file should be placed into the "scripts" folder inside of your standard Hardhat project.
const express = require('express')
const hre = require('hardhat')
const app = express()
app.get('/', async (_, res) => {
try {
// will recompile if there are changes
await hre.run('compile')
// Grab SVG content from renderer
const Renderer = await hre.ethers.getContractFactory('Renderer')
const renderer = await Renderer.deploy()
await renderer.deployed()
const toRender = await renderer.render()
// Will refresh every 1 second
res.send(`
<html>
<head>
<meta http-equiv="refresh" content="1">
</head>
<body>
${toRender}
</body>
<style>body{margin:0;padding:0;}</style>
</html>
`)
} catch (e) {
// in case you grab compiler errors
res.send(`
<html>
<head>
<meta http-equiv="refresh" content="1">
</head>
${e}
</html>
`)
}
})
app.listen(3000, () => {
console.log('server started')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment