Home > database >  How can I add a created at for smart contract?
How can I add a created at for smart contract?

Time:04-13

I'm writing a smart contract for patient records. But the data will be in time-series data format. And I guess I should add created_at field for that. But I don't know exactly how to do this.

I'm pretty new at this job. Can you help me?

You can see part of the struct:

    struct Patient {
        string name;
        uint16 age;
        //max of uint16 is 4096
        //if we use uint8 the max is uint8
        string telephone;
        string homeAddress;
        uint64 birthday; //unix time
        string disease; //disease can be enum
        Gender gender;
    }

CodePudding user response:

You can use the block.timestamp keyword for have current block timestamp as seconds since unix epoch which your transaction is included.

More information about block.timestamp here.

You must to set your createdAt variable into a struct:

struct Patient {
  string name;
  uint16 age;
  //max of uint16 is 4096
  //if we use uint8 the max is uint8
  string telephone;
  string homeAddress;
  uint64 birthday; //unix time
  string disease; //disease can be enum
  Gender gender;
  // NOTE: createdAt variable
  uint createdAt
}

And then you must use this statement for set this variable:

[your_struct_variable] = block.timestamp;

Example of smart contract code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Hospital {

    enum Gender { MALE, FEMALE }

    struct Patient {
        string name;
        uint16 age;
        //max of uint16 is 4096
        //if we use uint8 the max is uint8
        string telephone;
        string homeAddress;
        uint64 birthday; //unix time
        string disease; //disease can be enum
        Gender gender;
        uint256 createdAt;
    }

    mapping(address => Patient) _patients;

    function setPatients() public {
        Patient memory _patient = Patient({
            name: "test",
            age: 50,
            telephone: "test",
            homeAddress: "test",
            birthday: 1010101010,
            disease: "test",
            gender: Gender.MALE,
            createdAt: block.timestamp            
        });
        _patients[msg.sender] = _patient;
    }

    function getPatient() external view returns(Patient memory) {
        return _patients[msg.sender];
    }

}
  • Related