
Understanding Ethereum Smart Contracts - bjaanes
http://www.gjermundbjaanes.com/understanding-ethereum-smart-contracts/
======
jatsign
I've been programing my own Ethereum smart contract (virtual currency) for
awhile now. Here's some gotchas off the top of my head:

\- You have about 500 lines of code to work with. This of course varies, but
smart contracts have to be really small to fit in the max gas limit (6.7
million wei).

\- You can't pass strings between contracts (coming soon).

\- There are no floating point numbers. Since you're probably working with
"money", this can make things tricky.

\- You can break up your code into multiple contracts, but the tradeoff is an
increased attack area.

\- Dumb code is more secure than smart code.

\- The tooling is very immature. You'll probably use truffle, which just
released version 4. It makes some things easier, some harder. It's version of
web3 (1.0) may differ from what you were expecting (0.2).

\- The Ethereum testnet (Ropsten) has a different gas limit than the main net
(4.7 million vs 6.7 million).

~~~
Slartie
> There are no floating point numbers. Since you're probably working with
> "money", this can make things tricky.

That is actually a feature when it comes to working with money. You don't ever
want to use floating-point arithmetic with monetary values due to its
inability to represent all possible decimal fractions of your base unit. This
is just as true for over-hyped blockchain stuff as it is for any imaginable
application in the "classic" financial sector.

What you need is either an integer data type plus a fixed, implied number of
digits that you want to handle (so for example 105 represents 1 dollar and 5
cents), or a fixed-point numeric type (like for example BigDecimal in Java;
there's lots of equivalents in other languages, most of them have something
like "decimal" in their names), which essentially just stores the integer
value together with the number of digits and features mathematical operations
of pairs of these with each other.

~~~
Kranar
>That is actually a feature when it comes to working with money. You don't
ever want to use floating-point arithmetic with monetary values due to its
inability to represent all possible decimal fractions of your base unit. This
is just as true for over-hyped blockchain stuff as it is for any imaginable
application in the "classic" financial sector.

I feel like this is constantly repeated but is simply untrue and working in
the financial sector (high frequency trading) I don't know anyone who actually
uses fixed digit number systems to represent money. Normally what I do see are
people outside of finance who need to represent money who read the common
mantra about using a fixed digit representation only to eventually encounter
all the issues that floating point was invented to solve. When they encounter
those issues they then end up having to adapt their code only to basically re-
invent a broken, unstable quasi-floating point system when they would have
been much better off using the IEEE floating point system and actually taking
the time to understanding how it works.

BigDecimal will solve the issue but it's absolute overkill both in terms of
space and time, we're talking many many orders of magnitude in terms of
performance degradation and it's entirely unneeded.

One simple solution that works very well for up to 6 decimal places is to take
your idea of having an implied number of digits, but instead of using an
integer data type, you use a floating point data type. So 1 dollar and 5 cents
becomes (double)(1050000.0). This lets you represent a range from 0.000001 up
to 9999999999.999999 exactly, without any loss of precision. Values outside of
that range can still be represented as well but you may have some precision
issues.

Another solution which is less efficient but more flexible is to use decimal
floating point numbers instead of binary floating point numbers. There is an
IEEE decimal floating point standard that can represent an enormous range of
decimal values exactly. Intel even provides a C/C++ implementation that meets
formal accounting standards.

Both of the solutions I list above are orders of magnitude more efficient than
using fixed-point numeric types and are by no means difficult to use.

~~~
Slartie
Self-quote: > any imaginable application in the "classic" financial sector

Kranar: > working in the financial sector (high frequency trading)

Okay, you got me there - you have pointed me to that single application from
the financial sector where it is not totally acceptable to "waste" a few
thousands of processor cycles to compute some money-related stuff. Granted, in
HFT applications, these cycles may allow you to get your trades in front of
those of the other HFT companies. You are forced to use CPU-accelerated (or
maybe even GPU?) computations in this case, which automatically means
"floating point".

But there's another difference that allows you do do this: you mostly don't
have to care about exact, accurate-up-to-the-penny results. I assume most of
your calculations are done to eventually arrive at a conclusion of whether to
buy or sell some stock or not, and at which price. You have to take care of
not accumulating too much rounding errors in the process, of course, but the
threshold for these errors is set by yourself, and you can give yourself a bit
of leeway on this, because it's all internal stuff, mostly probabilistic and
statistics-based - the only stuff that may be audited by someone else and thus
has to match the real numbers up to the last penny are the trades you do and
the money you move around, and I bet all of this accounting-style stuff is
recorded using...decimal numbers :D

I work in the retail industry (think cash registers, retail sale accounting,
that kind of stuff) and pretty much any legislation on this planet would
obliterate us if we'd tell them that the result of the computations of our
systems may be some cents up or down from the real result - the one someone
would get who just scribbled the numbers on a sheet of paper and added them up
manually. Our customers have to pay taxes based on the sales that they account
using our systems, and the tax calculations as well as the entire chain of
processes they use to arrive at the final numbers are regularly audited by the
respective governments. There are specific rules (of course differing by
country) as to how many decimal places have to be used and how stuff has to be
rounded in which particular cases in calculations that would require more
decimals. We waste an enormous amount of CPU cycles just to strictly adhere to
these rules - and that is not only absolutely necessary, but also totally
okay, modern CPUs can easily accomodate this in our scenario.

