Forked from tomconte/web3-solc-contract-compile-deploy.js
Last active
November 26, 2017 17:40
-
-
Save ceccode/f7c3b1e600b867bf77a7d59e934375e2 to your computer and use it in GitHub Desktop.
Compiling and deploying an Ethereum Smart Contract, using solc and web3.
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
const fs = require('fs'); | |
const solc = require('solc'); | |
const Web3 = require('web3'); | |
// Connect to local Ethereum node | |
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); | |
// Compile the source code | |
const input = fs.readFileSync('Token.sol'); | |
const output = solc.compile(input.toString(), 1); | |
const bytecode = output.contracts[':Token'].bytecode; | |
const abi = JSON.parse(output.contracts[':Token'].interface); | |
// Contract object | |
const contract = web3.eth.contract(abi); | |
// Deploy contract instance | |
const contractInstance = contract.new({ | |
data: '0x' + bytecode, | |
from: web3.eth.coinbase, | |
gas: 90000*2 | |
}, (err, res) => { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
// Log the tx, you can explore status with eth.getTransaction() | |
console.log(res.transactionHash); | |
// If we have an address property, the contract was deployed | |
if (res.address) { | |
console.log('Contract address: ' + res.address); | |
// Let's test the deployed contract | |
testContract(res.address); | |
} | |
}); | |
// Quick test the contract | |
function testContract(address) { | |
// Reference to the deployed contract | |
const token = contract.at(address); | |
// Destination account for test | |
const dest_account = '0x002D61B362ead60A632c0e6B43fCff4A7a259285'; | |
// Assert initial account balance, should be 100000 | |
const balance1 = token.balances.call(web3.eth.coinbase); | |
console.log(balance1 == 1000000); | |
// Call the transfer function | |
token.transfer(dest_account, 100, {from: web3.eth.coinbase}, (err, res) => { | |
// Log transaction, in case you want to explore | |
console.log('tx: ' + res); | |
// Assert destination account balance, should be 100 | |
const balance2 = token.balances.call(dest_account); | |
console.log(balance2 == 100); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment