您的位置:首页 > 其它

区块链学堂(10):Browser-solidity

2018-01-02 11:39 513 查看


使用Browser-solidity来编译合约&部署合约

https://ethereum.github.io/browser-solidity

在上一章中部署在Geth上的源代码如下:

pragma solidity 0.4.9;
contract DemoTypes {
function f(uint a) returns (uint b) { uint result = a * 8; return result; }
}
这个时候在这个地址的左侧,复制黏贴上述的代码,然后就可以看到右侧编译好的代码:



复制黏贴这段代码,且web3.eth.accounts[0]也处于解锁状态的话,即可部署到以太坊的私有链上。并可以被执行和调用。



> a_demotypes.f.call(100)
800
> a_demotypes.f.call(125)
1000


智能合约Solidity 源代码分析

这个最简单的智能合约代码如下:
pragma solidity 0.4.9;
contract DemoTypes {
function f(uint a) returns (uint b)
{
uint result = a * 8;
return result;
}
}

我们接下来试着做一些简单的分析,并介绍一些最基本的Solidity知识

第一行

pragma solidity 0.4.9;

第一行代码是必须的,否则编译器将不知道该如何选择编译器,以及编译器版本。
第一行的
pragma
solidity
 中
pragma
是关键词,代表程序开始,
solidity
 代表本智能合约是由Solidity语言所撰写
0.4.9
 代表的是编译器版本,注意:从0.4.9起可以在前面不打^,0.4.8/0.4.7等版本还是需要打^

编译器版本向下兼容,




第二行

contract DemoTypes {
...
}


这里引用一段说明Solidity里的Contract

Contracts in Solidity are similar to classes in object-oriented languages. They contain persistent data in state variables and functions that can modify these variables. Calling a function on a different contract (instance) will perform an EVM function call
and thus switch the context such that state variables are inaccessible. (引用自 here)

中文翻译:

Solidity中Contract和面向对象语言中的类很相像。有带持久数据的变量,以及能改变这些变量的function. 在不同的Contract实例中调用一个function,将会执行一个在EVM(以太坊虚拟机)中的function调用。

由此可见,Solidity中的智能合约和传统面向对象语言中的类很相像,因此有构造函数,有继承,有变量,有function,也有抽象类等等传统概念。
由Solidity所写的智能合约,经过编译后就会由EVM来部署执行
Solidity语言是一种类JS的语言,因此很多编码规范和JS很相似

第三行

function f(uint a) returns (uint b)
{
...
}

上面说过,contract中包含了变量&方法(function)。
function
f(uint a) returns (uint b)
 代表定义了一个名为
f
的方法,输入变量为
uint
a
, 输出为
uint b

uint 代表无状态的整型数字,即大于0的整数
uint = uint256, 最大值为2的256次方,这个数字对于绝大多数的数学运算是足够得了。
相对于uint来说还有带负数的整数类型,即int, int=int256, 取值范围从 
负2的128次方到正2的128次方

uint/int类型细节请参见后面的Int类型介绍。或者点击here

Function的核心代码

function f(uint a) returns (uint b)
{
uint result = a * 8;
return result;
}

这是一段很平常的js代码,值得注意的是以下两点

Solidity是一个类型语言,因此每个变量都需要定义他的类型,uint/int/string/var

Solidity is a statically typed language, which means that the type of each variable (state and local) needs to be specified (or at least known – see Type Deduction below) at compile-time. Solidity provides several elementary types which can be combined to form
complex types. 引用自here

关于编码风格 
uint
result = a * 8;
, solidity 鼓励在操作符中有一个空格。

More than one space around an assignment or other operator to align with 引用自here

Yes:

x = 1;
y = 2;
long_variable = 3;


更多关于Solidity的编码风格,请参考官方文档 https://solidity.readthedocs.io/en/develop/style-guide.html


经过上面的代码,我们知道了关于智能合约的一些基础知识,下篇将开始讲解Browser-solidity右侧的奥秘



QQ群:559649971 (区块链学堂粉丝群)

个人微信:steven_k_colin



获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  以太坊