-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (92 loc) · 2.68 KB
/
index.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
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
const WebMonetization = require('koa-web-monetization')
const plugin = require('ilp-plugin')()
const SPSP = require('ilp-protocol-spsp')
class WebMonetizationDM extends WebMonetization {
constructor () {
super()
this.pointers = new Map()
}
addPointer () {
return async (ctx, next) => {
console.log('adding spsp pointer')
console.log('id=', ctx.params.id, ' pointer=', ctx.params.pointer)
try {
await SPSP.pay(plugin, {
receiver: `${ctx.params.pointer}`,
sourceAmount: '0'
})
console.log('paid!')
this.pointers.set(ctx.params.id, ctx.params.pointer)
} catch (e) {
console.log(e.message)
return ctx.throw(400, e.message)
}
return next()
}
}
spawnPlayer ({price}) {
return async (ctx, next) => {
console.log('spawnplayer called')
const id = ctx.params.id
console.log('id: ', id)
if (!id) {
return ctx.throw(400, 'ctx.params.id must be defined')
}
const _price = (typeof price === 'function')
? Number(price(ctx))
: Number(price)
const hasBucket = this.buckets.get(id) || -1
if (hasBucket === -1) {
console.log('Player is not on server')
ctx.throw(400, 'Player is not on server')
}
const hasPointer = this.pointers.get(id) || -1
if (hasPointer === -1) {
console.log('Player does not have pointer')
ctx.throw(400, 'Player does not have pointer')
}
try {
this.spend(id, _price)
} catch (e) {
console.log('spawnPlayer ERROR: ', e.message)
return ctx.throw(402, e.message)
}
return next()
}
}
payPlayer (price) {
return async (ctx, next) => {
const id = ctx.params.id
const balance = this.buckets.get(id) || -1
if (balance === -1) {
console.log('Player is not on server')
ctx.throw(400, 'Player is not on server')
}
const pointer = this.pointers.get(id) || -1
if (pointer === -1) {
console.log('Player has no pointer')
ctx.throw(400, 'Player has no pointer')
}
console.log(`${pointer}`)
try {
await SPSP.pay(plugin, {
receiver: `${pointer}`,
sourceAmount: price
})
console.log('paid ', id, ' ', price, ' drops at ', pointer)
} catch (e) {
console.log('payPlayer ERROR: ', e.message)
return ctx.throw(402, e.message)
}
return next()
}
}
disconnectPlayer () {
return async (ctx, next) => {
console.log('disconnecting player')
const id = ctx.params.id
this.buckets.set(id, 0)
}
}
}
module.exports = WebMonetizationDM