stellar_interchain_token/
contract.rs

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
use soroban_sdk::token::{StellarAssetInterface, TokenInterface};
use soroban_sdk::{
    assert_with_error, contract, contractimpl, panic_with_error, token, Address, BytesN, Env,
    String,
};
use soroban_token_sdk::event::Events as TokenEvents;
use soroban_token_sdk::metadata::TokenMetadata;
use soroban_token_sdk::TokenUtils;
use stellar_axelar_std::events::Event;
use stellar_axelar_std::interfaces::OwnableInterface;
use stellar_axelar_std::ttl::{extend_instance_ttl, extend_persistent_ttl};
use stellar_axelar_std::{ensure, interfaces, Upgradable};

use crate::error::ContractError;
use crate::event::{MinterAddedEvent, MinterRemovedEvent};
use crate::interface::InterchainTokenInterface;
use crate::storage_types::{AllowanceDataKey, AllowanceValue, DataKey};

#[contract]
#[derive(Upgradable)]
pub struct InterchainToken;

#[contractimpl]
impl InterchainToken {
    pub fn __constructor(
        env: Env,
        owner: Address,
        minter: Option<Address>,
        token_id: BytesN<32>,
        token_metadata: TokenMetadata,
    ) {
        interfaces::set_owner(&env, &owner);

        Self::write_metadata(&env, token_metadata);

        env.storage().instance().set(&DataKey::TokenId, &token_id);

        env.storage().instance().set(&DataKey::Minter(owner), &());

        if let Some(minter) = minter {
            env.storage().instance().set(&DataKey::Minter(minter), &());
        }
    }
}

#[contractimpl]
impl StellarAssetInterface for InterchainToken {
    fn set_admin(env: Env, admin: Address) {
        Self::transfer_ownership(&env, admin);
    }

    fn admin(env: Env) -> Address {
        Self::owner(&env)
    }

    fn set_authorized(_env: Env, _id: Address, _authorize: bool) {
        todo!()
    }

    fn authorized(_env: Env, _id: Address) -> bool {
        todo!()
    }

    fn mint(env: Env, to: Address, amount: i128) {
        if let Err(err) = Self::mint_from(&env, Self::owner(&env), to, amount) {
            panic_with_error!(env, err);
        }
    }

    fn clawback(_env: Env, _from: Address, _amount: i128) {
        todo!()
    }
}

#[contractimpl]
impl InterchainTokenInterface for InterchainToken {
    fn token_id(env: &Env) -> BytesN<32> {
        env.storage()
            .instance()
            .get(&DataKey::TokenId)
            .expect("token id not found")
    }

    fn is_minter(env: &Env, minter: Address) -> bool {
        env.storage().instance().has(&DataKey::Minter(minter))
    }

    fn mint_from(
        env: &Env,
        minter: Address,
        to: Address,
        amount: i128,
    ) -> Result<(), ContractError> {
        minter.require_auth();

        ensure!(
            Self::is_minter(env, minter.clone()),
            ContractError::NotMinter
        );

        Self::validate_amount(env, amount);

        Self::receive_balance(env, to.clone(), amount);

        extend_instance_ttl(env);

        TokenUtils::new(env).events().mint(minter, to, amount);

        Ok(())
    }

    fn add_minter(env: &Env, minter: Address) {
        Self::owner(env).require_auth();

        env.storage()
            .instance()
            .set(&DataKey::Minter(minter.clone()), &());

        extend_instance_ttl(env);

        MinterAddedEvent { minter }.emit(env);
    }

    fn remove_minter(env: &Env, minter: Address) {
        Self::owner(env).require_auth();

        env.storage()
            .instance()
            .remove(&DataKey::Minter(minter.clone()));

        extend_instance_ttl(env);

        MinterRemovedEvent { minter }.emit(env);
    }
}

#[contractimpl]
impl token::Interface for InterchainToken {
    fn allowance(env: Env, from: Address, spender: Address) -> i128 {
        extend_instance_ttl(&env);
        Self::read_allowance(&env, from, spender).amount
    }

    fn approve(env: Env, from: Address, spender: Address, amount: i128, expiration_ledger: u32) {
        from.require_auth();

        Self::validate_amount(&env, amount);

        Self::write_allowance(
            &env,
            from.clone(),
            spender.clone(),
            amount,
            expiration_ledger,
        );

        extend_instance_ttl(&env);

        TokenUtils::new(&env)
            .events()
            .approve(from, spender, amount, expiration_ledger);
    }

    fn balance(env: Env, id: Address) -> i128 {
        extend_instance_ttl(&env);
        Self::read_balance(&env, id)
    }

    fn transfer(env: Env, from: Address, to: Address, amount: i128) {
        from.require_auth();

        Self::validate_amount(&env, amount);
        Self::spend_balance(&env, from.clone(), amount);
        Self::receive_balance(&env, to.clone(), amount);

        extend_instance_ttl(&env);

        TokenUtils::new(&env).events().transfer(from, to, amount);
    }

