referrerpolicy=no-referrer-when-downgrade

snowbridge_outbound_queue_primitives/v1/
message.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2023 Snowfork <hello@snowfork.com>
3//! # Outbound V1 primitives
4
5use crate::{OperatingMode, SendError, SendMessageFeeProvider};
6use codec::{Decode, DecodeWithMemTracking, Encode};
7use ethabi::Token;
8use scale_info::TypeInfo;
9use snowbridge_core::{pricing::UD60x18, ChannelId};
10use sp_arithmetic::traits::{BaseArithmetic, Unsigned};
11use sp_core::{RuntimeDebug, H160, H256, U256};
12use sp_std::{borrow::ToOwned, vec, vec::Vec};
13
14/// Enqueued outbound messages need to be versioned to prevent data corruption
15/// or loss after forkless runtime upgrades
16#[derive(Encode, Decode, TypeInfo, Clone, RuntimeDebug)]
17#[cfg_attr(feature = "std", derive(PartialEq))]
18pub enum VersionedQueuedMessage {
19	V1(QueuedMessage),
20}
21
22impl TryFrom<VersionedQueuedMessage> for QueuedMessage {
23	type Error = ();
24	fn try_from(x: VersionedQueuedMessage) -> Result<Self, Self::Error> {
25		use VersionedQueuedMessage::*;
26		match x {
27			V1(x) => Ok(x),
28		}
29	}
30}
31
32impl<T: Into<QueuedMessage>> From<T> for VersionedQueuedMessage {
33	fn from(x: T) -> Self {
34		VersionedQueuedMessage::V1(x.into())
35	}
36}
37
38/// A message which can be accepted by implementations of `/[`SendMessage`\]`
39#[derive(Encode, Decode, TypeInfo, Clone, RuntimeDebug)]
40#[cfg_attr(feature = "std", derive(PartialEq))]
41pub struct Message {
42	/// ID for this message. One will be automatically generated if not provided.
43	///
44	/// When this message is created from an XCM message, the ID should be extracted
45	/// from the `SetTopic` instruction.
46	///
47	/// The ID plays no role in bridge consensus, and is purely meant for message tracing.
48	pub id: Option<H256>,
49	/// The message channel ID
50	pub channel_id: ChannelId,
51	/// The stable ID for a receiving gateway contract
52	pub command: Command,
53}
54
55/// A command which is executable by the Gateway contract on Ethereum
56#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
57#[cfg_attr(feature = "std", derive(PartialEq))]
58pub enum Command {
59	/// Execute a sub-command within an agent for a consensus system in Polkadot
60	/// DEPRECATED in favour of `UnlockNativeToken`. We still have to keep it around in
61	/// case buffered and uncommitted messages are using this variant.
62	AgentExecute {
63		/// The ID of the agent
64		agent_id: H256,
65		/// The sub-command to be executed
66		command: AgentExecuteCommand,
67	},
68	/// Upgrade the Gateway contract
69	Upgrade {
70		/// Address of the new implementation contract
71		impl_address: H160,
72		/// Codehash of the implementation contract
73		impl_code_hash: H256,
74		/// Optionally invoke an initializer in the implementation contract
75		initializer: Option<Initializer>,
76	},
77	/// Set the global operating mode of the Gateway contract
78	SetOperatingMode {
79		/// The new operating mode
80		mode: OperatingMode,
81	},
82	/// Set token fees of the Gateway contract
83	SetTokenTransferFees {
84		/// The fee(DOT) for the cost of creating asset on AssetHub
85		create_asset_xcm: u128,
86		/// The fee(DOT) for the cost of sending asset on AssetHub
87		transfer_asset_xcm: u128,
88		/// The fee(Ether) for register token to discourage spamming
89		register_token: U256,
90	},
91	/// Set pricing parameters
92	SetPricingParameters {
93		// ETH/DOT exchange rate
94		exchange_rate: UD60x18,
95		// Cost of delivering a message from Ethereum to BridgeHub, in ROC/KSM/DOT
96		delivery_cost: u128,
97		// Fee multiplier
98		multiplier: UD60x18,
99	},
100	/// Transfer ERC20 tokens
101	UnlockNativeToken {
102		/// ID of the agent
103		agent_id: H256,
104		/// Address of the ERC20 token
105		token: H160,
106		/// The recipient of the tokens
107		recipient: H160,
108		/// The amount of tokens to transfer
109		amount: u128,
110	},
111	/// Register foreign token from Polkadot
112	RegisterForeignToken {
113		/// ID for the token
114		token_id: H256,
115		/// Name of the token
116		name: Vec<u8>,
117		/// Short symbol for the token
118		symbol: Vec<u8>,
119		/// Number of decimal places
120		decimals: u8,
121	},
122	/// Mint foreign token from Polkadot
123	MintForeignToken {
124		/// ID for the token
125		token_id: H256,
126		/// The recipient of the newly minted tokens
127		recipient: H160,
128		/// The amount of tokens to mint
129		amount: u128,
130	},
131}
132
133impl Command {
134	/// Compute the enum variant index
135	pub fn index(&self) -> u8 {
136		match self {
137			Command::AgentExecute { .. } => 0,
138			Command::Upgrade { .. } => 1,
139			Command::SetOperatingMode { .. } => 5,
140			Command::SetTokenTransferFees { .. } => 7,
141			Command::SetPricingParameters { .. } => 8,
142			Command::UnlockNativeToken { .. } => 9,
143			Command::RegisterForeignToken { .. } => 10,
144			Command::MintForeignToken { .. } => 11,
145		}
146	}
147
148	/// ABI-encode the Command.
149	pub fn abi_encode(&self) -> Vec<u8> {
150		match self {
151			Command::AgentExecute { agent_id, command } => ethabi::encode(&[Token::Tuple(vec![
152				Token::FixedBytes(agent_id.as_bytes().to_owned()),
153				Token::Bytes(command.abi_encode()),
154			])]),
155			Command::Upgrade { impl_address, impl_code_hash, initializer, .. } =>
156				ethabi::encode(&[Token::Tuple(vec![
157					Token::Address(*impl_address),
158					Token::FixedBytes(impl_code_hash.as_bytes().to_owned()),
159					initializer.clone().map_or(Token::Bytes(vec![]), |i| Token::Bytes(i.params)),
160				])]),
161			Command::SetOperatingMode { mode } =>
162				ethabi::encode(&[Token::Tuple(vec![Token::Uint(U256::from((*mode) as u64))])]),
163			Command::SetTokenTransferFees {
164				create_asset_xcm,
165				transfer_asset_xcm,
166				register_token,
167			} => ethabi::encode(&[Token::Tuple(vec![
168				Token::Uint(U256::from(*create_asset_xcm)),
169				Token::Uint(U256::from(*transfer_asset_xcm)),
170				Token::Uint(*register_token),
171			])]),
172			Command::SetPricingParameters { exchange_rate, delivery_cost, multiplier } =>
173				ethabi::encode(&[Token::Tuple(vec![
174					Token::Uint(exchange_rate.clone().into_inner()),
175					Token::Uint(U256::from(*delivery_cost)),
176					Token::Uint(multiplier.clone().into_inner()),
177				])]),
178			Command::UnlockNativeToken { agent_id, token, recipient, amount } =>
179				ethabi::encode(&[Token::Tuple(vec![
180					Token::FixedBytes(agent_id.as_bytes().to_owned()),
181					Token::Address(*token),
182					Token::Address(*recipient),
183					Token::Uint(U256::from(*amount)),
184				])]),
185			Command::RegisterForeignToken { token_id, name, symbol, decimals } =>
186				ethabi::encode(&[Token::Tuple(vec![
187					Token::FixedBytes(token_id.as_bytes().to_owned()),
188					Token::String(name.to_owned()),
189					Token::String(symbol.to_owned()),
190					Token::Uint(U256::from(*decimals)),
191				])]),
192			Command::MintForeignToken { token_id, recipient, amount } =>
193				ethabi::encode(&[Token::Tuple(vec![
194					Token::FixedBytes(token_id.as_bytes().to_owned()),
195					Token::Address(*recipient),
196					Token::Uint(U256::from(*amount)),
197				])]),
198		}
199	}
200}
201
202/// Representation of a call to the initializer of an implementation contract.
203/// The initializer has the following ABI signature: `initialize(bytes)`.
204#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, RuntimeDebug, TypeInfo)]
205pub struct Initializer {
206	/// ABI-encoded params of type `bytes` to pass to the initializer
207	pub params: Vec<u8>,
208	/// The initializer is allowed to consume this much gas at most.
209	pub maximum_required_gas: u64,
210}
211
212/// A Sub-command executable within an agent
213#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
214#[cfg_attr(feature = "std", derive(PartialEq))]
215pub enum AgentExecuteCommand {
216	/// Transfer ERC20 tokens
217	TransferToken {
218		/// Address of the ERC20 token
219		token: H160,
220		/// The recipient of the tokens
221		recipient: H160,
222		/// The amount of tokens to transfer
223		amount: u128,
224	},
225}
226
227impl AgentExecuteCommand {
228	fn index(&self) -> u8 {
229		match self {
230			AgentExecuteCommand::TransferToken { .. } => 0,
231		}
232	}
233
234	/// ABI-encode the sub-command
235	pub fn abi_encode(&self) -> Vec<u8> {
236		match self {
237			AgentExecuteCommand::TransferToken { token, recipient, amount } => ethabi::encode(&[
238				Token::Uint(self.index().into()),
239				Token::Bytes(ethabi::encode(&[
240					Token::Address(*token),
241					Token::Address(*recipient),
242					Token::Uint(U256::from(*amount)),
243				])),
244			]),
245		}
246	}
247}
248
249/// Message which is awaiting processing in the MessageQueue pallet
250#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
251#[cfg_attr(feature = "std", derive(PartialEq))]
252pub struct QueuedMessage {
253	/// Message ID
254	pub id: H256,
255	/// Channel ID
256	pub channel_id: ChannelId,
257	/// Command to execute in the Gateway contract
258	pub command: Command,
259}
260
261#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
262#[cfg_attr(feature = "std", derive(PartialEq))]
263/// Fee for delivering message
264pub struct Fee<Balance>
265where
266	Balance: BaseArithmetic + Unsigned + Copy,
267{
268	/// Fee to cover cost of processing the message locally
269	pub local: Balance,
270	/// Fee to cover cost processing the message remotely
271	pub remote: Balance,
272}
273
274impl<Balance> Fee<Balance>
275where
276	Balance: BaseArithmetic + Unsigned + Copy,
277{
278	pub fn total(&self) -> Balance {
279		self.local.saturating_add(self.remote)
280	}
281}
282
283impl<Balance> From<(Balance, Balance)> for Fee<Balance>
284where
285	Balance: BaseArithmetic + Unsigned + Copy,
286{
287	fn from((local, remote): (Balance, Balance)) -> Self {
288		Self { local, remote }
289	}
290}
291
292/// A trait for sending messages to Ethereum
293pub trait SendMessage: SendMessageFeeProvider {
294	type Ticket: Clone + Encode + Decode;
295
296	/// Validate an outbound message and return a tuple:
297	/// 1. Ticket for submitting the message
298	/// 2. Delivery fee
299	fn validate(
300		message: &Message,
301	) -> Result<(Self::Ticket, Fee<<Self as SendMessageFeeProvider>::Balance>), SendError>;
302
303	/// Submit the message ticket for eventual delivery to Ethereum
304	fn deliver(ticket: Self::Ticket) -> Result<H256, SendError>;
305}
306
307pub trait Ticket: Encode + Decode + Clone {
308	fn message_id(&self) -> H256;
309}
310
311pub trait GasMeter {
312	/// All the gas used for submitting a message to Ethereum, minus the cost of dispatching
313	/// the command within the message
314	const MAXIMUM_BASE_GAS: u64;
315
316	/// Total gas consumed at most, including verification & dispatch
317	fn maximum_gas_used_at_most(command: &Command) -> u64 {
318		Self::MAXIMUM_BASE_GAS + Self::maximum_dispatch_gas_used_at_most(command)
319	}
320
321	/// Measures the maximum amount of gas a command payload will require to *dispatch*, NOT
322	/// including validation & verification.
323	fn maximum_dispatch_gas_used_at_most(command: &Command) -> u64;
324}
325
326/// A meter that assigns a constant amount of gas for the execution of a command
327///
328/// The gas figures are extracted from this report:
329/// > forge test --match-path test/Gateway.t.sol --gas-report
330///
331/// A healthy buffer is added on top of these figures to account for:
332/// * The EIP-150 63/64 rule
333/// * Future EVM upgrades that may increase gas cost
334pub struct ConstantGasMeter;
335
336impl GasMeter for ConstantGasMeter {
337	// The base transaction cost, which includes:
338	// 21_000 transaction cost, roughly worst case 64_000 for calldata, and 100_000
339	// for message verification
340	const MAXIMUM_BASE_GAS: u64 = 185_000;
341
342	fn maximum_dispatch_gas_used_at_most(command: &Command) -> u64 {
343		match command {
344			Command::SetOperatingMode { .. } => 40_000,
345			Command::AgentExecute { command, .. } => match command {
346				// Execute IERC20.transferFrom
347				//
348				// Worst-case assumptions are important:
349				// * No gas refund for clearing storage slot of source account in ERC20 contract
350				// * Assume dest account in ERC20 contract does not yet have a storage slot
351				// * ERC20.transferFrom possibly does other business logic besides updating balances
352				AgentExecuteCommand::TransferToken { .. } => 200_000,
353			},
354			Command::Upgrade { initializer, .. } => {
355				let initializer_max_gas = match *initializer {
356					Some(Initializer { maximum_required_gas, .. }) => maximum_required_gas,
357					None => 0,
358				};
359				// total maximum gas must also include the gas used for updating the proxy before
360				// the the initializer is called.
361				50_000 + initializer_max_gas
362			},
363			Command::SetTokenTransferFees { .. } => 60_000,
364			Command::SetPricingParameters { .. } => 60_000,
365			Command::UnlockNativeToken { .. } => 200_000,
366			Command::RegisterForeignToken { .. } => 1_200_000,
367			Command::MintForeignToken { .. } => 100_000,
368		}
369	}
370}
371
372impl GasMeter for () {
373	const MAXIMUM_BASE_GAS: u64 = 1;
374
375	fn maximum_dispatch_gas_used_at_most(_: &Command) -> u64 {
376		1
377	}
378}
379
380pub const ETHER_DECIMALS: u8 = 18;