Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Last active March 14, 2018 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiro-hiro/65ae723196c9bbd29d362cd38f5bab4e to your computer and use it in GitHub Desktop.
Save chiro-hiro/65ae723196c9bbd29d362cd38f5bab4e to your computer and use it in GitHub Desktop.
PartTime smart contract

Toàn bộ smart contract như sau

pragma solidity ^0.4.17;

contract PartTime {
  
  struct Job {
    uint256 id;
    address creator;
    uint256 salary;
    bytes title;
    bytes description;
  }

  uint256 totalJob;

  mapping (uint256 => Job) public jobData;
  

  function createJob(uint256 salary, bytes title, bytes description)
  returns(uint256 jobId)
  {
    // Saving a little gas by create a temporary object
    Job memory newJob;

    // Assign jobId
    jobId = totalJob;
    
    newJob.id = jobId;
    newJob.title = title;
    newJob.description = description; 
    newJob.salary = salary;
    newJob.creator = msg.sender;

    // Append newJob to jobData
    jobData[totalJob++] = newJob;
  }
 
}

Struct job

Mình define struct Job chứa thông tin của một công việc part time, bao gồm các thông tin như id, title, description, salary, creator:

  struct Job {
    uint256 id;
    address creator;
    uint256 salary;
    bytes title;
    bytes description;
  }

Mapping dữ liệu

Mình muốn có thể chứa nhiều công việc trong smart contract, nên mình khai báo một mapping để chứa được nhiều jobs hơn, đoạn code này làm nhiệm vụ mapping một unsigned integer 256 bits vào một struct job:

mapping (uint256 => Job) public jobData;

Mapping thế này cho phép bạn truy cập lại dữ liệu cũ khi bạn có được index của dữ liệu, thông qua sử dụng toán tử [] (khá giống với array, nhưng dùng mapping tiết kiệm gas hơn).

Thêm một record vào bảng mapping

  function createJob(uint256 salary, bytes title, bytes description)
  returns(uint256 jobId)
  {
    // Saving a little gas by create a temporary object
    Job memory newJob;

    // Assign jobId
    jobId = totalJob;
    
    newJob.id = jobId;
    newJob.title = title;
    newJob.description = description; 
    newJob.salary = salary;
    newJob.creator = msg.sender;

    // Append newJob to jobData
    jobData[totalJob++] = newJob;
  }

Function này sẽ thêm một job vào phía cuối mapping table chứa rất nhiều struct job mà chúng ta lưu trong jobData.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment