odra-cli 2.10.1

Odra CLI - Command Line Interface for Odra smart contracts.
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
#![allow(unused_variables)]
use odra::contract_def::HasIdent;
use odra::{
    casper_types::{
        bytesrepr::{Bytes, ToBytes},
        PublicKey, RuntimeArgs, U512
    },
    entry_point_callback::EntryPointsCaller,
    host::{HostContext, HostEnv},
    prelude::*,
    schema::{
        casper_contract_schema::{Access, Argument, Entrypoint, NamedCLType, Type},
        SchemaCustomTypes
    },
    CallDef, EventError, GasReport
};
use odra_schema::codec::CustomTypeSet;

use crate::{
    cmd::args::CommandArg,
    container::{ContractError, ContractStorage, ContractStorageSource, ContractsData},
    DeployedContractsContainer
};

pub fn mock_entry_point() -> Entrypoint {
    Entrypoint {
        name: "test".to_string(),
        description: None,
        is_mutable: false,
        is_payable: false,
        arguments: vec![
            Argument::new(
                "voucher",
                "",
                NamedCLType::Custom("PaymentVoucher".to_string())
            ),
            Argument::new(
                "signature",
                "",
                NamedCLType::List(Box::new(NamedCLType::U8))
            ),
        ],
        return_ty: Type(NamedCLType::Bool),
        is_contract_context: true,
        access: Access::Public
    }
}

pub fn mock_command_args() -> Vec<CommandArg> {
    vec![
        CommandArg::new("voucher.payment.buyer", "", NamedCLType::Key).required(),
        CommandArg::new("voucher.payment.payment_id", "", NamedCLType::String).required(),
        CommandArg::new("voucher.payment.amount", "", NamedCLType::U512).required(),
        CommandArg::new("voucher.names.label", "", NamedCLType::String)
            .required()
            .list(),
        CommandArg::new("voucher.names.owner", "", NamedCLType::Key)
            .required()
            .list(),
        CommandArg::new("voucher.names.token_expiration", "", NamedCLType::U64)
            .required()
            .list(),
        CommandArg::new("voucher.voucher_expiration", "", NamedCLType::U64).required(),
        CommandArg::new(
            "signature",
            "",
            NamedCLType::List(Box::new(NamedCLType::U8))
        )
        .required()
        .list(),
    ]
}

pub fn custom_types() -> CustomTypeSet {
    let mut types = CustomTypeSet::from_iter(PaymentVoucher::schema_types().into_iter().flatten());
    types.extend(NameTokenMetadata::schema_types().into_iter().flatten());
    types
}

#[odra::odra_type]
pub struct NameTokenMetadata {
    pub token_hash: String,
    pub expiration: u64,
    pub resolver: Option<Address>
}

#[odra::odra_type]
pub struct PaymentVoucher {
    pub payment: PaymentInfo,
    pub names: Vec<NameMintInfo>,
    pub voucher_expiration: u64
}

impl PaymentVoucher {
    pub fn new(payment: PaymentInfo, names: Vec<NameMintInfo>, voucher_expiration: u64) -> Self {
        Self {
            payment,
            names,
            voucher_expiration
        }
    }
}

#[odra::odra_type]
pub struct PaymentInfo {
    pub buyer: Address,
    pub payment_id: String,
    pub amount: U512
}

impl PaymentInfo {
    pub fn new(buyer: &str, payment_id: &str, amount: &str) -> Self {
        Self {
            buyer: buyer.parse().unwrap(),
            payment_id: payment_id.to_string(),
            amount: U512::from_dec_str(amount).unwrap()
        }
    }
}

#[odra::odra_type]
pub struct NameMintInfo {
    pub label: String,
    pub owner: Address,
    pub token_expiration: u64
}

impl NameMintInfo {
    pub fn new(label: &str, owner: &str, token_expiration: u64) -> Self {
        Self {
            label: label.to_string(),
            owner: owner.parse().unwrap(),
            token_expiration
        }
    }
}

