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
use crate::errors::ExecutionError;
use crate::future::CompatCallFuture;
use crate::transaction::build::BuildFuture;
use crate::transaction::confirm::ConfirmFuture;
use crate::transaction::{ResolveCondition, Transaction, TransactionBuilder, TransactionResult};
use futures::compat::Future01CompatExt;
use futures::ready;
use pin_project::{pin_project, project};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use web3::api::Web3;
use web3::types::{H256, U64};
use web3::Transport;
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[pin_project]
pub struct SendFuture<T: Transport> {
web3: Web3<T>,
resolve: Option<ResolveCondition>,
#[pin]
state: SendState<T>,
}
#[pin_project]
enum SendState<T: Transport> {
Building(#[pin] BuildFuture<T>),
Sending(#[pin] CompatCallFuture<T, H256>),
Confirming(#[pin] ConfirmFuture<T>),
}
impl<T: Transport> SendFuture<T> {
pub fn from_builder(mut builder: TransactionBuilder<T>) -> Self {
let web3 = builder.web3.clone();
let resolve = Some(builder.resolve.take().unwrap_or_default());
let state = SendState::Building(BuildFuture::from_builder(builder));
SendFuture {
web3,
resolve,
state,
}
}
}
impl<T: Transport> Future for SendFuture<T> {
type Output = Result<TransactionResult, ExecutionError>;
#[project]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
loop {
#[project]
let SendFuture {
web3,
resolve,
state,
} = self.as_mut().project();
#[project]
let next_state = match state.project() {
SendState::Building(build) => {
let tx = match ready!(build.poll(cx)) {
Ok(tx) => tx,
Err(err) => return Poll::Ready(Err(err)),
};
let eth = web3.eth();
let send = match tx {
Transaction::Request(tx) => eth.send_transaction(tx).compat(),
Transaction::Raw(tx) => eth.send_raw_transaction(tx).compat(),
};
SendState::Sending(send)
}
SendState::Sending(send) => {
let tx_hash = match ready!(send.poll(cx)) {
Ok(tx_hash) => tx_hash,
Err(err) => return Poll::Ready(Err(err.into())),
};
let confirm = match resolve.take().expect("confirmation called more than once")
{
ResolveCondition::Pending => {
return Poll::Ready(Ok(TransactionResult::Hash(tx_hash)))
}
ResolveCondition::Confirmed(params) => {
ConfirmFuture::new(&web3, tx_hash, params)
}
};
SendState::Confirming(confirm)
}
SendState::Confirming(confirm) => {
return confirm.poll(cx).map(|result| {
let tx = result?;
match tx.status {
Some(U64([1])) => Ok(TransactionResult::Receipt(tx)),
_ => Err(ExecutionError::Failure(Box::new(tx))),
}
})
}
};
self.state = next_state;
}
}
}