128

请教各位大神:关于 Solidity 的 mapping 问题

jason_chen · 于 发布 · 最后由 jason_chen回复 · 817 次阅读
contract experiment {

    struct CommunityObj {
        string addr; //小区地址 主键
        string cname; //小区名字
        uint16 tree_num; //小区树的数量   
        mapping(uint8 => BuildingObj) buildingDB;
    }

    struct BuildingObj {
        uint8 tablet; //楼号  主键
        uint8 floor; //层数 
    }

    mapping(string => CommunityObj) communityDB;

    //输入信息
    function addinfo(string addr,string cnameuint16 tree_num,uint8 tablet,uint8 floor){

        CommunityObj community = communityDB[addr];
        community.addr = addr;
        community.cname = cname;
        community.tree_num = tree_num;
        community.buildingDB[tablet].tablet = tablet;
        community.buildingDB[tablet].floor = floor;
        }

        //读取信息
        function getinfo(string addr) returns(string cname,uint16 tree_num,uint8 tablet,uint8 floor){

        CommunityObj community = communityDB[addr];
        cname = community.cname;
        tree_num = community.tree_num;
        tablet = community.buildingDB[tablet].tablet;
        floor = community.buildingDB[tablet].floor;
        }

}

以上是合约程序,在web3.js中我在call getinfo信息时,只能读出cname、tree_num信息,而tablet和floor的信息读取为0,说明我之前没有写进去。
我的问题是mapping和struct不能嵌套使用吗?为什么我没能写进去,请各位指教!谢谢!

  • 51 large
    rubyu2

    你的getinfo函数有问题,这样写

      //读取信息
      function getinfo(string addr, uint8 _tablet) constant returns(string cname,uint16 tree_num,uint8 tablet,uint8 floor){
        CommunityObj community = communityDB[addr];
        cname = community.cname;
        tree_num = community.tree_num;
        tablet = community.buildingDB[_tablet].tablet;
        floor = community.buildingDB[_tablet].floor;
      }

    测试的代码:

    Experiment.addinfo.sendTransaction('123456', 'abc', 100, 10, 22, { from: web3.eth.accounts[0], gas:300000 }, function(err, tx){
      if(err){
        console.log('err!');
      } else {
        console.log('tx', tx);
      }
    })
    miner.start(2);
    admin.sleepBlocks(2);
    miner.stop();
    
    result = Experiment.getinfo.call('123456', 10, { from: web3.eth.accounts[0] });
    console.log('result: ', result[0], result[1].toNumber(), result[2].toNumber(), result[3].toNumber());
    
    // tx 0xbd44cf54d38809d9dea6f8a561ba8e0c029885b7a782997015090f8b6825e976
    // result:  abc 100 10 22

    链接:
    https://github.com/u2/solidity-assembly-practise/blob/master/contracts/Experiment.sol

    https://github.com/u2/solidity-assembly-practise/blob/master/test/experiment.js

  • 128
    jason_chen

    谢谢大神!醍醐灌顶啊!谢谢!
    另外
    function(err, tx){
    if(err){
    console.log('err!');
    } else {
    console.log('tx', tx);
    }
    }
    这个部分就是event监听?err是如何判断的?不能理解
    在function addinfo怎么添加event事件?

  • 51 large
    rubyu2

    这个不是 event 监听,event监听是用filter,你可以看下web3.js的文档。这里用的是 tx 的异步回调。

  • 128
    jason_chen

    @rubyu2 好的,谢谢!