我想在部署后获取合同地址,然后将其保存到mongoDB中。但是,相反,我的合同地址被部署在该地址之后。因此,我的mongoDB不会保存我的合同地址。这是我的代码:
//My middleware : '/admin/my-connection/deploy' action => POST
exports.postContractDeployed = (req, res, next) => {
const contractId = req.body.contractId;
const ethereumUri = req.body.ethereumURI;
const contractABI = req.body.contractABI;
const contractBytecode = req.body.contractBytecode;
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(ethereumUri));
//define default account[0]
const address = web3.eth.accounts[0];
if (!web3.isConnected()) {
throw new Error('unable to connect to ethereum node at ' + ethereumUri);
}
let MyContract = web3.eth.contract([{
contractABI
}]
);
const kodeByte = '0x' + contractBytecode;
let deployContract = MyContract.new({
from: address,
data: kodeByte,
gas: '4700000'
}, async function (e, contract) {
// console.log(e, contract);
if (typeof contract.address !== 'undefined') {
console.log('Contract mined! address: ' + contract.address + 'with transactionHash: ' + contract
.transactionHash);
global.newContractAddress = contract.address;
global.newContractTxHash = contract.transactionHash;
});
Contract.findById(contractId).then(result => {
result.contractAddress = global.newContractAddress;
result.contractTxHash = global.newContractTxHash;
return result.save();
}).then(data => {
console.log('Contract Address has been generate!');
console.log('My Contract Address : ', global.newContractAddress);
res.redirect('/admin/my-connection');
}).catch(err => console.log(err)); };