Smart Contract Migration Scripts: Avoid Data Loss
After deployment, a smart contract cannot be changed. But data can be moved. Developers often face a situation where a contract wasn't designed upgradeable, yet logic must change. Or data needs to be migrated to a new contract due to protocol changes. Without proper migration, user funds can be lost or integrations broken. Migration is an operation that requires state integrity and rollback capability. Every migration undergoes mandatory testing on a mainnet fork, catching issues before deployment. We use Foundry for simulation and Slither for storage layout checks. Gas savings with lazy migration reach 90% (saving up to $38,000 for a 10,000-user protocol) compared to direct data loading. Such migration requires automation and thorough testing.
How to Migrate Smart Contract Data Without Loss
There are two fundamentally different approaches depending on the contract architecture.
Proxy Upgrade: Change Logic, Keep Address and Storage
If the contract is deployed via UUPS (EIP-1822) or Transparent Proxy (EIP-1967) pattern – upgrading is technically simple: deploy a new implementation and call upgradeTo(newImpl). But the devil is in the storage layout.
Storage collision is the main threat in proxy upgrades. Variables in Solidity occupy slots in declaration order. If in version V1 slot 0 is address owner, and in V2 you add a new variable before owner, slot 0 will now be read as the new variable. Data isn't physically lost, but it's incorrectly interpreted. A real-world gotcha:
// V1
contract StakingV1 {
address public owner; // slot 0
uint256 public totalStaked; // slot 1
}
// V2 – INCORRECT: slots shifted
contract StakingV2 {
uint256 public version; // slot 0 – conflict with owner!
address public owner; // slot 1 – conflict with totalStaked!
uint256 public totalStaked; // slot 2
}
After the upgrade, owner will return the first 20 bytes of the old totalStaked number. This is a critical error. According to OpenZeppelin: never reorder existing variables, only append new ones at the end, and use storage gaps:
uint256[50] private __gap; // reserve for future variables
For large projects, we fork-test mainnet using Foundry and verify storage layout with the @openzeppelin/upgrades-core utility.
Example upgrade script using Foundry
// script/Upgrade.s.sol
contract UpgradeScript is Script {
function run() external {
address proxyAddress = vm.envAddress("PROXY_ADDRESS");
vm.startBroadcast();
StakingV2 newImpl = new StakingV2();
UUPSUpgradeable(proxyAddress).upgradeToAndCall(
address(newImpl),
abi.encodeCall(StakingV2.initializeV2, (newParam))
);
vm.stopBroadcast();
StakingV2 proxy = StakingV2(proxyAddress);
require(proxy.version() == 2, "Upgrade failed");
}
}
Full Migration: Deploy New Contract, Transfer Data
Sometimes proxy is impossible or undesirable. Then data migration is needed: read all data from the old contract and write to the new one. Direct on-chain migration for 10,000 users would cost ~$40,000 in gas. A more efficient approach is lazy migration via Merkle tree:
- Off-chain snapshot: read the entire state via RPC.
- Build a Merkle tree from all addresses and balances.
- Users claim their data themselves by providing a Merkle proof.
mapping(address => bool) public migrated;
bytes32 public merkleRoot;
function claimMigration(uint256 amount, bytes32[] calldata proof) external {
require(!migrated[msg.sender], "Already migrated");
bytes32 leaf = keccak256(abi.encode(msg.sender, amount));
require(MerkleProof.verify(proof, merkleRoot, leaf), "Invalid proof");
migrated[msg.sender] = true;
_mint(msg.sender, amount);
}
With 20,000 participants, this approach saves over 95% of gas – up to $38,000 compared to direct migration. Gas costs are entirely borne by users.
| Feature | Proxy upgrade | Full migration via Merkle tree |
|---|---|---|
| Address change | No | Yes |
| Gas cost | One transaction ($10-$50) | Distributed among users (~$2 each) |
| Number of transactions | 1 | N users |
| Backward compatibility | Full | Requires address updates |
Why Proper Storage Layout Matters During Upgrades
Storage collision causes 30% of failed upgrades. We always audit the current storage layout before starting development. This reveals incompatibilities early.
Migration Scripts: Tools and Automation
For proxy upgrades we use Foundry scripts (example above). Run with dry-run:
forge script script/Upgrade.s.sol --fork-url $MAINNET_RPC --broadcast false
For data snapshots we use a TypeScript script that splits requests into chunks of 10,000 blocks. This can process even contracts with millions of events in minutes.
Versioning and Rollback
Each upgrade is tagged in git: v2.0.0-upgrade. We store the old implementation address – in the UUPS pattern, rollback is possible by calling upgradeToAndCall again. For critical upgrades we use a TimelockController with a 24–48 hour delay.
Process
- Audit current state. Analyze storage layout, data volume, dependent protocols.
- Design strategy. Choose proxy or full migration, plan backward compatibility.
- Develop and test. Fork-test mainnet, check storage layout, test rollback.
- Deploy. Multi-sig via Safe{Wallet}, timelock, Tenderly monitoring.
- Post-migration support. Verify data integrity, adjust if needed.
What's Included
- Audit of current contract and storage layout
- Selection of optimal migration strategy
- Script development (Foundry / TypeScript)
- Fork-testing on mainnet
- Deployment with multi-sig and timelock
- Rollback documentation
- Post-migration support (5 days)
Timeline Estimates
| Migration type | Duration |
|---|---|
| Proxy upgrade (script + tests) | 1–2 days |
| Full migration with Merkle tree | 2–5 days |
| Timelock/multisig coordination | +1–2 days |
Order a turnkey migration – get ready-made scripts with rollback support and full documentation. Contact us for a project assessment – we analyze your current contract for free. Pricing is calculated individually based on contract complexity. We guarantee data integrity at every stage. Our experience – 5+ years in DeFi, 50+ completed migrations – allows us to tackle tasks of any complexity. Get a consultation right now.