#[odra::odra_type]
pub enum Status {
    Active,
    Paused,
    Terminated
}

#[odra::module]
pub struct TestContract;

#[odra::module]
impl TestContract {
    pub fn add(&self, x: u64, y: u64) -> u64 {
        x + y
    }

    pub fn echo(&self, message: String) -> String {
        message
    }

    pub fn mutable(&mut self) {}

    pub fn upgrade(&mut self, version: u32) {}

    pub fn set_status(&mut self, status: Status) {}

    #[allow(clippy::too_many_arguments)]
    pub fn various_args(
        &self,
        a: Address,
        b: Option<Address>,
        c: Vec<String>,
        d: Result<u64, String>,
        e: Result<u64, String>,
        f: (String,),
        g: (String, String),
        h: (String, String, String),
        i: BTreeMap<String, u64>,
        j: Bytes
    ) -> Vec<u8> {
        (a, b, c, d, e).to_bytes().unwrap_or_revert(self)
    }

    #[odra(payable)]
    pub fn deposit(&mut self) {}

    #[odra(offchain)]
    pub fn sum_of(&self, values: Vec<u64>) -> u64 {
        values.iter().sum()
    }
}

#[odra::module(factory = on)]
pub struct TestCounter {
    value: Var<u32>
}

#[odra::module(factory = on)]
impl TestCounter {
    pub fn init(&mut self, value: u32) {
        self.value.set(value);
    }

    pub fn upgrade(&mut self, new_value: u32) {
        self.value.set(new_value);
    }
}

struct DummyHostCtx;

impl HostContext for DummyHostCtx {
    #[doc = " Sets the caller address for the current contract execution."]
    fn set_caller(&self, caller: Address) {
        todo!()
    }

    #[doc = " Sets the gas limit for the current contract execution."]
    fn set_gas(&self, gas: u64) {}

    #[doc = " Returns the caller address for the current contract execution."]
    fn caller(&self) -> Address {
        todo!()
    }

    #[doc = " Returns the account address at the specified index."]
    fn get_account(&self, index: usize) -> Address {
        todo!()
    }

    #[doc = " Returns the validator public key."]
    fn get_validator(&self, index: usize) -> PublicKey {
        todo!()
    }

    #[doc = " The validator at the given index will withdraw all funds and be removed from the validator set."]
    fn remove_validator(&self, index: usize) {
        todo!()
    }

    #[doc = " Returns the CSPR balance of the specified address."]
    fn get_storage_value(&self, address: &Address, key: &[u8]) -> Option<Bytes> {
        None
    }

    fn get_named_value(&self, address: &Address, name: &str) -> Option<Bytes> {
        None
    }

    fn get_dictionary_value(
        &self,
        address: &Address,
        dictionary_name: &str,
        key: &[u8]
    ) -> Option<Bytes> {
        None
    }

    fn balance_of(&self, address: &Address) -> U512 {
        todo!()
    }

    #[doc = " Advances the block time by the specified time difference."]
    fn advance_block_time(&self, time_diff: u64) {
        todo!()
    }

    #[doc = " Advances the block time by the specified time difference and processes auctions."]
    fn advance_with_auctions(&self, time_diff: u64) {
        todo!()
    }

    #[doc = " Time between auctions in milliseconds."]
    fn auction_delay(&self) -> u64 {
        todo!()
    }

    #[doc = " Time for the funds to be transferred back to the delegator after undelegation in milliseconds."]
    fn unbonding_delay(&self) -> u64 {
        todo!()
    }

    #[doc = " Returns the delegated amount for the specified delegator and validator."]
    fn delegated_amount(&self, delegator: Address, validator: PublicKey) -> U512 {
        todo!()
    }

    #[doc = " Returns the current block time."]
    fn block_time(&self) -> u64 {
        todo!()
    }

    fn take_snapshot(&self) {
        todo!()
    }

