forked from massalabs/massa-standards
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken-burn.ts
76 lines (67 loc) · 1.99 KB
/
token-burn.ts
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
import {
Storage,
Context,
Address,
generateEvent,
createEvent,
} from '@massalabs/massa-as-sdk';
import { Args, bytesToU64, u64ToBytes } from '@massalabs/as-types';
import { totalSupply, TOTAL_SUPPLY_KEY } from './token';
import { _balance, _setBalance } from './token-commons';
const BURN_EVENT_NAME = 'BURN';
/**
* Burn tokens from the caller address
*
* @param binaryArgs - byte string with the following format:
* - the amount of tokens to burn obn the caller address (u64).
*/
export function burn(binaryArgs: StaticArray<u8>): void {
const args = new Args(binaryArgs);
const amount = args.nextU64().expect('amount argument is missing or invalid');
const isDecreaseTotalSupplySuccess = _decreaseTotalSupply(amount);
assert(
isDecreaseTotalSupplySuccess,
'Requested burn amount causes an underflow',
);
const isBurnSuccess = _burn(Context.caller(), amount);
assert(isBurnSuccess, 'Requested burn amount causes an underflow');
generateEvent(
createEvent(BURN_EVENT_NAME, [
Context.caller().toString(),
amount.toString(),
]),
);
}
/**
* Removes amount of token from addressToBurn.
*
* @param addressToBurn -
* @param amount -
* @returns true if tokens has been burned
*/
function _burn(addressToBurn: Address, amount: u64): boolean {
const oldRecipientBalance = _balance(addressToBurn);
const newRecipientBalance = oldRecipientBalance - amount;
// Check underflow
if (oldRecipientBalance < newRecipientBalance) {
return false;
}
_setBalance(addressToBurn, newRecipientBalance);
return true;
}
/**
* Decreases the total supply of the token.
*
* @param amount -
* @returns true if the total supply has been decreased
*/
function _decreaseTotalSupply(amount: u64): boolean {
const oldTotalSupply = bytesToU64(totalSupply([]));
const newTotalSupply = oldTotalSupply - amount;
// Underflow
if (oldTotalSupply < newTotalSupply) {
return false;
}
Storage.set(TOTAL_SUPPLY_KEY, u64ToBytes(newTotalSupply));
return true;
}