substrate_api_client/api/rpc_api/
author.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
/*
   Copyright 2019 Supercomputing Systems AG
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
	   http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

//! Interface to common author rpc functions and helpers thereof.

use crate::{
	api::{rpc_api::events::FetchEvents, Error, Result},
	rpc::{HandleSubscription, Request, Subscribe},
	Api, ExtrinsicReport, TransactionStatus, XtStatus,
};
use ac_compose_macros::rpc_params;
use ac_primitives::{config::Config, UncheckedExtrinsicV4};
#[cfg(not(feature = "sync-api"))]
use alloc::boxed::Box;
use codec::{Decode, Encode};
use log::*;
use serde::de::DeserializeOwned;
use sp_core::Bytes;
use sp_runtime::traits::Hash as HashTrait;

pub type TransactionSubscriptionFor<Client, Hash> =
	<Client as Subscribe>::Subscription<TransactionStatus<Hash, Hash>>;

/// Simple extrinsic submission without any subscription.
#[maybe_async::maybe_async(?Send)]
pub trait SubmitExtrinsic {
	type Hash;

	/// Submit an encodable extrinsic to the substrate node.
	/// Returns the extrinsic hash.
	async fn submit_extrinsic<Address, Call, Signature, SignedExtra>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
	) -> Result<Self::Hash>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode;

	/// Submit an encoded, opaque extrinsic to the substrate node.
	/// Returns the extrinsic hash.
	async fn submit_opaque_extrinsic(&self, encoded_extrinsic: &Bytes) -> Result<Self::Hash>;
}

#[maybe_async::maybe_async(?Send)]
impl<T, Client> SubmitExtrinsic for Api<T, Client>
where
	T: Config,
	Client: Request,
{
	type Hash = T::Hash;

	async fn submit_extrinsic<Address, Call, Signature, SignedExtra>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
	) -> Result<Self::Hash>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode,
	{
		self.submit_opaque_extrinsic(&extrinsic.encode().into()).await
	}

	async fn submit_opaque_extrinsic(&self, encoded_extrinsic: &Bytes) -> Result<Self::Hash> {
		let hex_encoded_xt = rpc_params![encoded_extrinsic];
		debug!("sending extrinsic: {:?}", hex_encoded_xt);
		let xt_hash = self.client().request("author_submitExtrinsic", hex_encoded_xt).await?;
		Ok(xt_hash)
	}
}

#[maybe_async::maybe_async(?Send)]
pub trait SubmitAndWatch {
	type Client: Subscribe;
	type Hash: DeserializeOwned + Decode + Encode;

	/// Submit an extrinsic an return a Subscription
	/// to watch the extrinsic progress.
	///
	/// This method is blocking if the sync-api feature is activated
	async fn submit_and_watch_extrinsic<Address, Call, Signature, SignedExtra>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
	) -> Result<TransactionSubscriptionFor<Self::Client, Self::Hash>>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode;

	/// Submit an encoded, opaque extrinsic an return a Subscription to
	/// watch the extrinsic progress.
	///
	/// This method is blocking if the sync-api feature is activated
	async fn submit_and_watch_opaque_extrinsic(
		&self,
		encoded_extrinsic: &Bytes,
	) -> Result<TransactionSubscriptionFor<Self::Client, Self::Hash>>;

	/// Submit an extrinsic and watch it until the desired status
	/// is reached, if no error is encountered previously.
	///
	/// If watched until `InBlock` or `Finalized`, this function will
	/// return an error if the extrinsic was not successfully executed.
	/// If it was successful, a report containing the following is returned:
	/// - extrinsic hash
	/// - hash of the block the extrinsic was included in
	/// - last known extrinsic (transaction) status
	/// - associated events of the extrinsic
	///
	/// If not watched until at least `InBlock`, this function will not know if the extrinsic
	/// has been executed on chain or not and will therefore not return an error if execution fails.
	/// An error will be returned if the extrinsic has failed to be sent or if it has not been
	/// included into the transaction pool of the node.
	/// If no error occurs, a report containing the following is returned:
	/// - extrinsic hash
	/// - last known extrinsic (transaction) status
	///
	/// This method is blocking if the sync-api feature is activated
	async fn submit_and_watch_extrinsic_until<Address, Call, Signature, SignedExtra>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode;

	/// Submit an encoded, opaque extrinsic until the desired status
	/// is reached, if no error is encountered previously.
	///
	/// If watched until `InBlock` or `Finalized`, this function will
	/// return an error if the extrinsic was not successfully executed.
	/// If it was successful, a report containing the following is returned:
	/// - extrinsic hash
	/// - hash of the block the extrinsic was included in
	/// - last known extrinsic (transaction) status
	/// - associated events of the extrinsic (only for InBlock or Finalized)
	///
	/// If not watched until at least `InBlock`, this function will not know if the extrinsic
	/// has been executed on chain or not and will therefore not return an error if execution fails..
	/// An error will be returned, if the extrinsic has failed to be sent or if it has not been
	/// included into the transaction pool of the node.
	/// If no error occurs, a report containing the following is returned:
	/// - extrinsic hash
	/// - last known extrinsic (transaction) status
	///
	/// This method is blocking if the sync-api feature is activated
	async fn submit_and_watch_opaque_extrinsic_until(
		&self,
		encoded_extrinsic: &Bytes,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>>;

	/// Submit an extrinsic and watch it until the desired status
	/// is reached, if no error is encountered previously.
	/// The events are not fetched. So no events are listed in the report.
	/// To fetch the triggered events, please use submit_and_watch_extrinsic_until.
	/// Upon success, a report containing the following information is returned:
	/// - extrinsic hash
	/// - if watched until at least `InBlock`:
	///   hash of the block the extrinsic was included in
	/// - last known extrinsic (transaction) status
	///
	/// This method is blocking if the sync-api feature is activated
	async fn submit_and_watch_extrinsic_until_without_events<
		Address,
		Call,
		Signature,
		SignedExtra,
	>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode;

	/// Submit an encoded, opaque extrinsic and watch it until the desired status
	/// is reached, if no error is encountered previously.
	/// The events are not fetched. So no events are listed in the report.
	/// To fetch the triggered events, please use submit_and_watch_opaque_extrinsic_until.
	/// Upon success, a report containing the following information is returned:
	/// - extrinsic hash
	/// - if watched until at least `InBlock`:
	///   hash of the block the extrinsic was included in
	/// - last known extrinsic (transaction) status
	///
	/// This method is blocking if the sync-api feature is activated
	async fn submit_and_watch_opaque_extrinsic_until_without_events(
		&self,
		encoded_extrinsic: &Bytes,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>>;

	/// Query the events for the specified `report` and attaches them to the mutable report.
	/// If the function fails events might still be added to the report.
	///
	/// This method is blocking if the sync-api feature is activated
	async fn populate_events(&self, report: &mut ExtrinsicReport<Self::Hash>) -> Result<()>;
}

#[maybe_async::maybe_async(?Send)]
impl<T, Client> SubmitAndWatch for Api<T, Client>
where
	T: Config,
	Client: Subscribe + Request,
{
	type Client = Client;
	type Hash = T::Hash;

	async fn submit_and_watch_extrinsic<Address, Call, Signature, SignedExtra>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
	) -> Result<TransactionSubscriptionFor<Self::Client, Self::Hash>>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode,
	{
		self.submit_and_watch_opaque_extrinsic(&extrinsic.encode().into()).await
	}

	async fn submit_and_watch_opaque_extrinsic(
		&self,
		encoded_extrinsic: &Bytes,
	) -> Result<TransactionSubscriptionFor<Self::Client, Self::Hash>> {
		self.client()
			.subscribe(
				"author_submitAndWatchExtrinsic",
				rpc_params![encoded_extrinsic],
				"author_unsubmitAndWatchExtrinsic",
			)
			.await
			.map_err(|e| e.into())
	}

	async fn submit_and_watch_extrinsic_until<Address, Call, Signature, SignedExtra>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode,
	{
		self.submit_and_watch_opaque_extrinsic_until(&extrinsic.encode().into(), watch_until)
			.await
	}

	async fn submit_and_watch_opaque_extrinsic_until(
		&self,
		encoded_extrinsic: &Bytes,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>> {
		let mut report = self
			.submit_and_watch_opaque_extrinsic_until_without_events(encoded_extrinsic, watch_until)
			.await?;

		if watch_until < XtStatus::InBlock {
			return Ok(report)
		}
		self.populate_events(&mut report).await?;
		report.check_events_for_dispatch_error(self.metadata())?;
		return Ok(report);
	}

	async fn populate_events(&self, report: &mut ExtrinsicReport<Self::Hash>) -> Result<()> {
		if report.events.is_some() {
			return Err(Error::EventsAlreadyPresent)
		}
		let block_hash = report.block_hash.ok_or(Error::BlockHashNotFound)?;
		let extrinsic_events =
			self.fetch_events_for_extrinsic(block_hash, report.extrinsic_hash).await?;
		report.add_events(extrinsic_events);
		Ok(())
	}

	async fn submit_and_watch_extrinsic_until_without_events<
		Address,
		Call,
		Signature,
		SignedExtra,
	>(
		&self,
		extrinsic: UncheckedExtrinsicV4<Address, Call, Signature, SignedExtra>,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>>
	where
		Address: Encode,
		Call: Encode,
		Signature: Encode,
		SignedExtra: Encode,
	{
		self.submit_and_watch_opaque_extrinsic_until_without_events(
			&extrinsic.encode().into(),
			watch_until,
		)
		.await
	}

	async fn submit_and_watch_opaque_extrinsic_until_without_events(
		&self,
		encoded_extrinsic: &Bytes,
		watch_until: XtStatus,
	) -> Result<ExtrinsicReport<Self::Hash>> {
		let tx_hash = T::Hasher::hash(encoded_extrinsic);
		let mut subscription: TransactionSubscriptionFor<Self::Client, Self::Hash> =
			self.submit_and_watch_opaque_extrinsic(encoded_extrinsic).await?;

		while let Some(transaction_status) = subscription.next().await {
			let transaction_status = transaction_status?;
			match transaction_status.is_expected() {
				Ok(_) =>
					if transaction_status.reached_status(watch_until) {
						subscription.unsubscribe().await?;
						let block_hash = transaction_status.get_maybe_block_hash();
						return Ok(ExtrinsicReport::new(
							tx_hash,
							block_hash.copied(),
							transaction_status,
							None,
						))
					},
				Err(e) => {
					subscription.unsubscribe().await?;
					return Err(e)
				},
			}
		}
		Err(Error::NoStream)
	}
}