Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XCM builder pattern #2107

Merged
merged 17 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions polkadot/xcm/procedural/src/builder_pattern.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use syn::{parse_macro_input, DeriveInput, Data, Error, Fields};
use quote::{quote, format_ident};

pub fn derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let builder_impl = match &input.data {
Data::Enum(data_enum) => generate_methods_for_enum(input.ident, data_enum),
_ => return Error::new_spanned(&input, "Expected the `Instruction` enum")
franciscoaguirre marked this conversation as resolved.
Show resolved Hide resolved
.to_compile_error().into(),
};
let output = quote! {
pub struct XcmBuilder<Call>(Vec<Instruction<Call>>);
impl<Call> Xcm<Call> {
pub fn builder() -> XcmBuilder<Call> {
XcmBuilder::<Call>(Vec::new())
}
}
#builder_impl
};
output.into()
}

fn generate_methods_for_enum(name: syn::Ident, data_enum: &syn::DataEnum) -> TokenStream2 {
let methods = data_enum.variants.iter().map(|variant| {
let variant_name = &variant.ident;
let method_name_string = to_snake_case(&variant_name.to_string());
let method_name = syn::Ident::new(&method_name_string, variant_name.span());
match &variant.fields {
Fields::Unit => {
quote! {
pub fn #method_name(mut self) -> Self {
franciscoaguirre marked this conversation as resolved.
Show resolved Hide resolved
self.0.push(#name::<Call>::#variant_name);
self
}
}
},
Fields::Unnamed(fields) => {
let arg_names: Vec<_> = fields.unnamed.iter().enumerate()
.map(|(index, _)| format_ident!("arg{}", index))
.collect();
let arg_types: Vec<_> = fields.unnamed.iter().map(|field| &field.ty)
.collect();
quote! {
pub fn #method_name(mut self, #(#arg_names: #arg_types),*) -> Self {
self.0.push(#name::<Call>::#variant_name(#(#arg_names),*));
self
}
}
},
Fields::Named(fields) => {
let arg_names: Vec<_> = fields.named.iter().map(|field| &field.ident).collect();
let arg_types: Vec<_> = fields.named.iter().map(|field| &field.ty).collect();
quote! {
pub fn #method_name(mut self, #(#arg_names: #arg_types),*) -> Self {
self.0.push(#name::<Call>::#variant_name { #(#arg_names),* });
self
}
}
},
}
});
let output = quote! {
impl<Call> XcmBuilder<Call> {
#(#methods)*

pub fn build(self) -> Xcm<Call> {
Xcm(self.0)
}
}
};
output
}

fn to_snake_case(s: &str) -> String {
let mut snake = String::with_capacity(s.len());
let mut chars = s.chars().peekable();

while let Some(ch) = chars.next() {
// If it's an uppercase character and not the start
if ch.is_uppercase() && !snake.is_empty() {
// If the next character is lowercase, prepend an underscore
if chars.peek().map_or(false, |next| next.is_lowercase()) {
snake.push('_');
}
}

snake.extend(ch.to_lowercase());
}

snake
}
franciscoaguirre marked this conversation as resolved.
Show resolved Hide resolved
13 changes: 13 additions & 0 deletions polkadot/xcm/procedural/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use proc_macro::TokenStream;
mod v2;
mod v3;
mod weight_info;
mod builder_pattern;

#[proc_macro]
pub fn impl_conversion_functions_for_multilocation_v2(input: TokenStream) -> TokenStream {
Expand All @@ -47,3 +48,15 @@ pub fn impl_conversion_functions_for_junctions_v3(input: TokenStream) -> TokenSt
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}

/// This is called on the `Instruction` enum, not on the `Xcm` struct,
/// and allows for the following syntax for building XCMs:
/// let message = Xcm::builder()
/// .withdraw_asset(assets)
/// .buy_execution(fees, weight_limit)
/// .deposit_asset(assets, beneficiary)
/// .build();
#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
builder_pattern::derive(input)
}
2 changes: 1 addition & 1 deletion polkadot/xcm/src/v3/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ impl XcmContext {
///
/// This is the inner XCM format and is version-sensitive. Messages are typically passed using the
/// outer XCM format, known as `VersionedXcm`.
#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait)]
#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait, xcm_procedural::Builder)]
#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))]
#[codec(encode_bound())]
#[codec(decode_bound())]
Expand Down
16 changes: 16 additions & 0 deletions polkadot/xcm/xcm-simulator/example/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -649,4 +649,20 @@ mod tests {
);
});
}

#[test]
fn builder_pattern_works() {
let asset: MultiAsset = (Here, 100u128).into();
let beneficiary: MultiLocation = AccountId32 { id: [0u8; 32], network: None }.into();
let message: Xcm<()> = Xcm::builder()
.withdraw_asset(asset.clone().into())
.buy_execution(asset.clone(), Unlimited)
.deposit_asset(asset.clone().into(), beneficiary)
.build();
KiChjang marked this conversation as resolved.
Show resolved Hide resolved
assert_eq!(message, Xcm(vec![
WithdrawAsset(asset.clone().into()),
BuyExecution { fees: asset.clone(), weight_limit: Unlimited },
DepositAsset { assets: asset.into(), beneficiary },
]));
}
}
Loading