Skip to main content

stylus_sdk/call/
transfer.rs

1// Copyright 2022-2024, Offchain Labs, Inc.
2// For licensing, see https://github.com/OffchainLabs/stylus-sdk-rs/blob/main/licenses/COPYRIGHT.md
3
4use alloc::vec::Vec;
5use alloy_primitives::{Address, U256};
6use stylus_core::Host;
7
8use super::RawCall;
9
10/// Transfers an amount of ETH in wei to the given account.
11/// Note that this method will call the other contract, which may in turn call others.
12///
13/// All gas is supplied, which the recipient may burn.
14/// If this is not desired, the [`call`](super::call) function may be used directly.
15///
16/// ```
17/// # use stylus_sdk::prelude::*;
18/// # use stylus_sdk::stylus_core::host::Host;
19/// # use stylus_sdk::call::transfer::transfer_eth;
20/// # fn wrap(host: &impl Host) -> Result<(), Vec<u8>> {
21/// #   let value = alloy_primitives::U256::ZERO;
22/// #   let recipient = alloy_primitives::Address::ZERO;
23/// transfer_eth(host, recipient, value)?;                 // these two are equivalent
24/// call(host, Call::new().value(value), recipient, &[])?; // these two are equivalent
25/// #     Ok(())
26/// # }
27/// ```
28pub fn transfer_eth(host: &impl Host, to: Address, amount: U256) -> Result<(), Vec<u8>> {
29    host.flush_cache(true); // clear the storage to persist changes, invalidating the cache
30    unsafe {
31        RawCall::new_with_value(host, amount)
32            .skip_return_data()
33            .call(to, &[])?;
34    }
35    Ok(())
36}