|
| 1 | +const DEBUG = false; |
| 2 | + |
| 3 | +// ewasm main function |
| 4 | +export function main(): void { |
| 5 | + // assume the memory is already expanded.. |
| 6 | + // ethereum_return(0, ethereum_callDataSize()) |
| 7 | + |
| 8 | + // Make sure we have enough args |
| 9 | + if (getCallDataSize() < 4) |
| 10 | + revert(0, 0); |
| 11 | + |
| 12 | + var ptrSelector = <i32>allocate_memory(4); |
| 13 | + callDataCopy(ptrSelector, 0, 4); |
| 14 | + var selector = load<i32>(ptrSelector); |
| 15 | + switch(selector) { |
| 16 | + case 0x9993021a: |
| 17 | + do_balance(); |
| 18 | + break; |
| 19 | + case 0x5d359fbd: |
| 20 | + do_transfer(); |
| 21 | + break; |
| 22 | + default: |
| 23 | + revert(0, 0); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +function do_balance(): void { |
| 28 | + if (getCallDataSize() !== 24) |
| 29 | + revert(0, 0); |
| 30 | + |
| 31 | + var ptrAddress = <i32>allocate_memory(20); |
| 32 | + callDataCopy(ptrAddress, 4, 20); |
| 33 | + var ptrBalance = <i32>allocate_memory(32); |
| 34 | + storageLoad(ptrAddress, ptrBalance); |
| 35 | + if (DEBUG) { |
| 36 | + printMemHex(ptrAddress, 32); |
| 37 | + printMemHex(ptrBalance, 32); |
| 38 | + } |
| 39 | + finish(ptrBalance, 32); |
| 40 | +} |
| 41 | + |
| 42 | +function do_transfer(): void { |
| 43 | + if (getCallDataSize() !== 32) |
| 44 | + revert(0, 0); |
| 45 | + |
| 46 | + var ptrSender = <i32>allocate_memory(32); |
| 47 | + getCaller(ptrSender); |
| 48 | + var ptrRecipient = <i32>allocate_memory(32); |
| 49 | + callDataCopy(ptrRecipient, 4, 20); |
| 50 | + var ptrValue = <i32>allocate_memory(32); |
| 51 | + callDataCopy(ptrValue, 24, 8); |
| 52 | + // debug_printMemHex(ptrValue, 32); |
| 53 | + var ptrSenderBalance = <i32>allocate_memory(32); |
| 54 | + var ptrRecipientBalance = <i32>allocate_memory(32); |
| 55 | + storageLoad(ptrSender, ptrSenderBalance); |
| 56 | + storageLoad(ptrRecipient, ptrRecipientBalance); |
| 57 | + if (DEBUG) { |
| 58 | + printMemHex(ptrSender, 32); |
| 59 | + printMemHex(ptrRecipient, 32); |
| 60 | + printMemHex(ptrSenderBalance, 32); |
| 61 | + printMemHex(ptrRecipientBalance, 32); |
| 62 | + } |
| 63 | + var senderBalance = load<i32>(ptrSenderBalance); |
| 64 | + var recipientBalance = load<i32>(ptrRecipientBalance); |
| 65 | + var value = load<i32>(ptrValue); |
| 66 | + |
| 67 | + if (senderBalance < value) |
| 68 | + revert(0, 0); |
| 69 | + |
| 70 | + store<i32>(ptrSenderBalance, senderBalance - value); |
| 71 | + store<i32>(ptrRecipientBalance, recipientBalance + value); |
| 72 | + storageStore(ptrSender, ptrSenderBalance); |
| 73 | + storageStore(ptrRecipient, ptrRecipientBalance); |
| 74 | +} |
0 commit comments