-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathserver.js
167 lines (143 loc) · 4.41 KB
/
server.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true });
const fastifyEnv = require('fastify-env');
const chainLibs = require('./js-chain-libs/js_chain_libs');
const jormungandrApi = require('./jormungandr_api');
// Get config from .env file
const schema = {
type: 'object',
required: ['JORMUNGANDR_API', 'SECRET_KEY', 'LOVELACES_TO_GIVE'],
properties: {
// The node address
JORMUNGANDR_API: {
type: 'string',
default: 'http://localhost:8443/api'
},
// The faucet secret key in bech32 format
SECRET_KEY: {
type: 'string'
},
// The port to listen to
PORT: {
type: 'string',
default: 3000
},
// Fixed amount of lovelaces to give on each request
LOVELACES_TO_GIVE: {
type: 'number',
default: 3000
}
}
};
const options = {
schema,
dotenv: true
};
fastify.post('/send-money/:destinationAddress', async (request, reply) => {
try {
const {
OutputPolicy,
TransactionBuilder,
Address,
Input,
Value,
Fee,
Fragment,
PrivateKey,
Witness,
SpendingCounter,
Hash,
Account,
InputOutputBuilder,
PayloadAuthData,
Payload,
Witnesses,
// eslint-disable-next-line camelcase
uint8array_to_hex
} = await chainLibs;
// From the settings we can get:
// the block0hash used for signing
// the transaction fees
const nodeSettings = await jormungandrApi.getNodeSettings(
fastify.config.JORMUNGANDR_API
);
const iobuilder = InputOutputBuilder.empty();
const secretKey = PrivateKey.from_bech32(fastify.config.SECRET_KEY);
const faucetAccount = Account.single_from_public_key(secretKey.to_public());
// Fee (#inputs + #outputs) * coefficient + constant + #certificates*certificate
// #inputs = 1; #outputs = 2; #certificates = 0
const computedFee =
(1 + 1) * nodeSettings.fees.coefficient + nodeSettings.fees.constant;
const inputAmount = fastify.config.LOVELACES_TO_GIVE + computedFee;
// To get the account spending counter used for signing and the account available funds
const accountStatus = await jormungandrApi.getAccountStatus(
fastify.config.JORMUNGANDR_API,
uint8array_to_hex(secretKey.to_public().as_bytes())
);
const available_funds = accountStatus.value;
if (inputAmount > available_funds) {
reply
.code(503)
.send('No funds available in faucet account');
return;
}
const input = Input.from_account(
faucetAccount,
Value.from_str(inputAmount.toString())
);
iobuilder.add_input(input);
iobuilder.add_output(
Address.from_string(request.params.destinationAddress),
Value.from_str(fastify.config.LOVELACES_TO_GIVE.toString())
);
const feeAlgorithm = Fee.linear_fee(
Value.from_str(nodeSettings.fees.constant.toString()),
Value.from_str(nodeSettings.fees.coefficient.toString()),
Value.from_str(nodeSettings.fees.certificate.toString())
);
// The amount is exact, that's why we use `forget()`
const IOs = iobuilder.seal_with_output_policy(
Payload.no_payload(),
feeAlgorithm,
OutputPolicy.forget()
);
const builderSetWitness = new TransactionBuilder()
.no_payload()
.set_ios(IOs.inputs(), IOs.outputs());
const witness = Witness.for_account(
Hash.from_hex(nodeSettings.block0Hash),
builderSetWitness.get_auth_data_for_witness(),
secretKey,
SpendingCounter.from_u32(accountStatus.counter)
);
const witnesses = Witnesses.new();
witnesses.add(witness);
const signedTx = builderSetWitness
.set_witnesses(witnesses)
.set_payload_auth(PayloadAuthData.for_no_payload());
const message = Fragment.from_transaction(signedTx);
// Send the transaction
await jormungandrApi.postMsg(
fastify.config.JORMUNGANDR_API,
message.as_bytes()
);
reply
.code(200)
.send(`transaction id: ${uint8array_to_hex(message.id().as_bytes())}`);
} catch (err) {
fastify.log.error(err.message);
}
});
fastify.register(fastifyEnv, options).ready(err => {
if (err) fastify.log.error(err);
start();
});
const start = async () => {
try {
await fastify.listen(fastify.config.PORT);
fastify.log.info(`server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};