Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Created March 21, 2018 05:29
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/da72e9fc84caf39e07d9b195f3b28e66 to your computer and use it in GitHub Desktop.
Save chiro-hiro/da72e9fc84caf39e07d9b195f3b28e66 to your computer and use it in GitHub Desktop.
Partime smart contract and test case

Mình viết lại smart contract, thêm hai function mới takeJob()viewJob():

    //Take job
    function
    takeJob (uint256 jobId)
    public onlyValidMortgage(jobId) onlyValidId(jobId) onlyValidJob(jobId)
    {
        //Trigger event to log labor
        TakeJob(jobId, msg.sender);

        //Change working state
        jobData[jobId].start = block.timestamp;
    }

    //Veiw job data
    function
    viewJob(uint256 jobId)
    public onlyValidId(jobId) constant returns (
    uint256 id,
    address creator,
    uint256 salary,
    uint256 start,
    uint256 end,
    uint256 timeOut,
    bytes title,
    bytes description)
    {
        Job memory jobReader = jobData[jobId];
        return (jobReader.id,
        jobReader.creator,
        jobReader.salary,
        jobReader.start,
        jobReader.end,
        jobReader.timeOut,
        jobReader.title,
        jobReader.description);
    }

Trong phần struct mình cũng update thêm các biến liên quan tới thời gian, và để tiện xử lý mình sẽ sữ dụng Unix timestamp (Solidity không có kiểu datime nên dùng Unix time là tiện nhất):

        uint256 start;
        uint256 end;
        uint256 timeOut;

Chúng ta có toàn bộ mã nguồn như sau:

pragma solidity ^0.4.18;


contract PartTime {
    
    //Job structure
    struct Job {
        uint256 id;
        address creator;
        uint256 salary;
        uint256 start;
        uint256 end;
        uint256 timeOut;
        bytes title;
        bytes description;
    }

    //New job append
    event NewJob(uint256 indexed id,
    address creator,
    uint256 salary,
    uint256 timeOut);

    //An woker start working
    event TakeJob(
    uint256 indexed id,
    address indexed labor);

    //Minium accept salary
    uint256 constant public MINIUM_SALARY = 0.1 ether;

    //The number of jobs
    uint256 public totalJob;

    //Mapped data
    mapping (uint256 => Job) public jobData;
    
    //Transaction must contant Ethereum
    modifier onlyHaveFund {
        require(msg.value > MINIUM_SALARY);
        _;
    }

    //Valid timeOut should be greater than 3 days
    modifier onlyValidTimeOut(uint256 timeOut) {
        require(timeOut > 3 days);
        _;
    }

    //Check valid job Id
    modifier onlyValidId(uint256 jobId) {
        require(jobId < totalJob);
        _;
    }

    //Mortgage should be greater than 1/10
    modifier onlyValidMortgage(uint256 jobId) {
        require(msg.value > jobData[jobId].salary/10);
        _;
    }

    //Check is it a taked job
    modifier onlyValidJob(uint256 jobId) {
        require(jobData[jobId].end == 0);
        require(jobData[jobId].start == 0);
        _;
    }

    //Append new job to mapping
    function
    createJob (uint256 timeOut, bytes title, bytes description)
    public onlyHaveFund onlyValidTimeOut(timeOut) payable returns(uint256 jobId)
    {
        // Saving a little gas by create a temporary object
        Job memory newJob;

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

        //Trigger event
        NewJob(jobId, msg.sender, msg.value, timeOut);

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

        return jobId;
    }

    //Take job
    function
    takeJob (uint256 jobId)
    public onlyValidMortgage(jobId) onlyValidId(jobId) onlyValidJob(jobId)
    {
        //Trigger event to log labor
        TakeJob(jobId, msg.sender);

        //Change working state
        jobData[jobId].start = block.timestamp;
    }

    //Veiw job data
    function
    viewJob(uint256 jobId)
    public onlyValidId(jobId) constant returns (
    uint256 id,
    address creator,
    uint256 salary,
    uint256 start,
    uint256 end,
    uint256 timeOut,
    bytes title,
    bytes description)
    {
        Job memory jobReader = jobData[jobId];
        return (jobReader.id,
        jobReader.creator,
        jobReader.salary,
        jobReader.start,
        jobReader.end,
        jobReader.timeOut,
        jobReader.title,
        jobReader.description);
    }
 
}

Và mình viết thêm test case bằng JavaScript:

var Partime = artifacts.require("./PartTime.sol");

function createTx(from, to, value = 0, gas = 1000000, gasPrice = 20000000) {
    return {
        from: from,
        to: to,
        gas: gas,
        gasPrice: gasPrice,
        value: value
    };
}

contract('Partime', function (accounts) {

    it('should have 0 total part time job', function () {
        return Partime.deployed().then(function (instance) {
            return instance.totalJob.call();
        }).then(function (totalJob) {
            assert.equal(totalJob.valueOf(), 0, 'Total job was not equal to 0');
        });
    });

    it('should able to add new job', function () {
        return Partime.deployed().then(function (instance) {
            return instance.createJob(((new Date()).getTime() / 1000 + 432000),
                "This is tittle",
                "This is description",
                createTx(accounts[0], instance.address, web3.toWei('1', 'ether')));
        }).then(function (totalJob) {
            assert.equal(typeof (totalJob.valueOf()), 'object', 'Transaction was not triggered success');
        });
    });

    it('should have total part time job geater than 0', function () {
        return Partime.deployed().then(function (instance) {
            return instance.totalJob.call();
        }).then(function (totalJob) {
            assert.equal(totalJob.valueOf() > 0, true, 'Total job was equal to 0' );
        });
    });

});

Bạn chú ý thấy mình đang thêm 1 job mới:

            return instance.createJob(((new Date()).getTime() / 1000 + 432000),
                "This is tittle",
                "This is description",
                createTx(accounts[0], instance.address, web3.toWei('1', 'ether')));

Đoạn code này có nghĩa là mình tạo ra 1 job có

  • Timeout: 5 ngày
  • Title: This is tittle
  • Description: This is description
  • Value: 1 Ethereum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment