forked from ArweaveTeam/SmartWeave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.js
66 lines (51 loc) · 1.91 KB
/
token.js
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
// This contract is a token contract that supports divisibility.
// As long as the max supply of the token is <= Number.MAX_SAFE_INTEGER
// This will work fine, (all operations are done as integer values)
export function handle (state, action) {
const balances = state.balances
const input = action.input
const caller = action.caller
if (input.function === 'transfer') {
const target = input.target
if (isNaN(input.qty)) {
throw new ContractError('Invalid quantity')
}
const qty = Math.trunc(parseFloat(input.qty) * state.divisibility)
if (!target) {
throw new ContractError('No target specified')
}
if (qty <= 0 || caller === target) {
throw new ContractError('Invalid token transfer')
}
if (!(caller in balances)) {
throw new ContractError("Caller doesn't have a balance.");
}
if (balances[caller] < qty) {
throw new ContractError(`Caller balance not high enough to send ${qty} token(s)!`)
}
// Lower the token balance of the caller
balances[caller] -= qty
if (target in balances) {
// Wallet already exists in state, add new tokens
balances[target] += qty
} else {
// Wallet is new, set starting balance
balances[target] = qty
}
return { state }
}
if (input.function === 'balance') {
const target = input.target
const ticker = state.ticker
const divisibility = state.divisibility
const balance = balances[target] / divisibility
if (typeof target !== 'string') {
throw new ContractError('Must specificy target to get balance for')
}
if (typeof balances[target] !== 'number') {
throw new ContractError('Cannnot get balance, target does not exist')
}
return { result: { target, ticker, balance: balance.toFixed(divisibility), divisibility } }
}
throw new ContractError(`No function supplied or function not recognised: "${input.function}"`)
}