-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
205 lines (179 loc) · 5.76 KB
/
main.ts
File metadata and controls
205 lines (179 loc) · 5.76 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import * as T from "@minswap/translucent";
import { Client } from "pg";
import logger from "./logger";
import { checkSkipGenReward, getEnv } from "./utils";
import { runRecurringJob } from "./job";
import { Duration } from "./duration";
import { newRedisReadonly, type RedisReadOnly } from "./redis";
import JSONBig from "json-bigint";
const BATCH_SIZE = 30;
type RunBatcherOptions = {
t: T.Translucent;
redis: RedisReadOnly;
dbClient: Client;
rewardUnit: T.Unit;
fundAddress: T.Address;
};
function parseStakeAddress(utxo: T.UTxO): string | undefined {
const C = T.CModuleLoader.get;
try {
// parse Inline Datum Hex => C PlutusData
const plutusData = C.PlutusData.from_bytes(T.fromHex(utxo.datum!));
// convert it => utf8 string
return Buffer.from(plutusData.as_bytes()!).toString("utf-8");
} catch {
return undefined;
}
}
async function runBatcher(options: RunBatcherOptions): Promise<void> {
const { t, redis, dbClient, rewardUnit, fundAddress } = options;
// Check Skip
let finalRewardData = await redis.get("final_reward");
if (!finalRewardData) {
logger.warn("SKIP | Not Final Reward");
return;
}
// Check all seeds have been seeded or not?
const skipGenReward = await checkSkipGenReward(redis);
if (!skipGenReward) {
// should wait until seeding finish!
logger.warn("SKIP | Seeding not finished yet!");
return;
}
// Get Batcher UTxOs
const batcherUtxos = await t.wallet.getUtxos();
// We only handle BATCH_SIZE Order per batch
let userUtxos = batcherUtxos
.filter((u) => u.assets["lovelace"] === 2_000_000n)
.slice(0, BATCH_SIZE);
if (!userUtxos.length) {
logger.warn("SKIP | No Order");
return;
}
// mapping between stake-address -> Reward UTxO
const mapRewardUtxo: Record<string, T.UTxO> = {};
for (const u of batcherUtxos) {
// Seed UTxO contains reward Tokens
if (u.assets[rewardUnit] && u.assets[rewardUnit] > 0n) {
const sa = parseStakeAddress(u);
if (sa) {
mapRewardUtxo[sa] = u;
}
}
}
// Init TxBuilder
const txBuilder = t.newTx();
// init Input To Chosoe
const inputsToChoose: T.UTxO[] = [];
// loop userUTxOs to build Tx
for (const userUtxo of userUtxos) {
// Should try-catch to prevent crash batching
try {
// This Query aims to get User Stake Address, Address from Order's UTxO
const rawQuery = `
select stake_address.view, tx_out.address
from
tx inner join tx_in on tx.id = tx_in.tx_in_id
inner join tx_out on tx_in.tx_out_id = tx_out.tx_id and tx_in.tx_out_index = tx_out.index
inner join stake_address on stake_address.id = tx_out.stake_address_id
where
tx.hash='\\x${userUtxo.txHash}';
`;
const data = await dbClient.query(rawQuery);
const stakeAddress = data.rows[0].view;
const userAddress = data.rows[0].address;
// get reward UTxO, skip if not found
const rewardUtxo = mapRewardUtxo[stakeAddress];
if (!rewardUtxo) {
logger.warn(
`SKIP|already_redeem OR no_reward|stake_address=${stakeAddress}`,
);
continue;
}
// prepare user values
const userRewardAssets = {
...rewardUtxo.assets,
lovelace: 1_500_000n,
};
logger.info(
`redeem to user|${JSONBig.stringify(
{
rewardInput: {
txHash: rewardUtxo.txHash,
index: rewardUtxo.outputIndex,
},
userInput: { txHash: userUtxo.txHash, index: userUtxo.outputIndex },
userAddress,
userRewardAssets,
},
null,
2,
)}`,
);
// collect Order, Reward UTxO -> pays to User
txBuilder
.collectFrom([rewardUtxo, userUtxo])
.payToAddress(userAddress, userRewardAssets);
// only choose inputs that required
inputsToChoose.push(rewardUtxo, userUtxo);
} catch (err) {
logger.error("handle order failed");
logger.error(err);
}
}
// Check we redeem any
if (inputsToChoose.length > 0) {
// Build -> Sign -> Finalize
// Should return Change Fund to Fund Address
const completeTx = await txBuilder.complete({
inputsToChoose,
change: { address: fundAddress },
});
const signedTx = await completeTx.sign().complete();
// submit tx
const txHash = await signedTx.submit();
logger.info(`Batch Success|txHash=${txHash}`);
// wait Tx tobe confirmed! before run next batch
await t.awaitTx(txHash, 5000);
} else {
logger.info("SKIP | no redeem");
}
}
const main = async () => {
logger.info("Start | Batcher redeem rewards");
// load modules
await T.loadModule();
await T.CModuleLoader.load();
// Get needed things
const network: T.MaestroSupportedNetworks = getEnv(
"NETWORK",
) as T.MaestroSupportedNetworks;
const maestroApiKey = getEnv("MAESTRO_API_KEY");
const batcherSeedPhase = getEnv("BATCHER_SEED_PHASE");
const redisUrl = getEnv("REDIS_URL");
const dbConfig = {
user: getEnv("DB_USER"),
host: getEnv("DB_HOST"),
database: getEnv("DB_NAME"),
password: getEnv("DB_PASSWORD"),
port: Number(getEnv("DB_PORT")),
};
const rewardUnit = getEnv("REWARD_UNIT");
const fundAddress = getEnv("FUND_ADDRESS");
// Init connections
const redis = newRedisReadonly(redisUrl, "batcher");
const dbClient = new Client(dbConfig);
const maestro = new T.Maestro({ network, apiKey: maestroApiKey });
const t = await T.Translucent.new(maestro, network);
t.selectWalletFromSeed(batcherSeedPhase);
await dbClient.connect();
// run rucurring as Cronjob
await runRecurringJob({
name: "fiso-batcher",
interval: Duration.newSeconds(30),
job: async () => {
await runBatcher({ t, redis, dbClient, rewardUnit, fundAddress });
},
});
};
main();