-
-
Save skynode/e31b454a4e6b4566feb98e1f5cd07214 to your computer and use it in GitHub Desktop.
Deploy contracts on Ethereum and reliable get the contract address
This file contains hidden or 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
// -> Soldity | |
// ********** | |
// Your Soldity contract | |
event Created(bytes32 indexed identifier); | |
contract MyContract { | |
function MyContract(bytes32 identifier) { | |
Created(identifier); | |
} | |
... | |
} | |
// -> JavaScript | |
// ************* | |
// create contract | |
var MyContract = web3.eth.contract(abi); | |
// the identifier you pass need to be UNIQUE per contract, so you can reliably detect the log generated by your "Created" event | |
var myContractInstance = MyContract.new('0x16bd7d60bc08217d2e78d09658610a9eb6de22df8b587fdca9e980fafc4ecfcc', {from: ..., data: ..., gas: 123456}) | |
var createdAtBlock = web3.eth.blockNumber; | |
// listen for created log/event | |
var Created = web3.eth.filter({ | |
topics: [null, '0x16bd7d60bc08217d2e78d09658610a9eb6de22df8b587fdca9e980fafc4ecfcc'], | |
fromBlock: createdAtBlock, | |
toBlock: 'latest' | |
}); | |
Created.watch(function(error, log) { | |
if(!error) { | |
console.log('Contract created on '+ log.address); | |
myContractInstance.address = log.address; | |
// remove filter | |
Created.stopWatching(); | |
// watch for the last next 12 blocks if the code is still at the address | |
var filter = web3.eth.filter('latest'); | |
filter.watch(function(e, blockHash){ | |
if(!e) { | |
var block = web3.eth.getBlock(blockHash); | |
// check if contract stille exists, if show error to the user | |
if((block.number - createdAtBlock) < 12 && | |
web3.eth.getCode(myContractInstance.address).length > 2) { | |
alert('Oh no the contract is gone!'); | |
} else if (block.number - createdAtBlock > 12) { | |
filter.stopWatching(); | |
} | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment