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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// This file is part of Gear.

// Copyright (C) 2022-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Costs module.

use crate::pages::WasmPagesAmount;
use core::{fmt::Debug, marker::PhantomData};
use paste::paste;

/// Gas cost per some type of action or data size.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct CostOf<T> {
    cost: u64,
    _phantom: PhantomData<T>,
}

impl<T> CostOf<T> {
    /// Const constructor
    pub const fn new(cost: u64) -> Self {
        Self {
            cost,
            _phantom: PhantomData,
        }
    }

    /// Cost for one.
    pub const fn cost_for_one(&self) -> u64 {
        self.cost
    }
}

impl<T: Into<u32>> CostOf<T> {
    /// Calculate (saturating mult) cost for `num` amount of `T`.
    pub fn cost_for(&self, num: T) -> u64 {
        self.cost.saturating_mul(Into::<u32>::into(num).into())
    }
}

impl<T> Debug for CostOf<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{}", &self.cost))
    }
}

impl<T> From<u64> for CostOf<T> {
    fn from(cost: u64) -> Self {
        CostOf::new(cost)
    }
}

impl<T> From<CostOf<T>> for u64 {
    fn from(value: CostOf<T>) -> Self {
        value.cost
    }
}

impl<T> Default for CostOf<T> {
    fn default() -> Self {
        CostOf::new(0)
    }
}

/// Some actions or calls amount.
#[derive(Debug, Default, Clone, Copy, derive_more::From, derive_more::Into)]
pub struct CallsAmount(u32);

/// Bytes amount.
#[derive(Debug, Default, Clone, Copy, derive_more::From, derive_more::Into)]
pub struct BytesAmount(u32);

/// Chain blocks amount.
#[derive(Debug, Default, Clone, Copy, derive_more::From, derive_more::Into)]
pub struct BlocksAmount(u32);

/// Program imported function call (syscall) costs.
#[derive(Debug, Clone, Default)]
pub struct SyscallCosts {
    /// Cost of calling `alloc`.
    pub alloc: CostOf<CallsAmount>,

    /// Cost per allocated page for `alloc`.
    pub alloc_per_page: CostOf<WasmPagesAmount>,

    /// Cost of calling `free`.
    pub free: CostOf<CallsAmount>,

    /// Cost of calling `free_range`
    pub free_range: CostOf<CallsAmount>,

    /// Cost of calling `free_range` per page
    pub free_range_per_page: CostOf<WasmPagesAmount>,

    /// Cost of calling `gr_reserve_gas`.
    pub gr_reserve_gas: CostOf<CallsAmount>,

    /// Cost of calling `gr_unreserve_gas`
    pub gr_unreserve_gas: CostOf<CallsAmount>,

    /// Cost of calling `gr_system_reserve_gas`
    pub gr_system_reserve_gas: CostOf<CallsAmount>,

    /// Cost of calling `gr_gas_available`.
    pub gr_gas_available: CostOf<CallsAmount>,

    /// Cost of calling `gr_message_id`.
    pub gr_message_id: CostOf<CallsAmount>,

    /// Cost of calling `gr_program_id`.
    pub gr_program_id: CostOf<CallsAmount>,

    /// Cost of calling `gr_source`.
    pub gr_source: CostOf<CallsAmount>,

    /// Cost of calling `gr_value`.
    pub gr_value: CostOf<CallsAmount>,

    /// Cost of calling `gr_value_available`.
    pub gr_value_available: CostOf<CallsAmount>,

    /// Cost of calling `gr_size`.
    pub gr_size: CostOf<CallsAmount>,

    /// Cost of calling `gr_read`.
    pub gr_read: CostOf<CallsAmount>,

    /// Cost per payload byte for `gr_read`.
    pub gr_read_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_env_vars`.
    pub gr_env_vars: CostOf<CallsAmount>,

    /// Cost of calling `gr_block_height`.
    pub gr_block_height: CostOf<CallsAmount>,

    /// Cost of calling `gr_block_timestamp`.
    pub gr_block_timestamp: CostOf<CallsAmount>,

    /// Cost of calling `gr_random`.
    pub gr_random: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply_deposit`.
    pub gr_reply_deposit: CostOf<CallsAmount>,

    /// Cost of calling `gr_send`
    pub gr_send: CostOf<CallsAmount>,

