【Solidity】学习(2)

address 地址类型

40个16进制数,160位

地址包括合约地址和账户地址

payable 合约充值

balance,指的是当前地址的账户value,单位是wei

this指的是当前合约的地址

可以通过地址查找账户余额

pragma solidity ^0.4.0;

contract value {
    //合约充值
    function pay() payable{
        
    }   
    function getvalve()  view returns(uint){
        address add = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
        return add.balance;//
    }
    function getthisvalve()  view returns(uint){
        return this.balance;//
    }
    
}

transfer

转账和将合约的价值转移  

pragma solidity ^0.4.0;

contract value {
    //合约充值
    function pay() payable{
        
    }
    //先pay(),再transfer
    function transfer10rther() payable{
        address receive = 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c;
        receive.transfer(10 ether);
    }
    //直接选择value的值,即可转换
    function transfeMSG() payable{
        address receive = 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c;
        receive.transfer(msg.value);
    }
    
}

send

send()方法和transfer()类似,但是不安全,在以下情况下会报错:

  • 递归深度大于1024
  • gas不足
pragma solidity ^0.4.0;

contract value {
    //合约充值
    function pay() payable{
        
    }
    function sendMoney() payable returns (bool){
        address receive = 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c;
        //在图形化界面,如果输入的value的值不是10,则返回false
        return receive.send(10 ether);
    }
    
}

mapping

映射

pragma solidity ^0.4.0;

contract value {
    mapping (uint =>string)namemapping;
    uint public sum =0;

    function initMap(string _name){
        namemapping[sum++] = _name;
        
    }
    function findNameById(uint _id) view returns(string){
        if(_id <=sum)
         return namemapping[_id];
        else
            return "worng";
    }
}

函数

function (<parameter types>){private|internal|external|public}
[pure|constant|view|payble][returns(<return types>)]

 

函数重载

功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同

 

pragma solidity ^0.4.0;

contract value {
    function f1(uint160 a)returns(string){
        return "a";
    }
    function f1(address add)returns(string){
        return "add";
    }
    function test()view returns(string) {
            //下面两个情况编译不通过,uint160和地址类型格式相同
        //f1(0xca35b7d915458ef540ade6068dfe2f44e8fa733c);
        //f1(1);
        address add = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
        return f1(add);
    }
}

 

pragma solidity ^0.4.0;

contract value {
    function f1(uint a,uint b)view returns(uint ,uint ){
        return (a+b,a*b);
    }
    function f2(uint a,uint b)view returns(uint add,uint mul){
        return (a+b,a*b);
    }
}

 

posted on 2019-04-01 22:09  孤笑  阅读(183)  评论(0编辑  收藏  举报