193

A simple example demonstrating this effect looks like this: pragma solidity^0.4.12; contract Test { function test(uint[20] a) public returns (uint){ return a[10]*2; } function test2(uint[20] a) external returns (uint){ return a[10]*2; } } Calling each function, we can see that the public function uses 496 gas, while the ...


162

Here are some simple and useful patterns in increasing order of utility. Event logs are omitted for brevity. In practice, it's desirable to emit events for every important state change. Simple List Using Array Strengths Reliably chronological order Provides a count Random access by Row Number (not Id) Weaknesses No random access by Id No assurance of ...


134

Once a contract is in the blockchain, it is final and cannot be changed. Certain parameters, of course, can be changed if they are allowed to change via the original code. One method of updating contracts is to use a versioning system. For example, you could have an entryway contract that just forwards all calls to the most recent version of the contract, ...


92

There are two aspects to consider when choosing between assert() and require() Gas efficiency Bytecode analysis 1. Gas efficiency assert(false) compiles to 0xfe, which is an invalid opcode, using up all remaining gas, and reverting all changes. require(false) compiles to 0xfd which is the REVERT opcode, meaning it will refund the remaining gas. The ...


71

This is discussed here: https://github.com/ethereum/solidity/issues/992 and has been partially implemented in the change you noted. As I understand it, the point is that constant is misleading (constant functions don't necessarily return constant results), and not particularly nuanced. The changes when complete will introduce two replacement keywords: view ...


70

address.transfer() throws on failure forwards 2,300 gas stipend (not adjustable), safe against reentrancy should be used in most cases as it's the safest way to send ether address.send() returns false on failure forwards 2,300 gas stipend (not adjustable), safe against reentrancy should be used in rare cases when you want to handle failure in the contract ...


69

With msg.sender the owner can be a contract. With tx.origin the owner can never be a contract. In a simple call chain A->B->C->D, inside D msg.sender will be C, and tx.origin will be A. msg.sender is preferred for the flexibility it provides. Furthermore, for Serenity, even though it's a while out, Vitalik recommends avoiding tx.origin: How do I make my ...


69

Q What does the "indexed" keyword do in the below line of code? I'm guessing it just tells the event object that the following input should be logged? The indexed parameters for logged events will allow you to search for these events using the indexed parameters as filters. Q Can we use it other places ie outside of events? The indexed keyword is only ...


66