    /// Cost per bytes for `gr_send`.
    pub gr_send_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_send_wgas`.
    pub gr_send_wgas: CostOf<CallsAmount>,

    /// Cost of calling `gr_send_wgas` per one payload byte.
    pub gr_send_wgas_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_send_init`.
    pub gr_send_init: CostOf<CallsAmount>,

    /// Cost of calling `gr_send_push`.
    pub gr_send_push: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_send_push`.
    pub gr_send_push_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_send_commit`.
    pub gr_send_commit: CostOf<CallsAmount>,

    /// Cost of calling `gr_send_commit_wgas`.
    pub gr_send_commit_wgas: CostOf<CallsAmount>,

    /// Cost of calling `gr_reservation_send`.
    pub gr_reservation_send: CostOf<CallsAmount>,

    /// Cost of calling `gr_reservation_send` per one payload byte.
    pub gr_reservation_send_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reservation_send_commit`.
    pub gr_reservation_send_commit: CostOf<CallsAmount>,

    /// Cost of calling `gr_send_init`.
    pub gr_send_input: CostOf<CallsAmount>,

    /// Cost of calling `gr_send_init_wgas`.
    pub gr_send_input_wgas: CostOf<CallsAmount>,

    /// Cost of calling `gr_send_push_input`.
    pub gr_send_push_input: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_send_push_input`.
    pub gr_send_push_input_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reply`.
    pub gr_reply: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply` per one payload byte.
    pub gr_reply_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reply_wgas`.
    pub gr_reply_wgas: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply_wgas` per one payload byte.
    pub gr_reply_wgas_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reply_commit`.
    pub gr_reply_commit: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply_commit_wgas`.
    pub gr_reply_commit_wgas: CostOf<CallsAmount>,

    /// Cost of calling `gr_reservation_reply`.
    pub gr_reservation_reply: CostOf<CallsAmount>,

    /// Cost of calling `gr_reservation_reply` per one payload byte.
    pub gr_reservation_reply_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reservation_reply_commit`.
    pub gr_reservation_reply_commit: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply_push`.
    pub gr_reply_push: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_reply_push`.
    pub gr_reply_push_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reply_input`.
    pub gr_reply_input: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply_input_wgas`.
    pub gr_reply_input_wgas: CostOf<CallsAmount>,

    /// Cost of calling `gr_reply_push_input`.
    pub gr_reply_push_input: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_reply_push_input`.
    pub gr_reply_push_input_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reply_to`.
    pub gr_reply_to: CostOf<CallsAmount>,

    /// Cost of calling `gr_signal_code`.
    pub gr_signal_code: CostOf<CallsAmount>,

    /// Cost of calling `gr_signal_from`.
    pub gr_signal_from: CostOf<CallsAmount>,

    /// Cost of calling `gr_debug`.
    pub gr_debug: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_debug`.
    pub gr_debug_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_reply_code`.
    pub gr_reply_code: CostOf<CallsAmount>,

    /// Cost of calling `gr_exit`.
    pub gr_exit: CostOf<CallsAmount>,

    /// Cost of calling `gr_leave`.
    pub gr_leave: CostOf<CallsAmount>,

    /// Cost of calling `gr_wait`.
    pub gr_wait: CostOf<CallsAmount>,

    /// Cost of calling `gr_wait_for`.
    pub gr_wait_for: CostOf<CallsAmount>,

    /// Cost of calling `gr_wait_up_to`.
    pub gr_wait_up_to: CostOf<CallsAmount>,

    /// Cost of calling `gr_wake`.
    pub gr_wake: CostOf<CallsAmount>,

    /// Cost of calling `gr_create_program_wgas`.
    pub gr_create_program: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_create_program_wgas`.
    pub gr_create_program_payload_per_byte: CostOf<BytesAmount>,

    /// Cost per salt byte by `gr_create_program_wgas`.
    pub gr_create_program_salt_per_byte: CostOf<BytesAmount>,

    /// Cost of calling `gr_create_program_wgas`.
    pub gr_create_program_wgas: CostOf<CallsAmount>,

    /// Cost per payload byte by `gr_create_program_wgas`.
    pub gr_create_program_wgas_payload_per_byte: CostOf<BytesAmount>,

    /// Cost per salt byte by `gr_create_program_wgas`.
    pub gr_create_program_wgas_salt_per_byte: CostOf<BytesAmount>,
}

