radix-engine 1.3.1

Reference implementation of Radix Engine, from the Radix DLT project.
Documentation
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
use crate::blueprints::pool::v1::constants::*;
use crate::blueprints::pool::v1::errors::one_resource_pool::*;
use crate::blueprints::pool::v1::events::one_resource_pool::*;
use crate::blueprints::pool::v1::substates::one_resource_pool::*;
use crate::internal_prelude::*;
use radix_engine_interface::blueprints::component::*;
use radix_engine_interface::blueprints::pool::*;
use radix_engine_interface::prelude::*;
use radix_engine_interface::*;
use radix_native_sdk::modules::metadata::*;
use radix_native_sdk::modules::role_assignment::*;
use radix_native_sdk::modules::royalty::*;
use radix_native_sdk::resource::*;
use radix_native_sdk::runtime::*;

pub struct OneResourcePoolBlueprint;
impl OneResourcePoolBlueprint {
    pub fn instantiate<Y: SystemApi<RuntimeError>>(
        resource_address: ResourceAddress,
        owner_role: OwnerRole,
        pool_manager_rule: AccessRule,
        address_reservation: Option<GlobalAddressReservation>,
        api: &mut Y,
    ) -> Result<OneResourcePoolInstantiateOutput, RuntimeError> {
        // Validate that the resource is a fungible resource - a pool can't be created with non
        // fungible resources.
        let resource_manager = ResourceManager(resource_address);
        if let ResourceType::NonFungible { .. } = resource_manager.resource_type(api)? {
            Err(Error::NonFungibleResourcesAreNotAccepted { resource_address })?
        }

        // Allocating the component address of the pool - this will be used later for the component
        // caller badge.
        let (address_reservation, address) = {
            if let Some(address_reservation) = address_reservation {
                let address = api.get_reservation_address(address_reservation.0.as_node_id())?;
                (address_reservation, address)
            } else {
                api.allocate_global_address(BlueprintId {
                    package_address: POOL_PACKAGE,
                    blueprint_name: ONE_RESOURCE_POOL_BLUEPRINT_IDENT.to_string(),
                })?
            }
        };

        let pool_unit_resource_manager = {
            let component_caller_badge = NonFungibleGlobalId::global_caller_badge(address);

            ResourceManager::new_fungible(
                owner_role.clone(),
                true,
                18,
                FungibleResourceRoles {
                    mint_roles: mint_roles! {
                        minter => rule!(require(component_caller_badge.clone()));
                        minter_updater => rule!(deny_all);
                    },
                    burn_roles: burn_roles! {
                        burner => rule!(require(component_caller_badge.clone()));
                        burner_updater => rule!(deny_all);
                    },
                    ..Default::default()
                },
                metadata_init! {
                    "pool" => address, locked;
                },
                None,
                api,
            )?
        };

        let role_assignment = RoleAssignment::create(
            owner_role,
            indexmap! {
                ModuleId::Main => roles_init! {
                    RoleKey { key: POOL_MANAGER_ROLE.to_owned() } => pool_manager_rule;
                }
            },
            api,
        )?
        .0;
        let metadata = Metadata::create_with_data(
            metadata_init! {
                "pool_vault_number" => 1u8, locked;
                "pool_resources" => vec![GlobalAddress::from(resource_address)], locked;
                "pool_unit" => GlobalAddress::from(pool_unit_resource_manager.0), locked;
            },
            api,
        )?;
        let royalty = ComponentRoyalty::create(ComponentRoyaltyConfig::default(), api)?;
        let object_id = {
            let vault = Vault::create(resource_address, api)?;
            let substate = Substate {
                vault,
                pool_unit_resource_manager,
            };
            api.new_simple_object(
                ONE_RESOURCE_POOL_BLUEPRINT_IDENT,
                indexmap! {
                    OneResourcePoolField::State.field_index() => FieldValue::immutable(OneResourcePoolStateFieldPayload::from_content_source(substate)),
                },
            )?
        };

        api.globalize(
            object_id,
            indexmap!(
                AttachedModuleId::RoleAssignment => role_assignment.0,
                AttachedModuleId::Metadata => metadata.0,
                AttachedModuleId::Royalty => royalty.0,
            ),
            Some(address_reservation),
        )?;

        Ok(Global::new(ComponentAddress::new_or_panic(
            address.as_node_id().0,
        )))
    }