    fn restore_snapshot(&self) {
        todo!()
    }

    #[doc = " Returns the event bytes for the specified contract address and index."]
    fn get_event(&self, contract_address: &Address, index: u32) -> Result<Bytes, EventError> {
        todo!()
    }

    #[doc = " Returns the native event bytes for the specified contract address and index."]
    fn get_native_event(
        &self,
        contract_address: &Address,
        index: u32
    ) -> Result<Bytes, EventError> {
        todo!()
    }

    #[doc = " Returns the number of emitted events for the specified contract address."]
    fn get_events_count(&self, contract_address: &Address) -> Result<u32, EventError> {
        todo!()
    }

    #[doc = " Returns the number of emitted native events for the specified contract address."]
    fn get_native_events_count(&self, contract_address: &Address) -> Result<u32, EventError> {
        todo!()
    }

    #[doc = " Calls a contract at the specified address with the given call definition."]
    fn call_contract(
        &self,
        address: &Address,
        call_def: CallDef,
        use_proxy: bool
    ) -> OdraResult<Bytes> {
        todo!()
    }

    #[doc = " Creates a new contract with the specified name, initialization arguments, and entry points caller."]
    fn new_contract(
        &self,
        name: &str,
        init_args: RuntimeArgs,
        entry_points_caller: EntryPointsCaller
    ) -> OdraResult<Address> {
        todo!()
    }

    fn upgrade_contract(
        &self,
        name: &str,
        contract_to_upgrade: Address,
        upgrade_args: RuntimeArgs,
        entry_points_caller: EntryPointsCaller
    ) -> OdraResult<Address> {
        todo!()
    }

    #[doc = " Registers an existing contract with the specified address, name, and entry points caller."]
    fn register_contract(
        &self,
        address: Address,
        contract_name: String,
        entry_points_caller: EntryPointsCaller
    ) {
        todo!()
    }

    #[doc = " Returns the contract environment."]
    fn contract_env(&self) -> ContractEnv {
        todo!()
    }

    #[doc = " Returns the gas report for the current contract execution."]
    fn gas_report(&self) -> GasReport {
        todo!()
    }

    #[doc = " Returns the gas cost of the last contract call."]
    fn last_call_gas_cost(&self) -> u64 {
        todo!()
    }

    #[doc = " Signs the specified message with the given address and returns the signature."]
    fn sign_message(&self, message: &Bytes, address: &Address) -> Bytes {
        todo!()
    }

    #[doc = " Returns the public key associated with the specified address."]
    fn public_key(&self, address: &Address) -> PublicKey {
        todo!()
    }

    #[doc = " Transfers the specified amount of CSPR from the current caller to the specified address."]
    fn transfer(&self, to: Address, amount: U512) -> OdraResult<()> {
        todo!()
    }
}

pub fn mock_host_env() -> HostEnv {
    HostEnv::new(Rc::new(DummyHostCtx))
}

struct MockContractStorage;

impl ContractStorage for MockContractStorage {
    fn read(&self) -> Result<ContractsData, ContractError> {
        Ok(ContractsData::default())
    }

    fn write(&mut self, data: &ContractsData) -> Result<(), ContractError> {
        Ok(())
    }

    fn backup(&self) -> Result<(), ContractError> {
        Ok(())
    }

    fn source(&self) -> ContractStorageSource {
        ContractStorageSource::Memory
    }
}

pub fn mock_contracts_container() -> DeployedContractsContainer {
    DeployedContractsContainer::instance(MockContractStorage)
}

/// A memory-backed container with the contract `T` deployed at `address`, under `package_name`
/// or its ident.
pub fn contracts_container_with<T: HasIdent>(
    address: Address,
    package_name: Option<String>
) -> DeployedContractsContainer {
    let mut data = ContractsData::default();
    data.add_contract::<T>(address, package_name).unwrap();
    DeployedContractsContainer::with_data(data, MockContractStorage)
}