/// Enumerates syscalls that can be charged by gas meter.
#[derive(Debug, Copy, Clone)]
pub enum CostToken {
    /// Zero cost.
    Null,
    /// Cost of calling `alloc`.
    Alloc,
    /// Cost of calling `free`.
    Free,
    /// Cost of calling `free_range`
    FreeRange,
    /// Cost of calling `gr_reserve_gas`.
    ReserveGas,
    /// Cost of calling `gr_unreserve_gas`.
    UnreserveGas,
    /// Cost of calling `gr_system_reserve_gas`.
    SystemReserveGas,
    /// Cost of calling `gr_gas_available`.
    GasAvailable,
    /// Cost of calling `gr_message_id`.
    MsgId,
    /// Cost of calling `gr_program_id`.
    ProgramId,
    /// Cost of calling `gr_source`.
    Source,
    /// Cost of calling `gr_value`.
    Value,
    /// Cost of calling `gr_value_available`.
    ValueAvailable,
    /// Cost of calling `gr_size`.
    Size,
    /// Cost of calling `gr_read`.
    Read,
    /// Cost of calling `gr_env_vars`.
    EnvVars,
    /// Cost of calling `gr_block_height`.
    BlockHeight,
    /// Cost of calling `gr_block_timestamp`.
    BlockTimestamp,
    /// Cost of calling `gr_random`.
    Random,
    /// Cost of calling `gr_reply_deposit`.
    ReplyDeposit,
    /// Cost of calling `gr_send`, taking in account payload size.
    Send(BytesAmount),
    /// Cost of calling `gr_send_wgas`, taking in account payload size.
    SendWGas(BytesAmount),
    /// Cost of calling `gr_send_init`.
    SendInit,
    /// Cost of calling `gr_send_push`, taking in account payload size.
    SendPush(BytesAmount),
    /// Cost of calling `gr_send_commit`.
    SendCommit,
    /// Cost of calling `gr_send_commit_wgas`.
    SendCommitWGas,
    /// Cost of calling `gr_reservation_send`, taking in account payload size.
    ReservationSend(BytesAmount),
    /// Cost of calling `gr_reservation_send_commit`.
    ReservationSendCommit,
    /// Cost of calling `gr_send_input`.
    SendInput,
    /// Cost of calling `gr_send_input_wgas`.
    SendInputWGas,
    /// Cost of calling `gr_send_push_input`.
    SendPushInput,
    /// Cost of calling `gr_reply`, taking in account payload size.
    Reply(BytesAmount),
    /// Cost of calling `gr_reply_wgas`, taking in account payload size.
    ReplyWGas(BytesAmount),
    /// Cost of calling `gr_reply_push`, taking in account payload size.
    ReplyPush(BytesAmount),
    /// Cost of calling `gr_reply_commit`.
    ReplyCommit,
    /// Cost of calling `gr_reply_commit_wgas`.
    ReplyCommitWGas,
    /// Cost of calling `gr_reservation_reply`, taking in account payload size.
    ReservationReply(BytesAmount),
    /// Cost of calling `gr_reservation_reply_commit`.
    ReservationReplyCommit,
    /// Cost of calling `gr_reply_input`.
    ReplyInput,
    /// Cost of calling `gr_reply_input_wgas`.
    ReplyInputWGas,
    /// Cost of calling `gr_reply_push_input`.
    ReplyPushInput,
    /// Cost of calling `gr_reply_to`.
    ReplyTo,
    /// Cost of calling `gr_signal_code`.
    SignalCode,
    /// Cost of calling `gr_signal_from`.
    SignalFrom,
    /// Cost of calling `gr_debug`, taking in account payload size.
    Debug(BytesAmount),
    /// Cost of calling `gr_reply_code`.
    ReplyCode,
    /// Cost of calling `gr_exit`.
    Exit,
    /// Cost of calling `gr_leave`.
    Leave,
    /// Cost of calling `gr_wait`.
    Wait,
    /// Cost of calling `gr_wait_for`.
    WaitFor,
    /// Cost of calling `gr_wait_up_to`.
    WaitUpTo,
    /// Cost of calling `gr_wake`.
    Wake,
    /// Cost of calling `gr_create_program`, taking in account payload and salt size.
    CreateProgram(BytesAmount, BytesAmount),
    /// Cost of calling `gr_create_program_wgas`, taking in account payload and salt size.
    CreateProgramWGas(BytesAmount, BytesAmount),
}

