Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. pragma solidity >=0.4.21 <0.6.0;
  2.  
  3. contract GiftRegistry {
  4.  
  5. uint256 idCounter = 0;
  6. enum GiftStatus { Offered }
  7.  
  8. struct Gift {
  9. string description;
  10. uint256 value;
  11. GiftStatus status;
  12. address giftGiver;
  13. address giftReceiver;
  14. address giftApprover;
  15. }
  16.  
  17. mapping(uint256 => Gift) public giftMap;
  18.  
  19. function doesGiftExist(uint256 _giftId) private view returns(bool){
  20. Gift memory gift = giftMap[_giftId];
  21. bytes memory giftAsBytes = bytes(gift.description);
  22.  
  23. return giftAsBytes.length > 0;
  24. }
  25.  
  26. function getGift(uint256 _giftId) public view returns(string memory, uint256, GiftStatus, address, address, address){
  27. require(doesGiftExist(_giftId), 'Gift not found');
  28. Gift memory gift = giftMap[_giftId];
  29.  
  30. return (
  31. gift.description,
  32. gift.value,
  33. gift.status,
  34. gift.giftGiver,
  35. gift.giftReceiver,
  36. gift.giftApprover
  37. );
  38. }
  39.  
  40. function offerGift(string memory _description, uint256 _value, address _giftReceiver) public returns(uint256) {
  41. uint256 currentId = idCounter;
  42. giftMap[currentId] = Gift(_description, _value, GiftStatus.Offered, msg.sender, _giftReceiver, address(0));
  43.  
  44. idCounter = idCounter + 1;
  45.  
  46. return currentId;
  47. }
  48. }
  49.  
  50. const GiftRegistry = artifacts.require('GiftRegistry');
  51. const truffleAssert = require('truffle-assertions');
  52.  
  53. contract('The Gift Registry contract', accounts => {
  54. let contract;
  55. const giftGiverAddress = accounts[1];
  56. const giftReceiverAddress = accounts[2];
  57.  
  58. beforeEach(async () => {
  59. contract = await GiftRegistry.new({from: accounts[0]});
  60. });
  61.  
  62. describe('given offerGift is called', () => {
  63. const OfferedStatus = 0;
  64.  
  65. it('the status should be set to offered', async () => {
  66. const fiveDollars = 500;
  67. // Calling like this returns a tx instead of the id, the gift can be found with a hard coded index of 0
  68. const giftId1 = await contract.offerGift('coffee', fiveDollars, giftReceiverAddress, {from: giftGiverAddress});
  69. // This call returns the new giftId, however the gift can't be found and the call to getGift throws the error
  70. // Error: Returned error: VM Exception while processing transaction: revert Gift not found
  71. const giftId2 = await contract.offerGift.call('coffee', fiveDollars, giftReceiverAddress, {from: giftGiverAddress});
  72.  
  73. const gift = await contract.getGift.call(0);
  74.  
  75. assert.equal(OfferedStatus, gift[2]);
  76. });
  77.  
  78. });
  79. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement