-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_contract.rb
480 lines (416 loc) · 15.1 KB
/
test_contract.rb
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
TEST_CONTRACT = <<CODE
scilla_version 0
(* HelloWorld contract *)
import ListUtils
(***************************************************)
(* Associated library *)
(***************************************************)
library HelloWorld
let one_msg =
fun (msg : Message) =>
let nil_msg = Nil {Message} in
Cons {Message} msg nil_msg
let not_owner_code = Int32 1
let set_hello_code = Int32 2
(***************************************************)
(* The contract definition *)
(***************************************************)
contract HelloWorld
(owner: ByStr20)
field welcome_msg : String = ""
transition setHello (msg : String)
is_owner = builtin eq owner _sender;
match is_owner with
| False =>
msg = {_tag : "Main"; _recipient : _sender; _amount : Uint128 0; code : not_owner_code};
msgs = one_msg msg;
send msgs
| True =>
welcome_msg := msg;
msg = {_tag : "Main"; _recipient : _sender; _amount : Uint128 0; code : set_hello_code};
msgs = one_msg msg;
send msgs
end
end
transition getHello ()
r <- welcome_msg;
e = {_eventname: "getHello()"; msg: r};
event e
end
transition multipleMsgs()
msg1 = {_tag : "Main"; _recipient : _sender; _amount : Uint128 0};
msg2 = {_tag : "Main"; _recipient : _sender; _amount : Uint128 0};
msgs1 = one_msg msg1;
msgs2 = Cons {Message} msg2 msgs1;
send msgs2
end
transition contrAddr()
msg1 = {_eventname : "ContractAddress"; addr : _this_address };
event msg1
end
CODE
ZRC20 = <<CODE
scilla_version 0
(* This contract implements a fungible token interface a la ERC20.*)
(***************************************************)
(* Associated library *)
(***************************************************)
library FungibleToken
let min_int =
fun (a : Uint128) => fun (b : Uint128) =>
let alt = builtin lt a b in
match alt with
| True =>
a
| False =>
b
end
let le_int =
fun (a : Uint128) => fun (b : Uint128) =>
let x = builtin lt a b in
match x with
| True => True
| False =>
let y = builtin eq a b in
match y with
| True => True
| False => False
end
end
(***************************************************)
(* The contract definition *)
(***************************************************)
contract FungibleToken
(owner : ByStr20,
total_tokens : Uint128)
(* Initial balance is not stated explicitly: it's initialized when creating the contract. *)
field balances : Map ByStr20 Uint128 =
let m = Emp ByStr20 Uint128 in
builtin put m owner total_tokens
field allowed : Map ByStr20 (Map ByStr20 Uint128) = Emp ByStr20 (Map ByStr20 Uint128)
transition BalanceOf (tokenOwner : ByStr20)
bal <- balances[tokenOwner];
match bal with
| Some v =>
e = {_eventname : "BalanceOf"; address : tokenOwner; balance : v};
event e
| None =>
e = {_eventname : "BalanceOf"; address : tokenOwner; balance : Uint128 0};
event e
end
end
transition TotalSupply ()
e = {_eventname : "TotalSupply"; caller : _sender; balance : total_tokens};
event e
end
transition Transfer (to : ByStr20, tokens : Uint128)
bal <- balances[_sender];
match bal with
| Some b =>
can_do = le_int tokens b;
match can_do with
| True =>
(* subtract tokens from _sender and add it to "to" *)
new_sender_bal = builtin sub b tokens;
balances[_sender] := new_sender_bal;
(* Adds tokens to "to" address *)
to_bal <- balances[to];
new_to_bal = match to_bal with
| Some x => builtin add x tokens
| None => tokens
end;
balances[to] := new_to_bal;
e = {_eventname : "TransferSuccess"; sender : _sender; recipient : to; amount : tokens};
event e
| False =>
(* balance not sufficient. *)
e = {_eventname : "TransferFailure"; sender : _sender; recipient : to; amount : Uint128 0};
event e
end
| None =>
(* no balance record, can't transfer *)
e = {_eventname : "TransferFailure"; sender : _sender; recipient : to; amount : Uint128 0};
event e
end
end
transition TransferFrom (from : ByStr20, to : ByStr20, tokens : Uint128)
bal <- balances[from];
(* Check if _sender has been authorized by "from" *)
sender_allowed_from <- allowed[from][_sender];
match bal with
| Some a =>
match sender_allowed_from with
| Some b =>
(* We can only transfer the minimum of available or authorized tokens *)
t = min_int a b;
can_do = le_int tokens t;
match can_do with
| True =>
(* tokens is what we should subtract from "from" and add to "to" *)
new_from_bal = builtin sub a tokens;
balances[from] := new_from_bal;
to_bal <- balances[to];
match to_bal with
| Some tb =>
new_to_bal = builtin add tb tokens;
balances[to] := new_to_bal
| None =>
(* "to" has no balance. So just set it to tokens *)
balances[to] := tokens
end;
(* reduce "allowed" by "tokens" *)
new_allowed = builtin sub b tokens;
allowed[from][_sender] := new_allowed;
e = {_eventname : "TransferFromSuccess"; sender : from; recipient : to; amount : tokens};
event e
| False =>
e = {_eventname : "TransferFromFailure"; sender : from; recipient : to; amount : Uint128 0};
event e
end
| None =>
e = {_eventname : "TransferFromFailure"; sender : from; recipient : to; amount : Uint128 0};
event e
end
| None =>
e = {_eventname : "TransferFromFailure"; sender : from; recipient : to; amount : Uint128 0};
event e
end
end
transition Approve (spender : ByStr20, tokens : Uint128)
allowed[_sender][spender] := tokens;
e = {_eventname : "ApproveSuccess"; approver : _sender; spender : spender; amount : tokens};
event e
end
transition Allowance (tokenOwner : ByStr20, spender : ByStr20)
spender_allowance <- allowed[tokenOwner][spender];
match spender_allowance with
| Some n =>
e = {_eventname : "Allowance"; owner : tokenOwner; spender : spender; amount : n};
event e
| None =>
e = {_eventname : "Allowance"; owner : tokenOwner; spender : spender; amount : Uint128 0};
event e
end
end
CODE
SIMPLE_DEX = <<CODE
scilla_version 0
import PairUtils
(* Simple DEX : P2P Token Trades *)
(* Disclaimer: This contract is experimental and meant for testing purposes only *)
(* DO NOT USE THIS CONTRACT IN PRODUCTION *)
library SimpleDex
(* Pair helpers *)
let getAddressFromPair = @fst (ByStr20) (Uint128)
let getValueFromPair = @snd (ByStr20) (Uint128)
(* Event for errors *)
let make_error_event =
fun (location: String) =>
fun (msg: String) =>
{ _eventname : "Error" ; raisedAt: location; message: msg}
(* Order = { tokenA, valueA, tokenB, valueB } *)
type Order =
| Order of ByStr20 Uint128 ByStr20 Uint128
(* Create an orderID based on the hash of the parameters *)
let createOrderId =
fun (order: Order) =>
builtin sha256hash order
(* Create one transaction message *)
let transaction_msg =
fun (recipient : ByStr20) =>
fun (tag : String) =>
fun (transferFromAddr: ByStr20) =>
fun (transferToAddr: ByStr20) =>
fun (transferAmt: Uint128) =>
{_tag : tag; _recipient : recipient; _amount : Uint128 0;
from: transferFromAddr; to: transferToAddr; tokens: transferAmt }
(* Wrap one transaction message as singleton list *)
let transaction_msg_as_list =
fun (recipient : ByStr20) =>
fun (tag : String) =>
fun (transferFromAddr: ByStr20) =>
fun (transferToAddr: ByStr20) =>
fun (transferAmt: Uint128) =>
let one_msg =
fun (msg : Message) =>
let nil_msg = Nil {Message} in
Cons {Message} msg nil_msg in
let msg = transaction_msg recipient tag transferFromAddr transferToAddr transferAmt in
one_msg msg
(* Compute the new pending return val *)
(* If no existing records are found, return incomingTokensAmt *)
(* else, return incomingTokenAmt + existing value *)
let computePendingReturnsVal =
fun ( prevVal : Option Uint128 ) =>
fun ( incomingTokensAmt : Uint128 ) =>
match prevVal with
| Some v =>
builtin add v incomingTokensAmt
| None =>
incomingTokensAmt
end
let success = "Success"
(***************************************************)
(* The contract definition *)
(***************************************************)
contract SimpleDex
(contractOwner: ByStr20)
(* Orderbook: mapping (orderIds => ( (tokenA, valueA) (tokenB, valueB) )) *)
(* @param: tokenA: Contract address of token A *)
(* @param: valueA: total units of token A offered by maker *)
(* @param: tokenB: Contract address of token B *)
(* @param: valueB: total units of token B requsted by maker *)
field orderbook : Map ByStr32 Order
= Emp ByStr32 Order
(* Order info stores the mapping ( orderId => (tokenOwnerAddress, expirationBlock)) *)
field orderInfo : Map ByStr32 (Pair (ByStr20)(BNum)) = Emp ByStr32 (Pair (ByStr20) (BNum))
(* Ledger of how much the _sender can claim from the contract *)
(* mapping ( walletAddress => mapping (tokenContracts => amount) ) *)
field pendingReturns : Map ByStr20 (Map ByStr20 Uint128) = Emp ByStr20 (Map ByStr20 Uint128)
(* Maker creates an order to exchange valueA of tokenA for valueB of tokenB *)
transition makeOrder(tokenA: ByStr20, valueA: Uint128, tokenB: ByStr20, valueB: Uint128, expirationBlock: BNum)
currentBlock <- & BLOCKNUMBER;
validExpirationBlock = let minBlocksFromCreation = Uint128 50 in
let minExpiration = builtin badd currentBlock minBlocksFromCreation in
builtin blt minExpiration expirationBlock;
match validExpirationBlock with
| True =>
(* Creates a new order *)
newOrder = Order tokenA valueA tokenB valueB;
orderId = createOrderId newOrder;
orderbook[orderId] := newOrder;
(* Updates orderInfo with maker's address and expiration blocknumber *)
p = Pair {(ByStr20) (BNum)} _sender expirationBlock;
orderInfo[orderId] := p;
e = {_eventname: "Order Created"; hash: orderId };
event e;
(* Transfer tokens from _sender to the contract address *)
msgs = let tag = "TransferFrom" in
let zero = Uint128 0 in
transaction_msg_as_list tokenA tag _sender _this_address valueA;
send msgs
| False =>
e = let func = "makeOrder" in
let error_msg = "Expiration block must be at least 50 blocks more than current block" in
make_error_event func error_msg;
event e
end
end
(* Taker fills an order *)
transition fillOrder(orderId: ByStr32)
getOrder <- orderbook[orderId];
match getOrder with
| Some (Order tokenA valueA tokenB valueB)=>
(* Check the expiration block *)
optionOrderInfo <- orderInfo[orderId];
match optionOrderInfo with
| Some info =>
currentBlock <- & BLOCKNUMBER;
blockBeforeExpiration = let getBNum = @snd (ByStr20) (BNum) in
let expirationBlock = getBNum info in
builtin blt currentBlock expirationBlock;
match blockBeforeExpiration with
| True =>
makerAddr = let getMakerAddr = @fst (ByStr20)(BNum) in
getMakerAddr info;
(* Updates taker with the tokens that he is entitled to claim *)
prevVal <- pendingReturns[_sender][tokenA];
takerAmt = computePendingReturnsVal prevVal valueA;
pendingReturns[_sender][tokenA] := takerAmt;
prevVal <- pendingReturns[makerAddr][tokenB];
makerAmt = computePendingReturnsVal prevVal valueB;
pendingReturns[makerAddr][tokenB] := makerAmt;
(* Delete orders from the orderbook and orderinfo *)
delete orderInfo[orderId];
delete orderbook[orderId];
e = {_eventname: "Order Filled"; hash: orderId };
event e;
(* Transfer tokens from _sender to the contract address *)
msgs = let tag = "TransferFrom" in
transaction_msg_as_list tokenB tag _sender _this_address valueB;
send msgs
| False =>
e = let func = "fillOrder" in
let error_msg = "Current block number exceeds the expiration block set" in
make_error_event func error_msg;
event e
end
| None =>
e = let func = "fillOrder" in
let error_msg = "OrderId not found" in
make_error_event func error_msg;
event e
end
| None =>
e = let func = "fillOrder" in
let error_msg = "OrderId not found" in
make_error_event func error_msg;
event e
end
end
(* Allows users to claim back their tokens from the smart contract *)
transition ClaimBack(token: ByStr20)
getAmtOutstanding <- pendingReturns[_sender][token];
match getAmtOutstanding with
| Some amtOutstanding =>
delete pendingReturns[_sender][token];
e = {_eventname: "Claimback Successful"; caller: _sender; tokenAddr: token; amt: amtOutstanding };
event e;
(* Transfer tokens from _sender to the contract address *)
msgs = let tag = "TransferFrom" in
transaction_msg_as_list token tag _this_address _sender amtOutstanding;
send msgs
| None =>
e = let func = "claimBack" in
let error_msg = "No Pending Returns for Sender and Contract Address found" in
make_error_event func error_msg;
event e
end
end
(* Maker can cancel his order *)
transition cancelOrder(orderId: ByStr32)
getOrderInfo <- orderInfo[orderId];
match getOrderInfo with
| Some orderInfo =>
makerAddr = let getMakerAddr = @fst (ByStr20)(BNum) in
getMakerAddr orderInfo;
checkSender = builtin eq makerAddr _sender;
match checkSender with
| True =>
(* Sender is the maker, proceed with cancellation *)
fetchOrder <- orderbook[orderId];
match fetchOrder with
| Some (Order tokenA valueA _ _)=>
(* Updates taker with the tokens that he is entitled to claim *)
prevVal <- pendingReturns[_sender][tokenA];
takerAmt = computePendingReturnsVal prevVal valueA;
pendingReturns[_sender][tokenA] := takerAmt;
(* Delete orders from the orderbook and orderinfo *)
delete orderInfo[orderId];
delete orderbook[orderId];
e = {_eventname: "Cancel order successful"; hash: orderId };
event e
(* @note: For consistency, we use claimback instead of sending the tokens *)
(* back to the maker *)
| None =>
e = let func = "cancelOrder" in
let error_msg = "OrderID not found" in
make_error_event func error_msg;
event e
end
| False =>
(* Unauthorized transaction *)
e = let func = "cancelOrder" in
let error_msg = "Sender is not maker of the order" in
make_error_event func error_msg;
event e
end
| None =>
(* Order ID not found *)
e = let func = "cancelOrder" in
let error_msg = "OrderID not found" in
make_error_event func error_msg;
event e
end
end
CODE