impl SyscallCosts {
    /// Get cost for a token.
    pub fn cost_for_token(&self, token: CostToken) -> u64 {
        use CostToken::*;

        macro_rules! cost_with_per_byte {
            ($name:ident, $len:expr) => {
                paste! {
                    self.$name.cost_for_one().saturating_add(self.[< $name _per_byte >].cost_for($len))
                }
            };
        }

        match token {
            Null => 0,
            Alloc => self.alloc.cost_for_one(),
            Free => self.free.cost_for_one(),
            FreeRange => self.free_range.cost_for_one(),
            ReserveGas => self.gr_reserve_gas.cost_for_one(),
            UnreserveGas => self.gr_unreserve_gas.cost_for_one(),
            SystemReserveGas => self.gr_system_reserve_gas.cost_for_one(),
            GasAvailable => self.gr_gas_available.cost_for_one(),
            MsgId => self.gr_message_id.cost_for_one(),
            ProgramId => self.gr_program_id.cost_for_one(),
            Source => self.gr_source.cost_for_one(),
            Value => self.gr_value.cost_for_one(),
            ValueAvailable => self.gr_value_available.cost_for_one(),
            Size => self.gr_size.cost_for_one(),
            Read => self.gr_read.cost_for_one(),
            EnvVars => self.gr_env_vars.cost_for_one(),
            BlockHeight => self.gr_block_height.cost_for_one(),
            BlockTimestamp => self.gr_block_timestamp.cost_for_one(),
            Random => self.gr_random.cost_for_one(),
            ReplyDeposit => self.gr_reply_deposit.cost_for_one(),
            Send(len) => cost_with_per_byte!(gr_send, len),
            SendWGas(len) => cost_with_per_byte!(gr_send_wgas, len),
            SendInit => self.gr_send_init.cost_for_one(),
            SendPush(len) => cost_with_per_byte!(gr_send_push, len),
            SendCommit => self.gr_send_commit.cost_for_one(),
            SendCommitWGas => self.gr_send_commit_wgas.cost_for_one(),
            ReservationSend(len) => cost_with_per_byte!(gr_reservation_send, len),
            ReservationSendCommit => self.gr_reservation_send_commit.cost_for_one(),
            SendInput => self.gr_send_input.cost_for_one(),
            SendInputWGas => self.gr_send_input_wgas.cost_for_one(),
            SendPushInput => self.gr_send_push_input.cost_for_one(),
            Reply(len) => cost_with_per_byte!(gr_reply, len),
            ReplyWGas(len) => cost_with_per_byte!(gr_reply_wgas, len),
            ReplyPush(len) => cost_with_per_byte!(gr_reply_push, len),
            ReplyCommit => self.gr_reply_commit.cost_for_one(),
            ReplyCommitWGas => self.gr_reply_commit_wgas.cost_for_one(),
            ReservationReply(len) => cost_with_per_byte!(gr_reservation_reply, len),
            ReservationReplyCommit => self.gr_reservation_reply_commit.cost_for_one(),
            ReplyInput => self.gr_reply_input.cost_for_one(),
            ReplyInputWGas => self.gr_reply_input_wgas.cost_for_one(),
            ReplyPushInput => self.gr_reply_push_input.cost_for_one(),
            ReplyTo => self.gr_reply_to.cost_for_one(),
            SignalCode => self.gr_signal_code.cost_for_one(),
            SignalFrom => self.gr_signal_from.cost_for_one(),
            Debug(len) => cost_with_per_byte!(gr_debug, len),
            ReplyCode => self.gr_reply_code.cost_for_one(),
            Exit => self.gr_exit.cost_for_one(),
            Leave => self.gr_leave.cost_for_one(),
            Wait => self.gr_wait.cost_for_one(),
            WaitFor => self.gr_wait_for.cost_for_one(),
            WaitUpTo => self.gr_wait_up_to.cost_for_one(),
            Wake => self.gr_wake.cost_for_one(),
            CreateProgram(payload, salt) => self
                .gr_create_program
                .cost_for_one()
                .saturating_add(self.gr_create_program_payload_per_byte.cost_for(payload))
                .saturating_add(self.gr_create_program_salt_per_byte.cost_for(salt)),
            CreateProgramWGas(payload, salt) => self
                .gr_create_program_wgas
                .cost_for_one()
                .saturating_add(
                    self.gr_create_program_wgas_payload_per_byte
                        .cost_for(payload),
                )
                .saturating_add(self.gr_create_program_wgas_salt_per_byte.cost_for(salt)),
        }
    }
}