-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample_token.go
391 lines (351 loc) · 12.5 KB
/
sample_token.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package main
import (
. "erc20/helpers"
"erc20/lib/erc20basic"
"erc20/lib/erc20burnable"
"erc20/lib/erc20detailed"
"erc20/lib/erc20mintable"
"erc20/lib/erc20ownable"
"erc20/lib/erc20pausable"
"fmt"
"math/big"
"strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
//InitialMintAmount * 10^(token decimals) is the initial `total supply` of tokens
const InitialMintAmount int64 = 1000000000
var logger = shim.NewLogger("token-logger")
/*SampleToken is a simple ERC20 Token example. Refer to https://eips.ethereum.org/EIPS/eip-20 for documentations.*/
type SampleToken struct {
erc20basic.BasicTokenInterface
erc20ownable.OwnableTokenInterface
erc20detailed.DetailedTokenInterface
erc20mintable.MintableTokenInterface
erc20burnable.BurnableTokenInterface
erc20pausable.PausableTokenInterface
}
// main function starts up the chaincode in the container during instantiate
func main() {
//new instance of token that mostly implements standard library
//erc20 basic type is extended with "memo" functionality
sampleToken := &SampleToken{
&CustomBasicToken{},
&erc20ownable.Token{},
&erc20detailed.Token{},
&erc20mintable.Token{},
&erc20burnable.Token{},
&erc20pausable.Token{},
}
if err := shim.Start(sampleToken); err != nil {
panic(err)
}
}
//#region chain code implementation
/*Init chaincode for Token, this method is called when we instantiate or upgrade our token.
(https://hyperledger-fabric.readthedocs.io/en/release-1.4/chaincode4ade.html#initializing-the-chaincode).
Init takes in one argument as a JSON-formatted string for token configurations, specifies the token attributes.
Owner of the token is also initialized as the contract's invoker.
Examples: `{"name": "tokenName", "symbol": "tokenSymbol", "decimals": "18"}`*/
func (t *SampleToken) Init(stub shim.ChaincodeStubInterface) peer.Response {
callerID, err := GetCallerID(stub)
if err != nil {
return shim.Error(err.Error())
}
// if this is not the first init call (chaincode upgrade)
// then owner validation is needed
if currentOwner, _ := t.GetOwner(stub); strings.TrimSpace(currentOwner) != "" {
logger.Infof("Upgrading chaincode using %v...", callerID)
if err := CheckCallerIsOwner(callerID, currentOwner); err != nil {
return shim.Error(err.Error())
}
} else {
logger.Infof("Init chaincode using %v...", callerID)
// if this is first call, then initialize states
args := stub.GetStringArgs()
if err := CheckArgsLength(args, 1); err != nil {
return shim.Error(err.Error())
}
coinConfig := JSONToMap(args[0])
// checks if "decimals" is a string of number format
n := StringToInt(coinConfig["decimals"].(string))
err = stub.PutState("owner", []byte(callerID))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState("name", []byte(coinConfig["name"].(string)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState("symbol", []byte(coinConfig["symbol"].(string)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState("decimals", []byte(coinConfig["decimals"].(string)))
if err != nil {
return shim.Error(err.Error())
}
//mint the initial total supply
//https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/examples/SimpleToken.sol
//activate the owner account first
err = t.Activate(stub, []string{callerID}, t.GetBalanceOf)
if err != nil {
return shim.Error(err.Error())
}
err = t.Mint(stub,
[]string{callerID, Mul(big.NewInt(InitialMintAmount), Pow(10, n)).String()},
withOwnerIs(callerID),
withInitialBalanceOf(0),
t.GetTotalSupply,
)
if err != nil {
return shim.Error(err.Error())
}
}
return shim.Success(nil)
}
//bypass the instance's own GetBalanceOf method to avoid "user is not registered" error as the caller is not
//activated during first initialization phase (uncommitted transaction)
func withInitialBalanceOf(initialBalance int64) func(stub shim.ChaincodeStubInterface, args []string) (*big.Int, error) {
return func(stub shim.ChaincodeStubInterface, args []string) (*big.Int, error) {
return big.NewInt(initialBalance), nil
}
}
func withOwnerIs(owner string) func(shim.ChaincodeStubInterface) (string, error) {
return func(shim.ChaincodeStubInterface) (string, error) {
return owner, nil
}
}
/*Invoke is called per transaction on the chaincode*/
func (t *SampleToken) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
methodName, params := stub.GetFunctionAndParameters()
//some functions are locked when the token state is "paused"
isPaused, err := t.IsPaused(stub)
if err != nil {
return shim.Error(err.Error())
}
if isPaused {
switch methodName {
case "Transfer", "TransferFrom", "UpdateApproval":
return shim.Error("Calling " + methodName + " is not allowed when token is paused")
}
}
switch methodName {
case "GetBalanceOf":
f, err := t.GetBalanceOf(stub, params)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(f.String()))
case "GetTotalSupply":
f, err := t.GetTotalSupply(stub)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(f.String()))
case "GetAllowance":
f, err := t.GetAllowance(stub, params)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(f.String()))
case "GetOwner":
s, err := t.GetOwner(stub)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(s))
case "TransferOwnership":
err := t.TransferOwnership(stub, params, t.GetOwner)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "GetName":
s, err := t.GetName(stub)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(s))
case "GetSymbol":
s, err := t.GetSymbol(stub)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(s))
case "GetDecimals":
s, err := t.GetDecimals(stub)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(s))
case "Mint":
err := t.Mint(stub, params, t.GetOwner, t.GetBalanceOf, t.GetTotalSupply)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "Burn":
err := t.Burn(stub, params, t.GetTotalSupply, t.GetBalanceOf)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "BurnFrom":
err := t.BurnFrom(stub, params, t.GetAllowance, t.GetTotalSupply, t.GetBalanceOf)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "Transfer":
err := t.Transfer(stub, params, t.GetBalanceOf)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "TransferFrom":
err := t.TransferFrom(stub, params, t.GetBalanceOf, t.GetAllowance)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "UpdateApproval":
err := t.UpdateApproval(stub, params)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "Pause":
err := t.Pause(stub, t.GetOwner)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "Unpause":
err := t.Unpause(stub, t.GetOwner)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "GetMemo":
s, err := t.GetMemo(stub, params)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(s))
case "Activate":
err := t.Activate(stub, params, t.GetBalanceOf)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
return shim.Error("Input function is not defined in chaincode")
}
//#endregion chain code implementation
//#region custom non-standard ERC20 implementation (transaction memo)
var customLogger = shim.NewLogger("memo-logger")
/*CustomBasicToken adds "memo" feature on top of basic ERC20 implementation*/
type CustomBasicToken struct {
parentToken *erc20basic.Token
}
/*GetTotalSupply reimplement erc20basic's GetTotalSupply method*/
func (t *CustomBasicToken) GetTotalSupply(stub shim.ChaincodeStubInterface) (*big.Int, error) {
return t.parentToken.GetTotalSupply(stub)
}
/*GetAllowance reimplement erc20basic's GetAllowance method*/
func (t *CustomBasicToken) GetAllowance(stub shim.ChaincodeStubInterface, args []string) (*big.Int, error) {
return t.parentToken.GetAllowance(stub, args)
}
/*UpdateApproval reimplement erc20basic's UpdateApproval method*/
func (t *CustomBasicToken) UpdateApproval(stub shim.ChaincodeStubInterface, args []string) error {
return t.parentToken.UpdateApproval(stub, args)
}
/*GetMemo is a customed non standard erc20 that return the last memo string attached with transaction.
* `args[0]` - the key ID of target client.*/
func (t *SampleToken) GetMemo(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if err := CheckArgsLength(args, 1); err != nil {
return "", err
}
//expect only one element in iterator
iterator, err := stub.GetStateByPartialCompositeKey("Memo", args)
defer iterator.Close()
if err != nil {
customLogger.Errorf("[sample-token.GetMemo] error after GetStateByPartialCompositeKey: %v", err)
return "", err
}
if iterator.HasNext() {
customLogger.Infof("Getting last memo from composite key %v", args[0])
queryResult, err := iterator.Next()
return string(queryResult.GetValue()), err
}
customLogger.Warningf("Memo not found for ID %v", args[0])
return "", fmt.Errorf("Memo not found for ID %v", args[0])
}
/*Transfer adds "memo" feature after erc20basic's Transfer method*/
func (t *CustomBasicToken) Transfer(stub shim.ChaincodeStubInterface, args []string, getBalanceOf func(shim.ChaincodeStubInterface, []string) (*big.Int, error)) error {
err := t.parentToken.Transfer(stub, args, getBalanceOf)
if err != nil {
return err
}
//assumes the 3rd element in `args` is the comment
if len(args) == 3 {
receiverID, _, comment := args[0], args[1], args[2]
return setMemo(stub, receiverID, comment)
}
return nil
}
/*TransferFrom adds "memo" feature after erc20basic's TransferFrom method*/
func (t *CustomBasicToken) TransferFrom(stub shim.ChaincodeStubInterface,
args []string,
getBalanceOf func(shim.ChaincodeStubInterface, []string) (*big.Int, error),
getAllowance func(shim.ChaincodeStubInterface, []string) (*big.Int, error),
) error {
err := t.parentToken.TransferFrom(stub, args, getBalanceOf, getAllowance)
if err != nil {
return err
}
//assumes the 4th element in `args` is the comment
if len(args) == 4 {
_, receiverID, _, comment := args[0], args[1], args[2], args[3]
return setMemo(stub, receiverID, comment)
}
return nil
}
//setMemo updates world-state with a composite key of objectType "Memo", attribute of `key` and value of `memo`
func setMemo(stub shim.ChaincodeStubInterface, key string, memo string) error {
memoKey, err := stub.CreateCompositeKey("Memo", []string{key})
if err != nil {
return err
}
customLogger.Infof("setting %v to memo %v", memoKey, memo)
return stub.PutState(memoKey, []byte(memo))
}
/*GetBalanceOf is customed version of ERC20's standard, it rejects unregistered clients*/
func (t *CustomBasicToken) GetBalanceOf(stub shim.ChaincodeStubInterface, args []string) (*big.Int, error) {
tokenBalance, err := stub.GetState(args[0])
logger.Infof("[sample-token.GetBalanceOf] balance of %v: %v", args[0], string(tokenBalance))
// if the returned buffer is empty, this account is not registered
if len(tokenBalance) == 0 {
logger.Noticef("[sample-token.GetBalanceOf] %v is not registered", args[0])
return nil, fmt.Errorf("%v is not registered", args[0])
}
return BufferToBigInt(DefaultToZeroIfEmpty(tokenBalance)), err
}
/*Activate is a customed non standard erc20 that set the balance of client to "0".
This marks the active state of target so that subsequent Transfer operations will be successful
* `args[0]` - the key ID of target client.*/
func (t *SampleToken) Activate(stub shim.ChaincodeStubInterface, args []string, getBalanceOf func(shim.ChaincodeStubInterface, []string) (*big.Int, error)) error {
clientID := args[0]
balanceOfReceiver, err := getBalanceOf(stub, []string{clientID})
//if the client is never activated before
if err != nil && balanceOfReceiver == nil {
logger.Noticef("[sample-token.Activate] registering %v...", clientID)
// set the buffer to "0"
// so the next time (customed) `GetBalanceOf` is called it won't show error
return stub.PutState(clientID, []byte{48})
}
logger.Errorf("[sample-token.Activate] %v is already registered", clientID)
return fmt.Errorf("%v is already registered", clientID)
}
//#endregion custom non-standard ERC20 implementation (transaction memo)