    pub fn contribute<Y: SystemApi<RuntimeError>>(
        bucket: Bucket,
        api: &mut Y,
    ) -> Result<OneResourcePoolContributeOutput, RuntimeError> {
        if bucket.is_empty(api)? {
            return Err(Error::ContributionOfEmptyBucketError.into());
        }

        Self::with_state(api, |mut substate, api| {
            // Check if the provided resource belongs to the pool or not. If not, then error out.
            {
                let input_resource_address = bucket.resource_address(api)?;
                let pool_reserves_resource_address = substate.vault.resource_address(api)?;

                if input_resource_address != pool_reserves_resource_address {
                    return Err(Error::ResourceDoesNotBelongToPool {
                        resource_address: input_resource_address,
                    }
                    .into());
                }
            }

            /*
            There are four states that the pool could be in at this point of time depending on the
            total supply of the pool units and the the total amount of reserves that the pool has.
            We can examine each of those states.

            Let PU denote the total supply of pool units where 0 means that none exists and 1 means
            that some amount exists. Let R denote the total amount of reserves that the pool has
            where 0 here means that no reserves exist in the pool and 1 means that some reserves
            exist in the pool.

            PU  R
            0   0 => This is a new pool - no pool units and no pool reserves.
            0   1 => This is a pool which has been used but has dried out and all of the pool units
                     have been burned. The first contribution to this pool gets whatever dust is
                     left behind.
            1   0 => This is an illegal state! Some amount of people own some % of zero which is
                     invalid. There is pretty much nothing we can do in this case because we can't
                     determine how much pool units to mint for this contribution. To signify that
                     the user has 100% ownership of the pool we must mint the maximum mint amount
                     which will dilute the worth of the pool units.
            1   1 => The pool is in normal operations.

            Thus depending on the supply of these resources the pool behaves differently and the
            amount of pool units to mint changes as well.
             */

            let initial_reserves_decimal = substate.vault.amount(api)?;
            let initial_pool_unit_total_supply_decimal = substate
                .pool_unit_resource_manager
                .total_supply(api)?
                .expect("Total supply is always enabled for pool unit resource.");
            let amount_of_contributed_resources_decimal = bucket.amount(api)?;

            let initial_reserves = PreciseDecimal::from(initial_reserves_decimal);
            let initial_pool_unit_total_supply =
                PreciseDecimal::from(initial_pool_unit_total_supply_decimal);
            let amount_of_contributed_resources =
                PreciseDecimal::from(amount_of_contributed_resources_decimal);

            let pool_units_to_mint = match (
                initial_pool_unit_total_supply > PreciseDecimal::ZERO,
                initial_reserves > PreciseDecimal::ZERO,
            ) {
                (false, false) => Ok(amount_of_contributed_resources),
                (false, true) => amount_of_contributed_resources
                    .checked_add(initial_reserves)
                    .ok_or(Error::DecimalOverflowError),
                (true, false) => Err(Error::NonZeroPoolUnitSupplyButZeroReserves),
                // Note: we do the division first to make it harder for the calculation to overflow.
                (true, true) => amount_of_contributed_resources
                    .checked_div(initial_reserves)
                    .and_then(|d| d.checked_mul(initial_pool_unit_total_supply))
                    .ok_or(Error::DecimalOverflowError),
            }?;
            let pool_units_to_mint =
                Decimal::try_from(pool_units_to_mint).map_err(|_| Error::DecimalOverflowError)?;
            if pool_units_to_mint == Decimal::ZERO {
                return Err(Error::ZeroPoolUnitsMinted.into());
            }
            Runtime::emit_event(
                api,
                ContributionEvent {
                    amount_of_resources_contributed: amount_of_contributed_resources_decimal,
                    pool_units_minted: pool_units_to_mint,
                },
            )?;
            substate.vault.put(bucket, api)?;

            let pool_units = substate
                .pool_unit_resource_manager
                .mint_fungible(pool_units_to_mint, api)?;

            Ok(pool_units.into())
        })
    }

    pub fn redeem<Y: SystemApi<RuntimeError>>(
        bucket: Bucket,
        api: &mut Y,
    ) -> Result<OneResourcePoolRedeemOutput, RuntimeError> {
        Self::with_state(api, |mut substate, api| {
            // Ensure that the passed pool resources are indeed pool resources
            let bucket_resource_address = bucket.resource_address(api)?;
            if bucket_resource_address != substate.pool_unit_resource_manager.0 {
                return Err(Error::InvalidPoolUnitResource {
                    expected: substate.pool_unit_resource_manager.0,
                    actual: bucket_resource_address,
                }
                .into());
            }

            // Calculating the amount owed based on the passed pool units.
            let pool_units_to_redeem = bucket.amount(api)?;
            let initial_pool_units_total_supply = substate
                .pool_unit_resource_manager
                .total_supply(api)?
                .expect("Total supply is always enabled for pool unit resource.");
            let initial_pool_resource_reserves = substate.vault.amount(api)?;
            let reserves_divisibility = substate.vault
            .resource_address(api)
            .and_then(|resource_address| ResourceManager(resource_address).resource_type(api))
            .map(|resource_type| {
                if let ResourceType::Fungible { divisibility } = resource_type {
                    divisibility
                } else {
                    panic!("Impossible case, we check for this in the constructor and have a test for this.")
                }
            })?;

            let amount_owed = Self::calculate_amount_owed(
                pool_units_to_redeem,
                initial_pool_units_total_supply,
                initial_pool_resource_reserves,
                reserves_divisibility,
            )?;

            // Return an error if the amount owed to them is zero. This is to guard from cases where
            // the amount owed is zero due to the divisibility. As an example. Imagine a pool with
            // reserves of 100.00 of a resource that has two divisibility and a pool unit total
            // supply of 100 pool units. Redeeming 10^-18 pool units from this pool would mean
            // redeeming 10^-18 tokens which is invalid for this resource's divisibility. Thus, this
            // calculation would round to 0.
            if amount_owed == Decimal::ZERO {
                return Err(Error::RedeemedZeroTokens.into());
            }

            Runtime::emit_event(
                api,
                RedemptionEvent {
                    pool_unit_tokens_redeemed: pool_units_to_redeem,
                    redeemed_amount: amount_owed,
                },
            )?;

            // Burn the pool units and take the owed resources from the bucket.
            bucket.burn(api)?;
            substate.vault.take(amount_owed, api)
        })
    }

