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
use std::{future::IntoFuture, marker::PhantomData};

use alloy_dyn_abi::{DynSolValue, FunctionExt};
use alloy_json_abi::Function;
use alloy_network::Network;
use alloy_primitives::Bytes;
use alloy_rpc_types_eth::{state::StateOverride, BlockId};
use alloy_sol_types::SolCall;
use alloy_transport::Transport;

use crate::{Error, Result};

/// Raw coder.
const RAW_CODER: () = ();

#[allow(unnameable_types)]
mod private {
    pub trait Sealed {}
    impl Sealed for super::Function {}
    impl<C: super::SolCall> Sealed for super::PhantomData<C> {}
    impl Sealed for () {}
}

/// An [`alloy_provider::EthCall`] with an abi decoder.
#[must_use = "EthCall must be awaited to execute the call"]
#[derive(Clone, Debug)]
pub struct EthCall<'req, 'coder, D, T, N>
where
    T: Transport + Clone,
    N: Network,
    D: CallDecoder,
{
    inner: alloy_provider::EthCall<'req, T, N, Bytes>,

    decoder: &'coder D,
}

impl<'req, 'coder, D, T, N> EthCall<'req, 'coder, D, T, N>
where
    T: Transport + Clone,
    N: Network,
    D: CallDecoder,
{
    /// Create a new [`EthCall`].
    pub const fn new(
        inner: alloy_provider::EthCall<'req, T, N, Bytes>,
        decoder: &'coder D,
    ) -> Self {
        Self { inner, decoder }
    }
}

impl<'req, T, N> EthCall<'req, 'static, (), T, N>
where
    T: Transport + Clone,
    N: Network,
{
    /// Create a new [`EthCall`].
    pub const fn new_raw(inner: alloy_provider::EthCall<'req, T, N, Bytes>) -> Self {
        Self::new(inner, &RAW_CODER)
    }
}

impl<'req, D, T, N> EthCall<'req, '_, D, T, N>
where
    T: Transport + Clone,
    N: Network,
    D: CallDecoder,
{
    /// Swap the decoder for this call.
    pub fn with_decoder<'new_coder, E>(
        self,
        decoder: &'new_coder E,
    ) -> EthCall<'req, 'new_coder, E, T, N>
    where
        E: CallDecoder,
    {
        EthCall { inner: self.inner, decoder }
    }

    /// Set the state overrides for this call.
    pub fn overrides(mut self, overrides: &'req StateOverride) -> Self {
        self.inner = self.inner.overrides(overrides);
        self
    }

    /// Set the block to use for this call.
    pub fn block(mut self, block: BlockId) -> Self {
        self.inner = self.inner.block(block);
        self
    }
}

impl<'req, T, N> From<alloy_provider::EthCall<'req, T, N, Bytes>>
    for EthCall<'req, 'static, (), T, N>
where
    T: Transport + Clone,
    N: Network,
{
    fn from(inner: alloy_provider::EthCall<'req, T, N, Bytes>) -> Self {
        Self { inner, decoder: &RAW_CODER }
    }
}

impl<'req, 'coder, D, T, N> std::future::IntoFuture for EthCall<'req, 'coder, D, T, N>
where
    D: CallDecoder + Unpin,
    T: Transport + Clone,
    N: Network,
{
    type Output = Result<D::CallOutput>;

    type IntoFuture = EthCallFut<'req, 'coder, D, T, N>;

    fn into_future(self) -> Self::IntoFuture {
        EthCallFut { inner: self.inner.into_future(), decoder: self.decoder }
    }
}

/// Future for the [`EthCall`] type. This future wraps an RPC call with an abi
/// decoder.
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
#[allow(unnameable_types)]
pub struct EthCallFut<'req, 'coder, D, T, N>
where
    T: Transport + Clone,
    N: Network,
    D: CallDecoder,
{
    inner: <alloy_provider::EthCall<'req, T, N, Bytes> as IntoFuture>::IntoFuture,
    decoder: &'coder D,
}

impl<D, T, N> std::future::Future for EthCallFut<'_, '_, D, T, N>
where
    D: CallDecoder + Unpin,
    T: Transport + Clone,
    N: Network,
{
    type Output = Result<D::CallOutput>;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let this = self.get_mut();
        let pin = std::pin::pin!(&mut this.inner);
        match pin.poll(cx) {
            std::task::Poll::Ready(Ok(data)) => {
                std::task::Poll::Ready(this.decoder.abi_decode_output(data, true))
            }
            std::task::Poll::Ready(Err(e)) => std::task::Poll::Ready(Err(e.into())),
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}

/// A trait for decoding the output of a contract function.
///
/// This trait is sealed and cannot be implemented manually.
/// It is an implementation detail of [`CallBuilder`].
///
/// [`CallBuilder`]: crate::CallBuilder
pub trait CallDecoder: private::Sealed {
    // Not public API.

    /// The output type of the contract function.
    #[doc(hidden)]
    type CallOutput;

    /// Decodes the output of a contract function.
    #[doc(hidden)]
    fn abi_decode_output(&self, data: Bytes, validate: bool) -> Result<Self::CallOutput>;

    #[doc(hidden)]
    fn as_debug_field(&self) -> impl std::fmt::Debug;
}

impl CallDecoder for Function {
    type CallOutput = Vec<DynSolValue>;

    #[inline]
    fn abi_decode_output(&self, data: Bytes, validate: bool) -> Result<Self::CallOutput> {
        FunctionExt::abi_decode_output(self, &data, validate).map_err(Error::AbiError)
    }

    #[inline]
    fn as_debug_field(&self) -> impl std::fmt::Debug {
        self
    }
}

impl<C: SolCall> CallDecoder for PhantomData<C> {
    type CallOutput = C::Return;

    #[inline]
    fn abi_decode_output(&self, data: Bytes, validate: bool) -> Result<Self::CallOutput> {
        C::abi_decode_returns(&data, validate).map_err(|e| Error::AbiError(e.into()))
    }

    #[inline]
    fn as_debug_field(&self) -> impl std::fmt::Debug {
        std::any::type_name::<C>()
    }
}

impl CallDecoder for () {
    type CallOutput = Bytes;

    #[inline]
    fn abi_decode_output(&self, data: Bytes, _validate: bool) -> Result<Self::CallOutput> {
        Ok(data)
    }

    #[inline]
    fn as_debug_field(&self) -> impl std::fmt::Debug {
        format_args!("()")
    }
}