本质上来说,智能合约是一段程序,它以计算机指令的方式实现了传统合约的自动化处理。智能合约程序不只是一个可以自动执行的计算机程序,它本身就是一个系统参与者,对接收到的信息进行回应,可以接收和储存价值,也可以向外发送信息和价值。
简单讲,智能合约就是双方在区块链资产上交易时,触发执行的一段代码,这段代码就是智能合约。提前规定好合约的内容,当在满足触发合约条件的时候,程序就会自动执行合约内容。
在区块链应用开发过程中,需要调用您的智能合约,智能合约主要用于调用区块链。为提高基于链上的开发效率,BaaS平台提供了Cloud IDE智能合约开发工具和离线智能合约开发工具,帮助您快速实现智能合约的开发。
添加的代码中包括add(),sub(),mul(),sqr()和sqrt()函数:
contract mymath{
function sqrt(uint x)public view returns(uint y){
uint z=(x+1)/2;
y=x;
while(z<y){
y=z;
z=(x/z+z)/2;
}
}
function sqr(uint a)public view returns(uint){
uint c=a*a;
return c;
}
function mul(uint a,uint b)public view returns(uint){
uint c=a*b;
return c;
}
function sub(uint a,uint b)public view returns(uint){
return a-b;
}
function add(uint a,uint b)public view returns(uint){
uint c=a+b;
return c;
}}
现在编译我们的智能合约,并生成ABI(应用程序二进制接口)。通过ABI,我们可以创建智能合约中所有数据元素和函数。这通常用JSON格式定义。在我们的例子中,ABI是(可以从Remix中的ABI复制按钮中复制):
{
"inputs":[
{
"internalType":"uint256",
"name":"a",
"type":"uint256"
},
{
"internalType":"uint256",
"name":"b",
"type":"uint256"
}
],
"name":"add",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"a",
"type":"uint256"
},
{
"internalType":"uint256",
"name":"b",
"type":"uint256"
}
],
"name":"mul",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"a",
"type":"uint256"
}
],
"name":"sqr",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"x",
"type":"uint256"
}
],
"name":"sqrt",
"outputs":[
{
"internalType":"uint256",
"name":"y",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"a",
"type":"uint256"
},
{
"internalType":"uint256",
"name":"b",
"type":"uint256"
}
],
"name":"sub",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
}