Make sure that you have configured your network in truffle.js. It should look something like this for the setup mentioned above: module.exports = { networks: { development: { host: "localhost", port: 8545, network_id: "*" // Match any network id } } };


57

Use the delete operator to delete the element: delete array[index]; If you don't want to leave a gap, you need to move each element manually: contract test{ uint[] array = [1,2,3,4,5]; function remove(uint index) returns(uint[]) { if (index >= array.length) return; for (uint i = index; i<array.length-1; i++){ ...


56

Get contract address in Solidity Short answer: The global variable this is the contract address. Long answer: this is a variable representing the current contract. Its type is the type of the contract. Since any contract type basically inherits from the address type, this is always convertible to address and in this case contains its own address. Update ...


52

The EVM works with 256bit/32byte words (debatable design decision). Every operation is based on these base units. If your data is smaller, further operations are needed to downscale from 256 bits to 8 bits, hence why you see increased costs. Btw, if you toggle the "Details" on the online solidity compiler, it will give you the exact assembly dump where the ...


52

I was stuck on this issue as well for a very long time. So the solution is: Add this prefix string to your Solidity smart contract. function verify(bytes32 hash, uint8 v, bytes32 r, bytes32 s) constant returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(prefix, hash); return ecrecover(...


52

In earlier versions, we would apply the constant modifier to indicate that a function doesn't change the storage state in any way. For example: pragma solidity 0.4.16; contract UseConstant { string greeting; function UseConstant() public { greeting = "Hello"; } function SayHello() public constant returns(string says) { ...


50

Yes, just use fooStruct myStruct = fooStruct(1,2); Or fooStruct myStruct = fooStruct({foo:1, fighter:2}); Or fooStruct memory myStruct; // for temporary data myStruct.figther = 2; // will only write to memory fooStruct storage myStruct = ...; // for persistent data, has to be initialized from a state variable. `storage` is the default and a warning ...


50

The Solidity FAQ on "memory" is highly recommended reading in entirety, and a snippet is provided below. The Ethereum Virtual Machine has three areas where it can store items. The first is “storage”, where all the contract state variables reside. Every contract has its own storage and it is persistent between function calls and quite expensive to ...


46

Compilation back to the original source code is impossible because all variable names, type names and even function names are removed. It might be technically possible to arrive at some source code that is similar to the original source code but that is very complicated, especially when the optimizer was used during compilation. I don't know of any tools ...


46

One could consider topics as different index names. EVM uses low level primitives called logs to map them to high level Solidity construct called Event. Logs may contain different topics that are indexed arguments. Consider Event: emit PersonCreated(uint indexed age, uint indexed height); And you fire it in MyContract: function foobar() { ...


46

First, payable is a modifier that can be added to a function. What you are most likely misinterpreting is a use case like: function () public payable {} It's impossible to have payable() as a function name as it is a reserved keyword. You may use payable only in addition to existing functions like: function deposit() payable {} function register(address ...


45

Though this works, I personally think it is a good idea to have both operand types equal on boolean operations , as you mentioned for future compatibility. Instead of using > operator use equality == or != , as in case of address the greater operator may not make sense. Instead of using 0x0 use address(0) or address(0x0), as it would make much more of ...


45

You need to use an array in storage because it is not possible to resize memory arrays. contract D { uint[] myArray; function Test() constant returns (uint[]) { myArray.push(123); return myArray; } } Otherwise you need to define the size of the array during initialization: contract C { function f(uint len) { uint[] ...


45

3 Primary improvements with ERC223 Eliminates the problem of lost tokens which happens during the transfer of ERC20 tokens to a contract (when people mistakenly use the instructions for sending tokens to a wallet). ERC223 allows users to send their tokens to either wallet or contract with the same function transfer, thereby eliminating the potential for ...


45

You can do this by calling address.balance. To get the contract's balance, just do this.balance. Read the docs. Update: As of Solidity ^0.4.24, you need to do: address(this).balance (Copied from answer by Paul Berg)


44

In Ethereum transactions cost gas and hence ether. The gas consumption of a transaction depends on the opcodes that the EVM has to execute. The gas cost for each Opcode and be found as explained in this question. Few common opcodes and gas are, Operation Gas Description ADD/SUB 3 Arithmetic operation MUL/DIV ...


43

Summary Return the fields of the struct as separate return variables. Example I'm running this code in my local dev blockchain using the following command: geth --datadir ~/devdata --dev --nodiscover \ --mine --minerthreads 1 --port 30301 \ --maxpeers 0 --verbosity 3 --rpc console Your web frontend should be able to send transactions to insert ...


43

This has worked for me so far. Not sure if it's the best way. function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } Also, remember that ...


41

One way is to use Remix, the browser-based Solidity realtime compiler and runtime Solidity (formerly named browser-solidity). Paste the code in Remix. Wrap the function inside a contract if needed. (Example: contract C { ... }.) Click Contract tab and then Create to instantiate the contract. Enter the desired input next to the function. For bytes1 ... ...


41

Why string instead of bytes32? Use string for arbitrary-length string (UTF-8) data that's longer than 32 bytes. Frontends can decode a long string easier using methods like web3.toAscii or UTF-8 (when issues are fixed), instead of implementing the logic of UTF-8 decoding a series of bytes32. From Solidity docs: As a rule of thumb, use bytes for ...


41

It is a good practice to always declare the type access to your methods. If you forget to declare a function internal previous version will compile happily and will not warn about the potential security issue. function setFee(uint _fee) public { fee = Sf.mul(_fee,10); } The constant modifier is being replaced by view and pure. With view you cannot ...


40

Is this even possible (I remember I read somewhere that only normal accounts can send contract creating transactions)? This is definitely possible. When I invoke this method from contract, the address I receive seems to be normal address and not contract. I'm not sure which address you are talking about. This kind of design works well: contract ...


Only top voted, non community-wiki answers of a minimum length are eligible