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
// 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/>.

use super::{GearApi, Result};
use crate::Error;
use gear_core::ids::ProgramId;
use gsdk::{
    ext::sp_core::H256,
    metadata::{
        runtime_types::pallet_gear_voucher::{internal::VoucherId, pallet::Event as VoucherEvent},
        Event,
    },
};

impl GearApi {
    /// Issue a new voucher.
    ///
    /// Returns issued `voucher_id` at specified `at_block_hash`.
    ///
    /// Arguments:
    /// * spender:  user id that is eligible to use the voucher;
    /// * balance:  voucher balance could be used for transactions fees and gas;
    /// * programs: pool of programs spender can interact with, if None - means
    ///   any program, limited by Config param;
    /// * code_uploading: allow voucher to be used as payer for `upload_code`
    ///   transactions fee;
    /// * duration: amount of blocks voucher could be used by spender and
    ///   couldn't be revoked by owner. Must be out in [MinDuration;
    ///   MaxDuration] constants. Expiration block of the voucher calculates as:
    ///   current bn (extrinsic exec bn) + duration + 1.
    pub async fn issue_voucher(
        &self,
        spender: ProgramId,
        balance: u128,
        programs: Option<Vec<ProgramId>>,
        code_uploading: bool,
        duration: u32,
    ) -> Result<(VoucherId, H256)> {
        let spender: [u8; 32] = spender.into();

        let tx = self
            .0
            .calls
            .issue_voucher(spender, balance, programs, code_uploading, duration)
            .await?;

        for event in tx.wait_for_success().await?.iter() {
            if let Event::GearVoucher(VoucherEvent::VoucherIssued { voucher_id, .. }) =
                event?.as_root_event::<Event>()?
            {
                return Ok((voucher_id, tx.block_hash()));
            }
        }

        Err(Error::EventNotFound)
    }

    /// Update existing voucher.
    ///
    /// This extrinsic updates existing voucher: it can only extend vouchers
    /// rights in terms of balance, validity or programs to interact pool.
    ///
    /// Can only be called by the voucher owner.
    ///
    /// Arguments:
    /// * spender:          account id of the voucher spender;
    /// * voucher_id:       voucher id to be updated;
    /// * move_ownership:   optionally moves ownership to another account;
    /// * balance_top_up:   optionally top ups balance of the voucher from
    ///   origins balance;
    /// * append_programs:  optionally extends pool of programs by
    ///   `Some(programs_set)` passed or allows it to interact with any program
    ///   by `None` passed;
    /// * code_uploading:   optionally allows voucher to be used to pay fees for
    ///   `upload_code` extrinsics;
    /// * prolong_duration: optionally increases expiry block number. If voucher
    ///   is expired, prolongs since current bn. Validity prolongation (since
    ///   current block number for expired or since storage written expiry)
    ///   should be in [MinDuration; MaxDuration], in other words voucher
    ///   couldn't have expiry greater than current block number + MaxDuration.
    #[allow(clippy::too_many_arguments)]
    pub async fn update_voucher(
        &self,
        spender: ProgramId,
        voucher_id: VoucherId,
        move_ownership: Option<ProgramId>,
        balance_top_up: Option<u128>,
        append_programs: Option<Option<Vec<ProgramId>>>,
        code_uploading: Option<bool>,
        prolong_duration: u32,
    ) -> Result<(VoucherId, H256)> {
        let spender: [u8; 32] = spender.into();
        let move_ownership: Option<[u8; 32]> = move_ownership.map(|v| v.into());

        let tx = self
            .0
            .calls
            .update_voucher(
                spender,
                voucher_id,
                move_ownership,
                balance_top_up,
                append_programs,
                code_uploading,
                prolong_duration,
            )
            .await?;

        for event in tx.wait_for_success().await?.iter() {
            if let Event::GearVoucher(VoucherEvent::VoucherUpdated { voucher_id, .. }) =
                event?.as_root_event::<Event>()?
            {
                return Ok((voucher_id, tx.block_hash()));
            }
        }

        Err(Error::EventNotFound)
    }

    /// Revoke existing voucher.
    ///
    /// This extrinsic revokes existing voucher, if current block is greater
    /// than expiration block of the voucher (it is no longer valid).
    ///
    /// Currently it means sending of all balance from voucher account to
    /// voucher owner without voucher removal from storage map, but this
    /// behavior may change in future, as well as the origin validation:
    /// only owner is able to revoke voucher now.
    ///
    /// Arguments:
    /// * spender:    account id of the voucher spender;
    /// * voucher_id: voucher id to be revoked.
    pub async fn revoke_voucher(
        &self,
        spender: ProgramId,
        voucher_id: VoucherId,
    ) -> Result<(VoucherId, H256)> {
        let spender: [u8; 32] = spender.into();

        let tx = self.0.calls.revoke_voucher(spender, voucher_id).await?;

        for event in tx.wait_for_success().await?.iter() {
            if let Event::GearVoucher(VoucherEvent::VoucherRevoked { voucher_id, .. }) =
                event?.as_root_event::<Event>()?
            {
                return Ok((voucher_id, tx.block_hash()));
            }
        }

        Err(Error::EventNotFound)
    }

    /// Decline existing and not expired voucher.
    ///
    /// This extrinsic expires voucher of the caller, if it's still active,
    /// allowing it to be revoked.
    ///
    /// Arguments:
    /// * voucher_id:   voucher id to be declined.
    pub async fn decline_voucher(&self, voucher_id: VoucherId) -> Result<(VoucherId, H256)> {
        let tx = self.0.calls.decline_voucher(voucher_id).await?;

        for event in tx.wait_for_success().await?.iter() {
            if let Event::GearVoucher(VoucherEvent::VoucherDeclined { voucher_id, .. }) =
                event?.as_root_event::<Event>()?
            {
                return Ok((voucher_id, tx.block_hash()));
            }
        }

        Err(Error::EventNotFound)
    }

    /// Decline existing and not expired voucher with voucher.
    pub async fn decline_voucher_with_voucher(
        &self,
        voucher_id: VoucherId,
    ) -> Result<(VoucherId, H256)> {
        let tx = self
            .0
            .calls
            .decline_voucher_with_voucher(voucher_id)
            .await?;

        for event in tx.wait_for_success().await?.iter() {
            if let Event::GearVoucher(VoucherEvent::VoucherDeclined { voucher_id, .. }) =
                event?.as_root_event::<Event>()?
            {
                return Ok((voucher_id, tx.block_hash()));
            }
        }

        Err(Error::EventNotFound)
    }
}