Created
October 26, 2018 17:01
-
-
Save Hokid/b4e7e3ce7519911d0641dd305868771b to your computer and use it in GitHub Desktop.
__dapp.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function waitContractEventOnce(events, name, timeout = Infinity) { | |
return new Promise(function (accept, reject) { | |
if (typeof events[name] !== 'function') reject(new Error(`no event with name "${name}"`)); | |
const timerCb = () => { | |
if (watcher) watcher.stopWatching(); | |
watcher = null; | |
reject(new Error('timout has been expired')); | |
}; | |
let watcher; | |
let timer = isFinite(timeout) && timeout >= 0 | |
? setTimeout(timerCb, timeout) | |
: null; | |
watcher = events[name](null, null, (error, result) => { | |
if (!watcher) return; | |
watcher.stopWatching(); | |
if (timer !== null) clearTimeout(timer); | |
if (error) return reject(error); | |
return accept(result); | |
}); | |
}); | |
} | |
function waitTransactionReceipt(tx, web3, timeout = 240000) { | |
return new Promise(function (accept, reject) { | |
const start = new Date().getTime(); | |
const make_attempt = () => { | |
web3.eth.getTransactionReceipt(tx, function (err, receipt) { | |
if (err && !err.toString().includes('unknown transaction')) { | |
return reject(err); | |
} | |
if (receipt != null) { | |
if (parseInt(receipt.status, 16) == 0) { | |
return reject(new Error('status error'), tx, receipt); | |
} else { | |
return accept({ | |
tx: tx, | |
receipt: receipt | |
}); | |
} | |
} | |
if (timeout > 0 && new Date().getTime() - start > timeout) { | |
return reject(new Error("Transaction " + tx + " wasn't processed in " + (timeout / 1000) + " seconds!")); | |
} | |
setTimeout(make_attempt, 1000); | |
}); | |
}; | |
make_attempt(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment