Skip to content

Commit

Permalink
Use a hashmap for storing balances rather than a list, get rid of hel…
Browse files Browse the repository at this point in the history
…per functions
  • Loading branch information
jespern authored and aidanok committed Jun 17, 2020
1 parent 8ba7de9 commit eddfb1b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 35 deletions.
10 changes: 3 additions & 7 deletions examples/token-init.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
{
"ticker": "AR2.0",
"divisibility": 1000000,
"walletList":
[
{
"addr":"vLRHFqCw1uHu75xqB4fCDW-QxpkpJxBtFD9g4QYUbfw",
"balance": 2000000
}
]
"balances": {
"vLRHFqCw1uHu75xqB4fCDW-QxpkpJxBtFD9g4QYUbfw": 2000000
}
}
36 changes: 8 additions & 28 deletions examples/token.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
let opts = JSON.parse(input)
state = JSON.parse(state)
let wl = state.walletList
let balances = state.balances

if(opts.function == "transfer") {
let target = opts.target
Expand All @@ -11,18 +11,18 @@ if(opts.function == "transfer") {
}

// Don't do anything unless we have enough tokens
if(getBalance(caller) >= qty) {
if(balances[caller] >= qty) {
// Lower the token balance of the caller
wl = modifyWallet(wl, caller, -qty)
if(getBalance(target) !== undefined) {
balances[caller] -= qty
if(target in balances) {
// Wallet already exists in state, add new tokens
wl = modifyWallet(wl, target, qty)
balances[target] += qty
}
else {
// Wallet is new, set starting balance
wl.push({"addr": target, "balance": qty})
balances[target] = qty
}
state.walletList = wl
state.balances = balances
state = JSON.stringify(state)
}
else {
Expand All @@ -33,31 +33,11 @@ else if(opts.function == "balance") {
let target = opts.target
let ticker = state.ticker
let divisibility = state.divisibility
let balance = getBalance(target) / divisibility
let balance = balances[target] / divisibility
console.log(
"The balance of wallet " + target +
" is " + balance + " " + ticker + ".")
}
else {
throw "Function not recognised."
}

// Helpers
function modifyWallet(wl, addr, mod) {
for(let i = 0; i < wl.length; i++) {
if((wl[i].addr == addr)) {
wl[i].balance += mod
return wl
}
}
return false
}

function getBalance(addr) {
for(let i = 0; i < wl.length; i++) {
if((wl[i].addr == addr)) {
return wl[i].balance
}
}
return undefined
}

0 comments on commit eddfb1b

Please sign in to comment.