-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatchSend.evm.ts
More file actions
60 lines (55 loc) · 1.76 KB
/
Copy pathbatchSend.evm.ts
File metadata and controls
60 lines (55 loc) · 1.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
import { call } from "../core/builtins";
import type { InlineFunction } from "../core/function";
import { Address, Bool, Weis } from "../core/types";
type Recipient = { address: Address; amount: bigint };
type RecipientGroup = { amount: bigint; recipients: Address[] };
const batchSendFixedAmount = (
recipients: readonly Address[],
amount: bigint,
): InlineFunction => {
if (recipients.length == 0)
throw new RangeError("batchSend requires at least one recipient");
if (recipients.length == 1) {
const recipient = recipients[0]!;
return evm (): Bool => {
return call(0, recipient, amount, 0, 0, 0, 0);
};
}
return evm (): Bool => {
const value: Weis = amount;
static for (const recipient of recipients) {
call(0, recipient, value, 0, 0, 0, 0);
}
};
}
const batchSend = (recipients: readonly Recipient[]): InlineFunction => {
const groups = groupByAmount(recipients);
if (groups.length == 0)
throw new RangeError("batchSend requires at least one recipient");
return evm (): Bool => {
static for (const group of groups) {
const value: Weis = group.amount;
static for (const recipient of group.recipients) {
call(0, recipient, value, 0, 0, 0, 0);
}
}
};
}
const groupByAmount = (recipients: readonly Recipient[]): RecipientGroup[] => {
const sorted = [...recipients].sort((a, b) =>
a.amount < b.amount ? -1 : a.amount > b.amount ? 1 : 0);
const groups: RecipientGroup[] = [];
for (const { address, amount } of sorted) {
const last = groups[groups.length - 1];
if (last && last.amount == amount)
last.recipients.push(address);
else
groups.push({ amount, recipients: [address] });
}
return groups;
}
export {
batchSend,
batchSendFixedAmount,
Recipient
};