Las reorganizaciones de cadena (reorgs) ocurren cuando una cadena competidora se convierte en la nueva cadena canónica. Entender cómo manejar las reorgs es crucial para mantener la consistencia de la aplicación.
// Monitorear reorgs
const monitorReorgs = async (callback, checkInterval = 5000) => {
let lastBlock = await web3.eth.getBlockNumber();
let lastBlockHash = (await web3.eth.getBlock(lastBlock)).hash;
return setInterval(async () => {
const currentBlock = await web3.eth.getBlockNumber();
const currentBlockHash = (await web3.eth.getBlock(lastBlock)).hash;
if (currentBlockHash !== lastBlockHash) {
// Reorg detectada
callback({
oldBlock: lastBlock,
oldHash: lastBlockHash,
newBlock: currentBlock,
newHash: currentBlockHash,
});
}
lastBlock = currentBlock;
lastBlockHash = currentBlockHash;
}, checkInterval);
};
// Obtener bloque ancestro común
const findCommonAncestor = async (hash1, hash2) => {
let block1 = await web3.eth.getBlock(hash1);
let block2 = await web3.eth.getBlock(hash2);
while (block1.number > block2.number) {
block1 = await web3.eth.getBlock(block1.parentHash);
}
while (block2.number > block1.number) {
block2 = await web3.eth.getBlock(block2.parentHash);
}
while (block1.hash !== block2.hash) {
block1 = await web3.eth.getBlock(block1.parentHash);
block2 = await web3.eth.getBlock(block2.parentHash);
}
return block1;
};