    fn transfer_from(env: Env, spender: Address, from: Address, to: Address, amount: i128) {
        spender.require_auth();

        Self::validate_amount(&env, amount);
        Self::spend_allowance(&env, from.clone(), spender, amount);
        Self::spend_balance(&env, from.clone(), amount);
        Self::receive_balance(&env, to.clone(), amount);

        extend_instance_ttl(&env);

        TokenUtils::new(&env).events().transfer(from, to, amount)
    }

    fn burn(env: Env, from: Address, amount: i128) {
        from.require_auth();

        Self::validate_amount(&env, amount);
        Self::spend_balance(&env, from.clone(), amount);

        extend_instance_ttl(&env);

        TokenUtils::new(&env).events().burn(from, amount);
    }

    fn burn_from(env: Env, spender: Address, from: Address, amount: i128) {
        spender.require_auth();

        Self::validate_amount(&env, amount);
        Self::spend_allowance(&env, from.clone(), spender, amount);
        Self::spend_balance(&env, from.clone(), amount);

        extend_instance_ttl(&env);

        TokenUtils::new(&env).events().burn(from, amount)
    }

    fn decimals(env: Env) -> u32 {
        TokenUtils::new(&env).metadata().get_metadata().decimal
    }

    fn name(env: Env) -> String {
        TokenUtils::new(&env).metadata().get_metadata().name
    }

    fn symbol(env: Env) -> String {
        TokenUtils::new(&env).metadata().get_metadata().symbol
    }
}

impl InterchainToken {
    // Modify this function to add migration logic
    const fn run_migration(_env: &Env, _migration_data: ()) {}

    fn validate_amount(env: &Env, amount: i128) {
        assert_with_error!(env, amount >= 0, ContractError::InvalidAmount);
    }

    fn read_allowance(env: &Env, from: Address, spender: Address) -> AllowanceValue {
        let key = DataKey::Allowance(AllowanceDataKey { from, spender });
        env.storage()
            .temporary()
            .get::<_, AllowanceValue>(&key)
            .map_or(
                AllowanceValue {
                    amount: 0,
                    expiration_ledger: 0,
                },
                |allowance| {
                    if allowance.expiration_ledger < env.ledger().sequence() {
                        AllowanceValue {
                            amount: 0,
                            expiration_ledger: allowance.expiration_ledger,
                        }
                    } else {
                        allowance
                    }
                },
            )
    }

    fn write_allowance(
        env: &Env,
        from: Address,
        spender: Address,
        amount: i128,
        expiration_ledger: u32,
    ) {
        let allowance = AllowanceValue {
            amount,
            expiration_ledger,
        };

        assert_with_error!(
            env,
            !(amount > 0 && expiration_ledger < env.ledger().sequence()),
            ContractError::InvalidExpirationLedger
        );

        let key = DataKey::Allowance(AllowanceDataKey { from, spender });
        env.storage().temporary().set(&key, &allowance);

        if amount > 0 {
            let live_for = expiration_ledger
                .checked_sub(env.ledger().sequence())
                .unwrap();

            env.storage()
                .temporary()
                .extend_ttl(&key, live_for, live_for)
        }
    }

    fn spend_allowance(env: &Env, from: Address, spender: Address, amount: i128) {
        let allowance = Self::read_allowance(env, from.clone(), spender.clone());

        assert_with_error!(
            env,
            allowance.amount >= amount,
            ContractError::InsufficientAllowance
        );

        if amount > 0 {
            Self::write_allowance(
                env,
                from,
                spender,
                allowance
                    .amount
                    .checked_sub(amount)
                    .expect("insufficient allowance"),
                allowance.expiration_ledger,
            );
        }
    }

    fn read_balance(env: &Env, addr: Address) -> i128 {
        let key = DataKey::Balance(addr);
        env.storage()
            .persistent()
            .get::<_, i128>(&key)
            .inspect(|_| {
                // Extend the TTL of the balance entry when the balance is successfully retrieved.
                extend_persistent_ttl(env, &key);
            })
            .unwrap_or_default()
    }

    fn receive_balance(env: &Env, addr: Address, amount: i128) {
        let key = DataKey::Balance(addr);

        env.storage()
            .persistent()
            .update(&key, |balance: Option<i128>| {
                balance.unwrap_or_default() + amount
            });
    }

    fn spend_balance(env: &Env, addr: Address, amount: i128) {
        let balance = Self::read_balance(env, addr.clone());

        assert_with_error!(env, balance >= amount, ContractError::InsufficientBalance);

        Self::write_balance(env, addr, balance - amount);
    }

    fn write_metadata(env: &Env, metadata: TokenMetadata) {
        TokenUtils::new(env).metadata().set_metadata(&metadata);
    }

    fn write_balance(env: &Env, addr: Address, amount: i128) {
        let key = DataKey::Balance(addr);

        env.storage().persistent().set(&key, &amount);

        extend_persistent_ttl(env, &key);
    }
}

#[contractimpl]
impl OwnableInterface for InterchainToken {
    fn owner(env: &Env) -> Address {
        interfaces::owner(env)
    }

    fn transfer_ownership(env: &Env, new_owner: Address) {
        interfaces::transfer_ownership::<Self>(env, new_owner.clone());
        // adhere to reference implementation for tokens and emit predefined soroban event
        TokenEvents::new(env).set_admin(Self::owner(env), new_owner);
    }
}