(ctx contractapi.TransactionContextInterface, sellerAddress string, buyerSignature string, buyerAddress string, energy string)
| 71 | } |
| 72 | |
| 73 | func (s *SmartContract) BuyByAddress(ctx contractapi.TransactionContextInterface, sellerAddress string, buyerSignature string, buyerAddress string, energy string) (*EnergyTransaction, error) { |
| 74 | energyValue, err := parsePositiveAmount(energy) |
| 75 | if err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | if !validSignature(buyerAddress, buyerSignature) { |
| 79 | return nil, fmt.Errorf("invalid buyer signature") |
| 80 | } |
| 81 | |
| 82 | seller, err := readHome(ctx, sellerAddress) |
| 83 | if err != nil { |
| 84 | return nil, err |
| 85 | } |
| 86 | if seller.Status != homeAvailableForTrade { |
| 87 | return nil, fmt.Errorf("seller %s is not available for trading", sellerAddress) |
| 88 | } |
| 89 | buyer, err := readHome(ctx, buyerAddress) |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | if seller.Energy < energyValue { |
| 94 | return nil, fmt.Errorf("seller has insufficient energy") |
| 95 | } |
| 96 | if buyer.Money < energyValue { |
| 97 | return nil, fmt.Errorf("buyer has insufficient money") |
| 98 | } |
| 99 | |
| 100 | seller.Energy -= energyValue |
| 101 | seller.Money += energyValue |
| 102 | buyer.Energy += energyValue |
| 103 | buyer.Money -= energyValue |
| 104 | |
| 105 | if err := putHome(ctx, seller); err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | if err := putHome(ctx, buyer); err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | |
| 112 | id, err := nextID(ctx, energyTxCounterKey) |
| 113 | if err != nil { |
| 114 | return nil, err |
| 115 | } |
| 116 | timestamp, err := txUnixTime(ctx) |
| 117 | if err != nil { |
| 118 | return nil, err |
| 119 | } |
| 120 | transaction := &EnergyTransaction{ |
| 121 | BuyerAddress: buyerAddress, |
| 122 | BuyerAddressSign: buyerSignature, |
| 123 | SellerAddress: sellerAddress, |
| 124 | Energy: energyValue, |
| 125 | Money: energyValue, |
| 126 | ID: id, |
| 127 | Time: timestamp, |
| 128 | } |
| 129 | if err := putJSON(ctx, energyTransactionKey(id), transaction); err != nil { |
| 130 | return nil, err |
nothing calls this directly
no test coverage detected