Blockchain DevOps and CI/CD
Blockchain DevOps combines traditional software engineering practices with blockchain-specific requirements for reliable smart contract development and deployment.
CI/CD Pipeline Architecture
GitHub Actions Configuration
# .github/workflows/ci.yml
name: Smart Contract CI/CD
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
- name: Run Slither
uses: crytic/[email protected]
with:
sarif: slither.sarif
- name: Run Solhint
run: forge fmt --check
test:
runs-on: ubuntu-latest
needs: lint
steps:
- uses: actions/checkout@v3
- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
- name: Run Tests
run: forge test -vvv --gas-report
- name: Run Coverage
run: forge coverage --report lcov
- name: Upload Coverage
uses: codecov/codecov-action@v3
deploy-testnet:
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
- name: Deploy to Goerli
run: |
forge script script/Deploy.s.sol \
--rpc-url ${{ secrets.GOERLI_RPC_URL }} \
--private-key ${{ secrets.GOERLI_PRIVATE_KEY }} \
--verify
env:
ETHERSCAN_API_KEY: ${{ secrets.ETHERSCAN_API_KEY }}
deploy-mainnet:
runs-on: ubuntu-latest
needs: deploy-testnet
if: github.ref == 'refs/heads/main'
environment: production
steps:
- uses: actions/checkout@v3
- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
- name: Deploy to Mainnet
run: |
forge script script/Deploy.s.sol \
--rpc-url ${{ secrets.MAINNET_RPC_URL }} \
--private-key ${{ secrets.MAINNET_PRIVATE_KEY }} \
--verify
env:
ETHERSCAN_API_KEY: ${{ secrets.ETHERSCAN_API_KEY }}
Automated Deployment
Deployment Script
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Script.sol";
import "../src/MyContract.sol";
contract DeployScript is Script {
function run() external returns (MyContract) {
uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
vm.startBroadcast(deployerPrivateKey);
MyContract myContract = new MyContract(
vm.envAddress("INITIALIZER"),
vm.envUint("INITIAL_VALUE")
);
vm.stopBroadcast();
console.log("MyContract deployed at:", address(myContract));
return myContract;
}
}
Deployment Checklist
| Step | Verification | Status |
|---|---|---|
| Code Review | Approved | â |
| Tests Passing | 100% | â |
| Gas Optimization | Within limits | â |
| Security Audit | Completed | â |
| Testnet Deploy | Verified | â |
| Mainnet Deploy | Executed | â |
| Post-Deploy Verify | Confirmed | â |
Monitoring and Alerting
Contract Monitoring
// monitoring/monitor.js
import { ethers } from 'ethers';
class ContractMonitor {
constructor(provider, contractAddress, abi) {
this.provider = provider;
this.contract = new ethers.Contract(contractAddress, abi, provider);
this.alerts = [];
}
async startMonitoring() {
// Monitor events
this.contract.on('Transfer', async (from, to, amount) => {
console.log(`Transfer: ${from} -> ${to}: ${amount}`);
if (amount > ethers.parseEther('1000')) {
await this.sendAlert('Large Transfer', {
from,
to,
amount: ethers.formatEther(amount)
});
}
});
// Monitor gas prices
this.provider.on('block', async (blockNumber) => {
const block = await this.provider.getBlock(blockNumber);
const gasPrice = block.gasPrice;
if (gasPrice > ethers.parseUnits('100', 'gwei')) {
await this.sendAlert('High Gas Price', {
blockNumber,
gasPrice: ethers.formatUnits(gasPrice, 'gwei')
});
}
});
// Monitor contract balance
setInterval(async () => {
const balance = await this.provider.getBalance(
this.contract.target
);
if (balance < ethers.parseEther('1')) {
await this.sendAlert('Low Contract Balance', {
balance: ethers.formatEther(balance)
});
}
}, 60000);
}
async sendAlert(title, data) {
console.log(`ALERT: ${title}`, data);
// Send to Slack, Discord, or PagerDuty
await fetch(process.env.ALERT_WEBHOOK, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title,
data,
timestamp: new Date().toISOString()
})
});
}
}
Alerting Configuration
# alerts/config.yml
alerts:
- name: "Large Transfer"
condition: "amount > 1000 ETH"
channels:
- slack
- email
severity: "high"
- name: "High Gas Price"
condition: "gasPrice > 100 gwei"
channels:
- slack
severity: "medium"
- name: "Low Contract Balance"
condition: "balance < 1 ETH"
channels:
- pagerduty
- email
severity: "critical"
- name: "Failed Transaction"
condition: "status == 'reverted'"
channels:
- slack
- pagerduty
severity: "high"
Incident Response
Incident Response Playbook
Emergency Pause Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract EmergencyPause is Pausable, AccessControl {
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
constructor() {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(EMERGENCY_ROLE, msg.sender);
}
function emergencyPause() external onlyRole(EMERGENCY_ROLE) {
_pause();
emit EmergencyPaused(msg.sender, block.timestamp);
}
function emergencyUnpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
emit EmergencyUnpaused(msg.sender, block.timestamp);
}
modifier whenNotPaused() {
require(!paused(), "Contract is paused");
_;
}
// Critical functions with pause modifier
function transfer(address to, uint256 amount) external whenNotPaused {
// Transfer logic
}
function withdraw() external whenNotPaused {
// Withdraw logic
}
}
Key Management
Multi-Signature Key Management
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract KeyManager {
struct Key {
bytes32 publicKey;
uint8 keyType;
bool active;
uint256 addedAt;
uint256 expiresAt;
}
mapping(address => Key[]) public keys;
mapping(address => mapping(bytes32 => bool)) public keyOwners;
uint256 public constant KEY_EXPIRY = 90 days;
function addKey(
bytes32 publicKey,
uint8 keyType
) external {
keys[msg.sender].push(Key({
publicKey: publicKey,
keyType: keyType,
active: true,
addedAt: block.timestamp,
expiresAt: block.timestamp + KEY_EXPIRY
}));
keyOwners[msg.sender][publicKey] = true;
emit KeyAdded(msg.sender, publicKey, keyType);
}
function revokeKey(uint256 index) external {
require(index < keys[msg.sender].length, "Invalid index");
keys[msg.sender][index].active = false;
emit KeyRevoked(msg.sender, index);
}
function isKeyValid(
address account,
bytes32 publicKey
) external view returns (bool) {
Key[] memory accountKeys = keys[account];
for (uint256 i = 0; i < accountKeys.length; i++) {
if (
accountKeys[i].publicKey == publicKey &&
accountKeys[i].active &&
block.timestamp < accountKeys[i].expiresAt
) {
return true;
}
}
return false;
}
}
Multi-Chain Deployment
Cross-Chain Deployment Script
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Script.sol";
contract MultiChainDeploy is Script {
struct ChainConfig {
uint256 chainId;
string rpcUrl;
address deployer;
}
function run() external {
ChainConfig[] memory chains = new ChainConfig[](3);
chains[0] = ChainConfig(1, "mainnet", 0x1234...);
chains[1] = ChainConfig(137, "polygon", 0x5678...);
chains[2] = ChainConfig(42161, "arbitrum", 0x9ABC...);
for (uint256 i = 0; i < chains.length; i++) {
_deployToChain(chains[i]);
}
}
function _deployToChain(ChainConfig memory config) internal {
vm.createSelectFork(config.rpcUrl);
vm.startBroadcast(config.deployer);
MyContract contract = new MyContract();
vm.stopBroadcast();
console.log(
"Deployed to chain",
config.chainId,
"at",
address(contract)
);
}
}
Multi-Chain Configuration
# deployment/config.yml
networks:
ethereum:
chainId: 1
rpc: ${ETHEREUM_RPC_URL}
deployer: ${ETHEREUM_DEPLOYER}
verify: true
polygon:
chainId: 137
rpc: ${POLYGON_RPC_URL}
deployer: ${POLYGON_DEPLOYER}
verify: true
arbitrum:
chainId: 42161
rpc: ${ARBITRUM_RPC_URL}
deployer: ${ARBITRUM_DEPLOYER}
verify: true
optimism:
chainId: 10
rpc: ${OPTIMISM_RPC_URL}
deployer: ${OPTIMISM_DEPLOYER}
verify: true
contracts:
MyContract:
name: "MyContract"
version: "1.0.0"
constructor_args:
- ${INITIALIZER_ADDRESS}
- ${INITIAL_VALUE}
Trade-offs
| Aspect | Centralized | Decentralized | Hybrid |
|---|---|---|---|
| Speed | Fast | Slow | Medium |
| Cost | Low | High | Medium |
| Security | Medium | High | High |
| Complexity | Low | High | Medium |
| Control | High | Low | Medium |
Real-World Example: Aave Deployment
Aave uses a sophisticated deployment pipeline:
// Simplified Aave deployment
async function deployAave() {
// 1. Deploy implementation
const LendingPool = await deployContract('LendingPool');
// 2. Deploy proxy admin
const ProxyAdmin = await deployContract('ProxyAdmin');
// 3. Deploy proxy
const Proxy = await deployContract('TransparentUpgradeableProxy', [
LendingPool.address,
ProxyAdmin.address,
'0x' // initialization data
]);
// 4. Verify contracts
await verifyContract(LendingPool.address);
await verifyContract(ProxyAdmin.address);
await verifyContract(Proxy.address);
// 5. Transfer ownership
await ProxyAdmin.transferOwnership(MULTISIG_ADDRESS);
console.log('Aave deployed successfully');
console.log('Proxy:', Proxy.address);
}
Interview Questions
-
Design a CI/CD pipeline for smart contracts that includes automated testing, security analysis, and staged deployment to testnet and mainnet.
-
How would you implement incident response for a compromised smart contract? What are the key steps and considerations?
-
Explain the challenges of multi-chain deployment and how to ensure consistent contract addresses across different networks.
Quiz Questions
-
What is the primary purpose of a CI/CD pipeline in smart contract development?
- A) Increase gas efficiency
- B) Automate testing and deployment
- C) Reduce code complexity
- D) Improve security
-
Which tool is commonly used for static analysis of Solidity code?
- A) Hardhat
- B) Slither
- C) Web3.js
- D) Remix
-
What is the recommended approach for deploying contracts to multiple chains?
- A) Deploy to each chain manually
- B) Use CREATE2 for deterministic addresses
- C) Use a factory contract
- D) All of the above