Last active
September 5, 2018 18:57
-
-
Save frozeman/655a9325a93ac198416e 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(); | |
} | |
} | |
}); | |
} | |
}); |
there is a )
too much at line 31 :)
This gist is outdated use:
web3.contract(abiArray).new({}, function(e, res){...})
See here for more: https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethcontract
Should line 49 be length <= 2
?
Is there a way to generate this kind of identifiers at execution time?
I created an example here using Web3.js 1.0.0 Beta 27 and trying to implement the Created event that @frozeman used https://github.com/ltfschoen/geth-node/blob/master/scripts/main.js
It doesn't work yet because it appears the unlockAccount()
function hasn't been implemented yet. See web3/web3.js#1264
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is the check
.length == '0x'
in line 49 really correct?