stylus_sdk/call/
transfer.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
// Copyright 2022-2024, Offchain Labs, Inc.
// For licensing, see https://github.com/OffchainLabs/stylus-sdk-rs/blob/main/licenses/COPYRIGHT.md

use crate::call::RawCall;
use alloc::vec::Vec;
use alloy_primitives::{Address, U256};

#[cfg(feature = "reentrant")]
use crate::storage::TopLevelStorage;

#[cfg(feature = "reentrant")]
use crate::storage::Storage;

/// Transfers an amount of ETH in wei to the given account.
/// Note that this method will call the other contract, which may in turn call others.
///
/// All gas is supplied, which the recipient may burn.
/// If this is not desired, the [`call`](super::call) function may be used directly.
///
/// [`call`]: super::call
#[cfg(feature = "reentrant")]
pub fn transfer_eth(
    _storage: &mut impl TopLevelStorage,
    to: Address,
    amount: U256,
) -> Result<(), Vec<u8>> {
    Storage::clear(); // clear the storage to persist changes, invalidating the cache
    unsafe {
        RawCall::new_with_value(amount)
            .skip_return_data()
            .call(to, &[])?;
    }
    Ok(())
}

/// Transfers an amount of ETH in wei to the given account.
/// Note that this method will call the other contract, which may in turn call others.
///
/// All gas is supplied, which the recipient may burn.
/// If this is not desired, the [`call`](super::call) function may be used directly.
///
/// ```
/// # use stylus_sdk::call::{call, Call, transfer_eth};
/// # fn wrap() -> Result<(), Vec<u8>> {
/// #   let value = alloy_primitives::U256::ZERO;
/// #   let recipient = alloy_primitives::Address::ZERO;
/// transfer_eth(recipient, value)?;                 // these two are equivalent
/// call(Call::new().value(value), recipient, &[])?; // these two are equivalent
/// #     Ok(())
/// # }
/// ```
#[cfg(not(feature = "reentrant"))]
pub fn transfer_eth(to: Address, amount: U256) -> Result<(), Vec<u8>> {
    RawCall::new_with_value(amount)
        .skip_return_data()
        .call(to, &[])?;
    Ok(())
}