~~~
Kranar
>I work in the retail industry (think cash registers, retail sale accounting,
that kind of stuff) and pretty much any legislation on this planet would
obliterate us if we'd tell them that the result of the computations of our
systems may be some cents up or down from the real result - the one someone
would get who just scribbled the numbers on a sheet of paper and added them up
manually.

It is especially in cases like this that you absolutely should not use fixed
decimal point systems to represent money. It is exactly in these circumstances
that your fixed decimal point system will eventually encounter a situation
where it fails catastrophically.

Intel provides an IEEE decimal floating point system specifically for the
purpose of adhering to legal requirements, they say so right at the top of
their website:

[https://software.intel.com/en-us/articles/intel-decimal-
floa...](https://software.intel.com/en-us/articles/intel-decimal-floating-
point-math-library)

If fixed point math would have solved this issue, they'd have provided a
solution involving that, but fixed point math is simply the absolute worst
solution to this problem, even worse than naively using a 64-bit binary
floating point number.

BigDecimal is also a viable solution, but it's entirely unnecessary and the
cost really is enormous especially if you need to handle a large number of
transactions. But sure, if you say performance genuinely isn't an issue go
with BigDecimal.

~~~
Slartie
> BigDecimal is also a viable solution, but it's entirely unnecessary and the
> cost really is enormous especially if you need to handle a large number of
> transactions. But sure, if you say performance genuinely isn't an issue go
> with BigDecimal.

That is exactly what we currently do, and speed of computations is definitely
not an issue at all. If we have performance related problems (and we do
sometimes), they have never in 10 years originated from numerical computation
just taking too long, but always from other inefficiencies, quite often of
architectural nature that uselessly burn a thousand times more cycles than the
numeric part of the job.

BigDecimal provides exactly what we need: a no-brainer, easy-to-use, easy-to-
understand and always correct vehicle for the calculation of monetary sums. It
lets our developers focus on implementing the business logic, and also on
making less of the described high-level failures that get us into actual
performance troubles, instead of consuming a lot of mental share just to “get
the computation right“ in all circumstances.

------
j_s
Just over a month ago, HN user DennisP answered the question "How did you get
into contract ethereum development?".