    pub fn protected_deposit<Y: SystemApi<RuntimeError>>(
        bucket: Bucket,
        api: &mut Y,
    ) -> Result<OneResourcePoolProtectedDepositOutput, RuntimeError> {
        let bucket_amount = bucket.amount(api)?;

        Self::with_state(api, |mut substate, api| substate.vault.put(bucket, api))?;

        Runtime::emit_event(
            api,
            DepositEvent {
                amount: bucket_amount,
            },
        )?;

        Ok(())
    }

    pub fn protected_withdraw<Y: SystemApi<RuntimeError>>(
        amount: Decimal,
        withdraw_strategy: WithdrawStrategy,
        api: &mut Y,
    ) -> Result<OneResourcePoolProtectedWithdrawOutput, RuntimeError> {
        let bucket = Self::with_state(api, |mut substate, api| {
            substate.vault.take_advanced(amount, withdraw_strategy, api)
        })?;

        let withdrawn_amount = bucket.amount(api)?;
        Runtime::emit_event(
            api,
            WithdrawEvent {
                amount: withdrawn_amount,
            },
        )?;

        Ok(bucket)
    }

    pub fn get_redemption_value<Y: SystemApi<RuntimeError>>(
        amount_of_pool_units: Decimal,
        api: &mut Y,
    ) -> Result<OneResourcePoolGetRedemptionValueOutput, RuntimeError> {
        Self::with_state(api, |substate, api| {
            let pool_units_to_redeem = amount_of_pool_units;
            let pool_units_total_supply = substate
                .pool_unit_resource_manager
                .total_supply(api)?
                .expect("Total supply is always enabled for pool unit resource.");

            if amount_of_pool_units.is_negative()
                || amount_of_pool_units.is_zero()
                || amount_of_pool_units > pool_units_total_supply
            {
                return Err(Error::InvalidGetRedemptionAmount.into());
            }

            let pool_resource_reserves = substate.vault.amount(api)?;
            let pool_resource_divisibility = substate.vault
            .resource_address(api)
            .and_then(|resource_address| ResourceManager(resource_address).resource_type(api))
            .map(|resource_type| {
                if let ResourceType::Fungible { divisibility } = resource_type {
                    divisibility
                } else {
                    panic!("Impossible case, we check for this in the constructor and have a test for this.")
                }
            })?;

            Self::calculate_amount_owed(
                pool_units_to_redeem,
                pool_units_total_supply,
                pool_resource_reserves,
                pool_resource_divisibility,
            )
        })
    }

    pub fn get_vault_amount<Y: SystemApi<RuntimeError>>(
        api: &mut Y,
    ) -> Result<OneResourcePoolGetVaultAmountOutput, RuntimeError> {
        Self::with_state(api, |substate, api| substate.vault.amount(api))
    }

    //===================
    // Utility Functions
    //===================

    fn calculate_amount_owed(
        pool_units_to_redeem: Decimal,
        pool_units_total_supply: Decimal,
        reserves_amount: Decimal,
        reserves_divisibility: u8,
    ) -> Result<Decimal, RuntimeError> {
        let pool_units_to_redeem = PreciseDecimal::from(pool_units_to_redeem);
        let pool_units_total_supply = PreciseDecimal::from(pool_units_total_supply);
        let reserves_amount = PreciseDecimal::from(reserves_amount);

        let amount_owed = pool_units_to_redeem
            .checked_div(pool_units_total_supply)
            .and_then(|d| d.checked_mul(reserves_amount))
            .ok_or(Error::DecimalOverflowError)?;

        Decimal::try_from(amount_owed)
            .ok()
            .and_then(|value| {
                value.checked_round(reserves_divisibility, RoundingMode::ToNegativeInfinity)
            })
            .ok_or(Error::DecimalOverflowError.into())
    }

    /// Opens the substate, executes the callback, and closes the substate.
    fn with_state<Y: SystemApi<RuntimeError>, O>(
        api: &mut Y,
        callback: impl FnOnce(Substate, &mut Y) -> Result<O, RuntimeError>,
    ) -> Result<O, RuntimeError> {
        // Open
        let substate_key = OneResourcePoolField::State.into();
        let handle =
            api.actor_open_field(ACTOR_STATE_SELF, substate_key, LockFlags::read_only())?;
        let substate = api
            .field_read_typed::<VersionedOneResourcePoolState>(handle)?
            .fully_update_and_into_latest_version();

        // Op
        let rtn = callback(substate, api);

        // Close
        if rtn.is_ok() {
            api.field_close(handle)?;
        }
        rtn
    }
}