Skip to content

Instantly share code, notes, and snippets.

@MitchK
Last active December 15, 2018 01:55
Show Gist options
  • Save MitchK/7c4d03a42e8ed4044f7067d7ecd90c2a to your computer and use it in GitHub Desktop.
Save MitchK/7c4d03a42e8ed4044f7067d7ecd90c2a to your computer and use it in GitHub Desktop.
Ethereum smart contract deployment
const Web3 = require('web3')
const solc = require('solc')
// Connect to instance using the RPC endpoint
const rpc = 'paste url here'
const web3 = new Web3(new Web3.providers.HttpProvider(rpc))
// Compile smart contract using the solc compiler
const sourceCode = `
pragma solidity ^0.5.0;
contract SimpleStorage {
uint public storedData;
constructor (uint initVal) public {
storedData = initVal;
}
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint retVal) {
return storedData;
}
}
`
const input = {
language: 'Solidity',
sources: { 'simplestorage.sol': { content: sourceCode } },
settings: { outputSelection: { '*': { '*': [ '*' ] } } }
}
const compiled = JSON.parse(solc.compile(JSON.stringify(input)))
if (compiled.errors > 0) {
console.error(compiled.errors)
process.exit(1)
}
const compiledContracts = compiled.contracts['simplestorage.sol']
console.log('successfully compiled contract(s)')
;(async () => {
try {
// Select account and unlock the account with your password
const accountAddress = 'paste account address create from service key'
const accountPassword = 'use your password to unlock account'
await web3.eth.personal.unlockAccount(accountAddress, accountPassword, 10)
console.log('account unlocked')
// Deploy contract, initialize with value 1
const contract = await new web3.eth.Contract(compiledContracts.SimpleStorage.abi).deploy({
data: '0x' + compiledContracts.SimpleStorage.evm.bytecode.object,
arguments: [1]
}).send({
from: accountAddress,
gas: 300000
})
const contractAddress = contract.options.address
console.log('contract successfully deployed')
// Retrieve contract using ABI and addres and read from it
const newContract = new web3.eth.Contract(compiledContracts.SimpleStorage.abi, contractAddress)
let result = await newContract.methods.get().call()
console.log('successfully read from contract:', result)
// Change value from 1 to 42
await newContract.methods.set(42).send({ from: accountAddress })
result = await newContract.methods.get().call()
console.log('successfully wrote and read new value to contract:', result)
// Change value
} catch (err) {
console.error(err)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment