MCPcopy
hub / github.com/yeasy/blockchain_guide / BuyByAddress

Method BuyByAddress

11_app_dev/chaincode_example05.go:73–133  ·  view source on GitHub ↗
(ctx contractapi.TransactionContextInterface, sellerAddress string, buyerSignature string, buyerAddress string, energy string)

Source from the content-addressed store, hash-verified

71}
72
73func (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

Callers

nothing calls this directly

Calls 8

readHomeFunction · 0.85
putHomeFunction · 0.85
energyTransactionKeyFunction · 0.85
parsePositiveAmountFunction · 0.70
validSignatureFunction · 0.70
nextIDFunction · 0.70
txUnixTimeFunction · 0.70
putJSONFunction · 0.70

Tested by

no test coverage detected