[https://news.ycombinator.com/item?id=15496393](https://news.ycombinator.com/item?id=15496393)

If you are starting back at the idea of the Bitcoin blockchain, see ahussain's
recommendation of 3Blue1Brown a day later:

[https://news.ycombinator.com/item?id=15504409](https://news.ycombinator.com/item?id=15504409)

[https://www.youtube.com/watch?v=bBC-
nXj3Ng4](https://www.youtube.com/watch?v=bBC-nXj3Ng4)

------
scandox
What I'd greatly appreciate is a walk through of a plausible real world use
case. I find it hard to concentrate on the technology itself until I
understand the application.

~~~
decentralised
Crowdfunding (ICOs) is a use case. DNS (ENS) is a use case. Organisational
Transparency (Aragon) is a use case. Prediction Markets(Augur) are a use case.
Electricity Markets (Grid+) are a use case. International payment card with
zero fees (TenX) is a use case.

I can go on for a while longer, there are hundreds of use cases but the
question is: what would be a use case for you?

~~~
scandox
They all sound great. So what I'd love to see is a well written blog post
describing how Ethereum would be put to work to achieve one of those goals and
to give me an understanding of its superiority within the domain.

I'm not demanding it and I'm not being snarky at all. It's just that's the
level I'm at - without that kind of entry point I struggle to assess it.

~~~
_red
Some of the use cases can be fairly simple (thus easier to see the value).

1\. Me and You start a company together. We would like to split things 50/50\.
We setup an address such that when values are paid to it, half goes to you,
half goes to me. Effectively we've created an "LLC with an Operating
Agreement", but we aren't relying on political legal system / country to
enforce. Enforcement is automatic and done by the network.

2\. You want to setup a Trust for your kids. You create a contract that holds
10 Bitcoin / Etherum / etc. On the date Jan 1, 2035 the value of that address
will be forwarded to your child's address. Again, we created a "Non-Revokable
Trust" that is network enforced. No need for probate, courts, trustees, etc.

~~~
SeckinJohn
1- 50% of what? Revenue _into_ the company or dividens/salary etc _out_ of the
company? if it's the latter, then, how do we make sure that you don't spend
$500.000 for trash bins for the office? Do we have to make sure every decision
goes through the network? (i.e. who is the authority to decide what is
reasonable and what is blatant fraud if things go sour AND is it even possible
to make sure that _nothing_ possibly can go sour[I don't think so.]. So, fraud
is possible, and in the case of fraud, -say; the network retroactively decides
that something really constitutes a fraud, hence is a crime- who is the
enforcer of the punishment[which is most likely to be physical: like prison
sentence]?)

2- How do you make sure that your child doesn't sell it in 2025 and buys a
Lambo? (which is a problem you don't have with regular Trusts AFAIK)

~~~
ringaroundthetx
regarding number 2, the child would not have a way of selling that Ethereum
before 2035.

~~~
hhmc
Can't they just sell access to their address?

~~~
Joeboy
One way or another I'd rate the odds of their still having access to that
address in 2035 as pretty low.

Realistically anything that requires people to have decent data management /
opsec is going to fail for >99% of people.

------
fortenforge
> Bitcoin transactions are pretty simple in what they do. You can do one
> single thing. One type of transaction. Skipping some details, it all boils
> down to TO (who is receiving money), FROM (who is sending money) and AMOUNT
> (how much money). This let’s bitcoin be a store of value with the capability
> to transfer the value between participants in the network.

Doesn't Bitcoin script allow you to do far more complex things than just send
btc from person A to person B?

~~~
stuxnet79
Yes it does. A lot of people tend to brush over this aspect of BTC. The whole
notion of smart contracts is really just an extension of the scripting
capability introduced in BTC which some felt was far too limited.

~~~
runeks
Not only that, but Bitcoin script was _intentionally_ designed to be Turing
incomplete, in order to allow static analysis of time/space complexity.

Ethereum was invented to fill the space of a blockchain with a Turing-complete
scripting language, which may or may not prove to be useful in the real world
(in my opinion it hasn’t yet).

------
huhtenberg
Any other "gentle introductions" out there? Something with a complete walk-
through both from contract creator's perspective and from some random node on
the network.

This one failed to explain how contract calls are executed - is it by a single
node, by multiple nodes, do nodes compete with each other for the execution,
what's their incentive, etc.

~~~
tmlee
Contract calls are executed by all the nodes in the network.

And they will all update the contract state onto their own blockchain then
broadcast the result and compete via proof of work.

~~~
posedge
I wonder how they can ever expect a system like this to scale given that every
node has to execute every instruction in every called smart contract...

~~~
gibybo
Scaling is definitely a serious concern and is a large focus of Ethereum
developers at the moment. I don't understand much about the proposed
solutions, but they generally think the Ethereum network can be sharded in a
way that allows only a small subset of the network to run any given contract
and still guarantee reliability similar to as if the whole network had run it.

~~~
jacquesm
You'll need some very hard guarantees that that 'small subset' can never be
under the control of a single entity.

~~~
zodiac
It doesn't work like that - a working sharding scheme should not fail if one
shard is taken over. This is the most recent description of ethereum sharding
if you want to learn more ->
[https://youtu.be/9RtSod8EXn4?t=3h12m30s](https://youtu.be/9RtSod8EXn4?t=3h12m30s)
. In particular look at step 4 where the fork choice rule is changed so that
shards with invalid blocks cannot exist on a valid base chain.

------
lowglow
We had an SF crypto builders meet-up[0] where I gave a talk on Introduction to
Solidity programming[1].

It's a pretty good primer to get from zero to smart contract in about 30
minutes. Learn from my suffering.

[0] [https://www.meetup.com/sfhackdays/](https://www.meetup.com/sfhackdays/)

[1]
[https://www.facebook.com/hackdays4all/videos/544008492611485...](https://www.facebook.com/hackdays4all/videos/544008492611485/)

------
dsr_
I am particularly amused that in the first example, a simple counter, no
mention is made of the initialization routine being callable at any point...
at which time the counter is reset to zero.

~~~
alvarosevilla95
If I'm not mistaken in Solidity constructors can only be called once on a
contract

~~~
cratering
Yes that is correct
[http://solidity.readthedocs.io/en/develop/contracts.html#cre...](http://solidity.readthedocs.io/en/develop/contracts.html#creating-
contracts)

------
coryl
I've also just begun to play with smart contract programming.

One problem I'm having is with event listening.

It seems that MetaMask doesn't yet support subscriptions, nor does my
localhost testRPC instance pass it in the web3 object.

Some have suggested I need to run my own node just to listen for contract
events. Has anyone figured out an easier solution?

~~~
fokinsean
Quick question, do you have to download the full ethereum chain before you can
start messing with smart contracts? Or is there a "light" client you can use?

~~~
zodiac
You shouldn't use the main ethereum network when testing smart contracts -
develop on a local testnet and then if you want, on a public testnet (eg
rinkeby or ropesten) first

------
cygned
I really recommend reading the whitepaper. It not only explains Ethereum very
well, it also contains the best explanation of Bitcoin I have ever read.

[https://github.com/ethereum/wiki/wiki/White-
Paper](https://github.com/ethereum/wiki/wiki/White-Paper)

------
julioademar
I published a code walkthrough tutorial yesterday on this:
[https://hackernoon.com/full-stack-smart-contract-
development...](https://hackernoon.com/full-stack-smart-contract-development-
fccdfe5176ce)

~~~
maxencecornet
I was looking for something like this

Thanks !

------
mvkel
Does this fundamentally break down if the cost of ETH rises to a level where
it’s too expensive to run code on the chain?

