Skip to content

Instantly share code, notes, and snippets.

@fabdarice
Last active August 23, 2022 10:30
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fabdarice/a4a581df4098323e1e3b286141d78034 to your computer and use it in GitHub Desktop.
Save fabdarice/a4a581df4098323e1e3b286141d78034 to your computer and use it in GitHub Desktop.
Useful Solidity/Web3/Truffle commands
1) go to https://ropsten.etherscan.io/verifyContract?a=0xa32b21ba14fd476757e392db5d1bbc833eaedaf5
2) enter contract address, name, compiler
3) copy code of contract flatten out (delete import and replace by actual code)
4) truffle console
5) var Eth = require('ethjs')
6) Eth.abi.encodeParams(["uint256", "uint256", "uint256", "address", "uint256"], ["1508105298", "1508710098", "200", "0x3d208fabaf7e919985d5d2f068f28d6a9022e8d5", "5000000000000000000000000000"])
7) copy paste result of encodeParams without '0x'
To manually compile a contract :
1) node
2) code = fs.readFileSync('Voting.sol').toString()
3) contract = web3.eth.compile.solidity(code)
contract.code: This is the bytecode you get when the source code in Voting.sol is compiled. This is the code which will be deployed to the blockchain.
contract.info.abiDefinition: This is an interface or template of the contract which tells the contract user what methods are available in the contract. Whenever you have to interact with the contract in the future, you will need this abiDefinition.
How to deploy a contract :
1) VotingContract = web3.eth.contract(contract.info.abiDefinition)
2) deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: contract.code, from: web3.eth.accounts[0], gas: 4700000})
3) contractInstance = VotingContract.at(deployedContract.address)
How to get a contract deployed in the blockchain :
eth.contract(ABI).at(Address)
How to destroy/delete a contract in the blockchain :
contractInstance.kill.sendTransaction({from:eth.accounts[0]})
How to simply return a value from a function that doesn't modify a state variable :
contractInstance.totalVotesFor.call('Nick').then(function(result) { console.log(result) })
OR
simply define the function as being 'constant' (i.e function totalVotes(bytes32 candidate) constant returns (uint8)
Watch Event since the beginning :
var depositEventAll = cryptoExContract.Deposit({_sender: userAddress}, {fromBlock: 0, toBlock: 'latest'});
depositEventAll.watch(function(err, result) {
if (err) {
console.log(err)
return;
}
// append details of result.args to UI
})
When the UI is rendered depositEventAll.stopWatching() should be called.
To register a ENS (testnet) .test name
1) have geth running
2) geth attach ipc:path_to_geth.ipc
3) loadScript('/path/to/ensutils-testnet.js');
4) new Date(testRegistrar.expiryTimes(web3.sha3('myname')).toNumber() * 1000) : check that name is available
5) eth.accounts[0] == ens.owner(namehash('MYNAME.test')) : verify that the domain belongs to you
6) ens.setResolver(namehash('fabtest.test'), publicResolver.address, {from: eth.accounts[0]});
7) publicResolver.setContent(namehash('MYNAME.test'), 'HASH', {from: eth.accounts[0], gas: 100000}) : to link resolver to the hash
WARNING : HASH has to start with "0x"
Registering an ENS on mainet .eth :
1) loadScript('/path/to/ensutils.js')
2) Make a bid: bid = ethRegistrar.shaBid(web3.sha3('myname'), eth.accounts[0], web3.toWei(1, 'ether'), web3.sha3('secret'));
3) Reveal your bid: ethRegistrar.unsealBid(web3.sha3('myname'), eth.accounts[0], web3.toWei(1, 'ether'), web3.sha3('secret'), {from: eth.accounts[0], gas: 500000});
4) Finalise : ethRegistrar.finalizeAuction(web3.sha3('myname'), {from: eth.accounts[0], gas: 500000});
You can get content by simply :
getContent('fabtest.test')
solc :
solc --optimize --bin A.sol : compile contract A
solc --optimize --bin B.sol | solc --link --libraries A:[A_CONTRACT_ADDRESS] : compile contract B that import library A
b_address.send(price) : A contract can send its Ether in units of wei to a recipient B using address.send like:
Best Practices :
Assert vs Require vs Throw
1) assert(false) use up all remaining gas, and reverting all changes - should be used more for runtime error catching:
2) require(false) will refund the remaining gas, and return a value (useful for debugging) - should be used for input validation.
3) Throw Deprecrated
Solidity offers low-level call methods that work on raw addresses: address.call(), address.callcode(), address.delegatecall(), and address.send.
These low-level methods never throw an exception, but will return false if the call encounters an exception.
On the other hand, contract calls (e.g., ExternalContract.doSomething()) will automatically propagate a throw (for example, ExternalContract.doSomething() will also throw if doSomething() throws).
Loop cannot run more than 255 times :
In for (var i = 0; i < arrayName.length; i++) { ... }, the type of i will be uint8, because this is the smallest type that is required to hold the value 0.
If the array has more than 255 elements, the loop will not terminate.
There is a way to forward more gas to the receiving contract using addr.call.value(x)(). This is essentially the same as addr.transfer(x), only that it forwards all remaining gas and opens up the ability for the recipient to perform more expensive actions (and it only returns a failure code and does not automatically propagate the error). This might include calling back into the sending contract or other state changes you might not have thought of. So it allows for great flexibility for honest users but also for malicious actors.
Never use tx.origin for authorization
SWARM :
swarm up [file] : upload a file to Swarm
swarm --bzzapi http://swarm-gateways.net up [file] : upload a file to Swarm without running a node
swarm --recursive up [folder]: upload a whole folder [folder]
swarm --recursive --defaultpath [file] up [folder] : assign a default file to show at root path
GET http://localhost:8500/bzz:/HASH : download the file at [HASH] address
swarm ls <domain-or-manifest-hash>/path
If you use IPFS / Swarm then you have the following
Advantages
The user can always be guaranteed that the data was not manipulated
The use may also get the data when you are offline
The load on your server is lower (or no server at all)
Disadvantages
People need to use a node or go through a gateway
You can't use centralized backend code
truffle console : run console
truffle compile : compile the contract within the contract folder
truffle migrate : compile & deploy the contract
truffle migrate -reset : recompile & redeploy all contracts
Contract.abi : retrieve abi definition of contract [Contract]
How to update a smart contract with Upgreadable contract (https://gist.github.com/Arachnid/4ca9da48d51e23e5cfe0f0e14dd6318f) :
1) Deploy Upgreadable
2) Deploy Example
3) Deploy a Dispatcher with the address of Example
4) Call whatever on the address of the Dispatcher, which gets forwarded to the Example instance
5) When you have a new Example, you get your current Example to call replace on itself to substitute in a new address
1) https://ropsten.etherscan.io/verifyContract
2) enter contract address, name, and select compiler
3) enter contract code (.sol) - (replace import line with the actual contract)
4) node
5) var Eth = require('ethjs')
6) Eth.abi.encodeParams(['uint256', 'uint256', 'uint256', 'address', 'uint256'], [1508105298, 1508710098, 300, '0x3d208fabaf7e919985d5d2f068f28d6a9022e8d5', 10000000000000000000])
7) Copy the result without the '0x' at the beginning
web3.eth.accounts : list accounts
web3.personal.unlockAccount(address, pw) : unlock an account before any sendTransaction
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]), 'ether') : check ether balance
web3.toWei(1.0, 'ether') : convert Ether to Wei Unit
web3.eth.getTransactionReceipt(tx) : retrieve transaction receipt from tx
web3.toAscii : convert bytes32 to String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment