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
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
#![feature(box_into_inner)]
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use proc_macro_error::{abort, abort_call_site, proc_macro_error};
use quote::quote;
use regex::Regex;
use tiny_keccak::{Hasher, Keccak};
fn get_function_signature(function_prototype: &str) -> [u8; 4] {
    let mut sig = [0; 4];
    let mut hasher = Keccak::v256();
    hasher.update(function_prototype.as_bytes());
    hasher.finalize(&mut sig);
    sig
}

fn write_function_signature(sig_str: &str) -> String {
    let re = Regex::new(r"^(?P<name>[^(]+?)\((?P<params>[^)]*?)\)").unwrap();
    if let Some(cap) = re.captures(sig_str) {
        let fn_name = cap.name("name").unwrap().as_str();
        let params = cap.name("params").unwrap().as_str().replace(" ", "");
        let canonical_fn = format!(
            "{}({})",
            fn_name,
            params
                .split(',')
                .map(|p| {
                    let p_split = p.split(':').collect::<Vec<_>>();
                    if p_split.len() == 2 {
                        p_split[1]
                    } else {
                        p_split[0]
                    }
                    .trim()
                })
                .collect::<Vec<_>>()
                .join(",")
        );
        format!(r"{:?}", get_function_signature(&canonical_fn))
    } else {
        format!(
            "{}_SIG",
            sig_str.to_string().replace(" ", "").to_ascii_uppercase()
        )
    }
}

/// helps you setup the main function of a contract
///
/// There are three different kind contract output.
///
/// `#[ewasm_main]`
/// The default contract output, the error will be return as a string message
/// This is for a scenario that you just want to modify the data on
/// chain only, and the error will to string than return.
///
/// `#[ewasm_main(rusty)]`
/// The rust styl output, the result object from ewasm_main function will be
/// returned, this is for a scenario that you are using a rust client to catch
/// and want to catch the result from the contract.
///
/// `#[ewasm_main(auto)]`
/// Auto unwrap the output of the result object from ewasm_main function.
/// This is for a scenario that you are using a rust non-rust client,
/// and you are only care the happy case of executing the contract.
///
/// ```compile_fail
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let contract = Contract::new()?;
///     match contract.get_function_selector()? {
///         ewasm_fn_sig!(check_input_object) => ewasm_input_from!(contract move check_input_object)?,
///         _ => return Err(Error::UnknownHandle.into()),
///     };
///     Ok(())
/// }
/// ```
#[proc_macro_error]
#[proc_macro_attribute]
pub fn ewasm_main(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let name = &input.sig.ident;
    if !input.sig.inputs.is_empty() {
        abort!(
            input.sig.inputs,
            "ewasm_main only wrap the function without inputs"
        )
    }

    let output_type = match input.sig.clone().output {
        syn::ReturnType::Type(_, boxed) => match Box::into_inner(boxed) {
            syn::Type::Path(syn::TypePath { path: p, .. }) => {
                let mut ok_type: Option<String> = None;
                let mut segments = p.segments;
                while let Some(pair) = segments.pop() {
                    ok_type = match pair.into_value() {
                        syn::PathSegment {
                            arguments:
                                syn::PathArguments::AngleBracketed(
                                    syn::AngleBracketedGenericArguments { args: a, .. },
                                ),
                            ..
                        } => match a.first() {
                            Some(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
                                path: p,
                                ..
                            }))) => {
                                if let Some(syn::PathSegment { ident: i, .. }) = p.segments.last() {
                                    Some(i.to_string())
                                } else {
                                    None
                                }
                            }
                            _ => None,
                        },
                        _ => None,
                    };
                    if ok_type.is_some() {
                        break;
                    }
                }
                ok_type
            }
            _ => None,
        },
        _ => None,
    };

    match attr.to_string().to_lowercase().as_str() {
        "auto" if Some("EwasmAny".to_string()) == output_type  => quote! {
            #[cfg(target_arch = "wasm32")]
            use sewup::bincode;
            #[cfg(target_arch = "wasm32")]
            use sewup::ewasm_api::finish_data;
            #[cfg(all(not(target_arch = "wasm32"), not(test)))]
            pub fn main() {}
            #[cfg(target_arch = "wasm32")]
            #[cfg(not(any(feature = "constructor", feature = "constructor-test")))]
            #[no_mangle]
            pub fn main() {
                #input
                match #name() {
                    Ok(r) =>  {
                        finish_data(&r.bin);
                    },
                    Err(e) => {
                        let error_msg = e.to_string();
                        finish_data(&error_msg.as_bytes());
                    }
                }
            }
        },
        // Return the inner structure from unwrap result
        // This is for a scenario that you take care the result but not using Rust client
        "auto" => quote! {
            #[cfg(target_arch = "wasm32")]
            use sewup::bincode;
            #[cfg(target_arch = "wasm32")]
            use sewup::ewasm_api::finish_data;
            #[cfg(all(not(target_arch = "wasm32"), not(test)))]
            pub fn main() {}
            #[cfg(target_arch = "wasm32")]
            #[cfg(not(any(feature = "constructor", feature = "constructor-test")))]
            #[no_mangle]
            pub fn main() {
                #input
                match #name() {
                    Ok(r) =>  {
                        let bin = bincode::serialize(&r).expect("The resuslt of `ewasm_main` should be serializable");
                        finish_data(&bin);
                    },
                    Err(e) => {
                        let error_msg = e.to_string();
                        finish_data(&error_msg.as_bytes());
                    }
                }
            }
        },
        "rusty" if Some("EwasmAny".to_string()) == output_type  => quote! {
            #[cfg(target_arch = "wasm32")]
            use sewup::bincode;
            #[cfg(target_arch = "wasm32")]
            use sewup::ewasm_api::finish_data;
            #[cfg(all(not(target_arch = "wasm32"), not(test)))]
            pub fn main() {}
            #[cfg(target_arch = "wasm32")]
            #[cfg(not(any(feature = "constructor", feature = "constructor-test")))]
            #[no_mangle]
            pub fn main() {
                #input
                let r = #name().map(|any| any.bin);
                let bin = bincode::serialize(&r).expect("The resuslt of `ewasm_main` should be serializable");
                finish_data(&bin);
            }
        },

        // Return all result structure
        // This is for a scenario that you are using a rust client to operation the contract
        "rusty" => quote! {
            #[cfg(target_arch = "wasm32")]
            use sewup::bincode;
            #[cfg(target_arch = "wasm32")]
            use sewup::ewasm_api::finish_data;
            #[cfg(all(not(target_arch = "wasm32"), not(test)))]
            pub fn main() {}
            #[cfg(target_arch = "wasm32")]
            #[cfg(not(any(feature = "constructor", feature = "constructor-test")))]
            #[no_mangle]
            pub fn main() {
                #input
                let r = #name();
                let bin = bincode::serialize(&r).expect("The resuslt of `ewasm_main` should be serializable");
                finish_data(&bin);
            }
        },

        // Default only return error message,
        // This is for a scenario that you just want to modify the data on
        // chain only
        _ => quote! {
            #[cfg(target_arch = "wasm32")]
            use sewup::bincode;
            #[cfg(target_arch = "wasm32")]
            use sewup::ewasm_api::finish_data;
            #[cfg(all(not(target_arch = "wasm32"), not(test)))]
            pub fn main() {}
            #[cfg(target_arch = "wasm32")]
            #[cfg(not(any(feature = "constructor", feature = "constructor-test")))]
            #[no_mangle]
            pub fn main() {
                #input
                if let Err(e) = #name() {
                    let error_msg = e.to_string();
                    finish_data(&error_msg.as_bytes());
                }
            }
        }
    }.into()
}

/// helps you to build your handlers in the contract
///
/// This macro also generate the function signature, you can use
/// `ewasm_fn_sig!` macro to get your function signature;
///
/// ```compile_fail
/// #[ewasm_fn]
/// fn check_input_object(s: SimpleStruct) -> anyhow::Result<()> {
///     Ok(())
/// }
///
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let contract = Contract::new()?;
///     match contract.get_function_selector()? {
///         ewasm_fn_sig!(check_input_object) => ewasm_input_from!(contract move check_input_object)?,
///         _ => return Err(Error::UnknownHandle.into()),
///     };
///     Ok(())
/// }
/// ```
///
#[proc_macro_error]
#[proc_macro_attribute]
pub fn ewasm_fn(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr_str = attr.to_string().replace(" ", "");
    let (hex_str, abi_str) = if attr_str.is_empty() {
        (None, "{}".to_string())
    } else if attr_str.starts_with('{') {
        (None, attr_str.split_whitespace().collect())
    } else if let Some((head, tail)) = attr_str.split_once(',') {
        (
            Some(head.replace("\"", "")),
            tail.split_whitespace().collect(),
        )
    } else {
        (Some(attr_str.replace("\"", "")), "{}".to_string())
    };

    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let name = &input.sig.ident;
    let args = &input
        .sig
        .inputs
        .iter()
        .map(|fn_arg| match fn_arg {
            syn::FnArg::Receiver(r) => {
                abort!(r, "please use ewasm_fn for function not method")
            }
            syn::FnArg::Typed(p) => Box::into_inner(p.ty.clone()),
        })
        .map(|ty| match ty {
            syn::Type::Path(tp) => (tp.path.segments.first().unwrap().ident.clone(), false),
            syn::Type::Reference(tr) => match Box::into_inner(tr.elem) {
                syn::Type::Path(tp) => (tp.path.segments.first().unwrap().ident.clone(), true),
                _ => abort_call_site!("please pass Path type or Reference type to ewasm_fn_sig"),
            },
            _ => abort_call_site!("please pass Path type or Reference type to ewasm_fn_sig"),
        })
        .map(|(ident, is_ref)| {
            if is_ref {
                format!("&{}", ident).to_ascii_lowercase()
            } else {
                format!("{}", ident).to_ascii_lowercase()
            }
        })
        .collect::<Vec<_>>()
        .join(",");
    let canonical_fn = format!("{}({})", name, args);
    let (sig_0, sig_1, sig_2, sig_3) = if let Some(hex_str) = hex_str {
        let fn_sig = hex::decode(hex_str).expect("function signature is not correct");
        (fn_sig[0], fn_sig[1], fn_sig[2], fn_sig[3])
    } else {
        let fn_sig = get_function_signature(&canonical_fn);
        (fn_sig[0], fn_sig[1], fn_sig[2], fn_sig[3])
    };
    let abi_info = Ident::new(
        &format!("{}_ABI", name.to_string().to_ascii_uppercase()),
        Span::call_site(),
    );
    let sig_name = Ident::new(
        &format!("{}_SIG", name.to_string().to_ascii_uppercase()),
        Span::call_site(),
    );
    let result = quote! {
        pub const #sig_name : [u8; 4] = [#sig_0, #sig_1, #sig_2, #sig_3];
        pub(crate) const #abi_info: &'static str = #abi_str;

        #[cfg(target_arch = "wasm32")]
        #[cfg(not(any(feature = "constructor", feature = "constructor-test")))]
        #input
    };
    result.into()
}

/// helps you to build your constructor for the contract
#[proc_macro_error]
#[proc_macro_attribute]
pub fn ewasm_constructor(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut input = syn::parse_macro_input!(item as syn::ItemFn);
    let default_name = Ident::new("__constructor", Span::call_site());
    if input.sig.ident != "__constructor" {
        input.sig.ident = default_name;
    }
    let result = quote! {
        #[cfg(target_arch = "wasm32")]
        #[cfg(any(feature = "constructor", feature = "constructor-test"))]
        #[no_mangle]
        #input

        #[cfg(target_arch = "wasm32")]
        #[cfg(feature = "constructor-test")]
        #[no_mangle]
        pub fn main() {
            __constructor();
        }
    };
    result.into()
}

/// helps you to build your handler in other module
///
/// This macro will automatically generated as `{FUNCTION_NAME}_SIG`
///
/// ```compile_fail
/// // module.rs
///
/// use sewup::ewasm_api;
///
/// #[ewasm_lib_fn]
/// pub fn symbol(s: &str) {
///     let symbol = s.to_string().into_bytes();
///     ewasm_api::finish_data(&symbol);
/// }
/// ```
///
/// ```compile_fail
/// // lib.rs
///
/// use module::{symbol, SYMBOL_SIG};
///
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let contract = Contract::new()?;
///     match contract.get_function_selector()? {
///         SYMBOL_SIG => symbol("ETD"),
///         _ => return Err(Error::UnknownHandle.into()),
///     };
///     Ok(())
/// }
/// ```
#[proc_macro_error]
#[proc_macro_attribute]
pub fn ewasm_lib_fn(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr_str = attr.to_string().replace(" ", "");
    let (hex_str, abi_str) = if attr_str.is_empty() {
        (None, "{}".to_string())
    } else if attr_str.starts_with('{') {
        (None, attr_str)
    } else if let Some((head, tail)) = attr_str.split_once(',') {
        (Some(head.replace("\"", "")), tail.to_string())
    } else {
        (Some(attr_str.replace("\"", "")), "{}".to_string())
    };

    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let name = &input.sig.ident;
    let inputs = &input.sig.inputs;

    let (sig_0, sig_1, sig_2, sig_3) = if let Some(hex_str) = hex_str {
        let fn_sig = hex::decode(hex_str).expect("function signature is not correct");
        (fn_sig[0], fn_sig[1], fn_sig[2], fn_sig[3])
    } else {
        let args = &inputs
            .iter()
            .map(|fn_arg| match fn_arg {
                syn::FnArg::Receiver(r) => {
                    abort!(r, "please use ewasm_fn for function not method")
                }
                syn::FnArg::Typed(p) => Box::into_inner(p.ty.clone()),
            })
            .map(|ty| match ty {
                syn::Type::Path(tp) => (tp.path.segments.first().unwrap().ident.clone(), false),
                syn::Type::Reference(tr) => match Box::into_inner(tr.elem) {
                    syn::Type::Path(tp) => (tp.path.segments.first().unwrap().ident.clone(), true),
                    _ => {
                        abort_call_site!("please pass Path type or Reference type to ewasm_fn_sig")
                    }
                },
                _ => abort_call_site!("please pass Path type or Reference type to ewasm_fn_sig"),
            })
            .map(|(ident, is_ref)| {
                if is_ref {
                    format!("&{}", ident).to_ascii_lowercase()
                } else {
                    format!("{}", ident).to_ascii_lowercase()
                }
            })
            .collect::<Vec<_>>()
            .join(",");
        let canonical_fn = format!("{}({})", name, args);
        let fn_sig = get_function_signature(&canonical_fn);
        (fn_sig[0], fn_sig[1], fn_sig[2], fn_sig[3])
    };
    let sig_name = Ident::new(
        &format!("{}_SIG", name.to_string().to_ascii_uppercase()),
        Span::call_site(),
    );
    let abi_info = Ident::new(
        &format!("{}_ABI", name.to_string().to_ascii_uppercase()),
        Span::call_site(),
    );
    let result = quote! {
        pub const #sig_name: [u8; 4] = [#sig_0, #sig_1, #sig_2, #sig_3];
        pub const #abi_info: &'static str = #abi_str;

        #[cfg(not(target_arch = "wasm32"))]
        #[allow(unused)]
        pub fn #name(#inputs) {}

        #[cfg(target_arch = "wasm32")]
        #input
    };
    result.into()
}

/// helps you get you function signature
///
/// 1. provide function name to get function signature from the same namespace,
/// which function should be decorated with `#[ewasm_fn]`, for example,
/// `ewasm_fn_sig!(contract_handler)`
///
/// ```compile_fail
/// #[ewasm_fn]
/// fn decorated_handler(a: i32, b: String) -> Result<()> {
///     Ok(())
/// }
///
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let contract = Contract::new()?;
///     match contract.get_function_selector()? {
///         ewasm_fn_sig!(decorated_handler) => ewasm_input_from!(contract move decorated_handler)?,
///         _ => return Err(Error::UnknownHandle.into()),
///     };
///     Ok(())
/// }
/// ```
///
/// 2. provide a function name with input parameters then the macro will
/// calculate the correct functional signature for you.
/// ex: `ewasm_fn_sig!(undecorated_handler( a: i32, b: String ))`
///
/// ```compile_fail
/// // some_crate.rs
/// pub fn decorated_handler(a: i32, b: String) -> Result<()> {
///     Ok(())
/// }
/// ```
///
/// ```compile_fail
/// use some_crate::decorated_handler;
///
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let contract = Contract::new()?;
///     match contract.get_function_selector()? {
///         ewasm_fn_sig!(undecorated_handler(a: i32, b: String))
///             => ewasm_input_from!(contract move undecorated_handler)?,
///         _ => return Err(Error::UnknownHandle.into()),
///     };
///     Ok(())
/// }
/// ```
///
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_fn_sig(item: TokenStream) -> TokenStream {
    write_function_signature(&item.to_string()).parse().unwrap()
}

/// helps you generate the input raw data for specific contract handler
/// ```compile_fail
/// let create_input = person::protocol(person.clone());
/// let mut input = ewasm_input!(create_input for person::create);
/// ```
#[proc_macro]
pub fn ewasm_input(item: TokenStream) -> TokenStream {
    let re = Regex::new(r"(?P<instance>.*)\s+for\s+(?P<sig>.*)").unwrap();
    if let Some(cap) = re.captures(&item.to_string()) {
        let sig = cap.name("sig").unwrap().as_str();
        let instance = cap.name("instance").unwrap().as_str();
        let output = if instance == "None" {
            format!("{}.to_vec()", write_function_signature(sig),)
        } else {
            format!(
                "{{
                let mut input = {}.to_vec();
                input.append(&mut bincode::serialize(&{}).unwrap());
                input
            }}",
                write_function_signature(sig),
                instance
            )
        };
        output.parse().unwrap()
    } else {
        panic!("ewasm_input input incorrect")
    }
}

/// helps you to get the input data from contract caller
///
/// This macro automatically deserialize input into handler
/// `ewasm_input_from!(contract, the_name_of_the_handler)`
/// ```compile_fail
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let contract = Contract::new()?;
///     match contract.get_function_selector()? {
///         ewasm_fn_sig!(check_input_object) => ewasm_input_from!(contract move check_input_object)?,
///         _ => return Err(Error::UnknownHandle.into()),
///     };
///  Ok(())
///  }
/// ```
///
/// Besides, you can map the error to your customized error when something wrong happened in
/// `ewasm_input_from!`, for example:
/// `ewasm_input_from!(contract move check_input_object, |_| Err("DeserdeError"))`
/// ```compile_fail
/// #[ewasm_main(rusty)]
/// fn main() -> Result<(), &'static str> {
///     let contract = Contract::new().map_err(|_| "NewContractError")?;
///     match contract.get_function_selector().map_err(|_| "FailGetFnSelector")? {
///         ewasm_fn_sig!(check_input_object) =>  ewasm_input_from!(contract move check_input_object, |_| "DeserdeError")?
///         _ => return Err("UnknownHandle"),
///     };
///     Ok(())
/// }
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_input_from(item: TokenStream) -> TokenStream {
    let re =
        Regex::new(r"^(?P<contract>\w+)\s+move\s+(?P<name>[^,]+),?(?P<error_handler>.*)").unwrap();
    if let Some(cap) = re.captures(&item.to_string()) {
        let contract = Ident::new(cap.name("contract").unwrap().as_str(), Span::call_site());
        let name_result: syn::Result<syn::ExprPath> =
            syn::parse_str(cap.name("name").unwrap().as_str());
        let name = if let Ok(name) = name_result {
            name
        } else {
            abort_call_site!(
                "`{}` is not an ExprPath",
                cap.name("name").unwrap().as_str()
            );
        };
        let error_handler = cap.name("error_handler").unwrap().as_str();
        return if error_handler.is_empty() {
            quote! {
                #name(sewup::bincode::deserialize(&#contract.input_data[4..])
                      .map_err(|e| anyhow::anyhow!("contract input deserialize error: {}", e))?
                )
            }
        } else {
            let closure: syn::Result<syn::ExprClosure> = syn::parse_str(error_handler);
            if let Ok(closure) = closure {
                quote! {
                    #name(sewup::bincode::deserialize(&#contract.input_data[4..]).map_err(#closure)?)
                }
            } else {
                abort_call_site!("`{}` is not an closure input for map_err", error_handler);
            }
        }
        .into();
    } else {
        abort_call_site!(
            r#"fail to parsing ewasm_input_from,
            please use
                `ewasm_input_from( contract move handler )
            or
                `ewasm_input_from( contract move handler, closure_for_map_err)`
            "#
        );
    }
}

/// help you generate the exactly contract output form rust instance
#[proc_macro]
pub fn ewasm_output_from(item: TokenStream) -> TokenStream {
    format!(
        r#"sewup::bincode::serialize(&{}).expect("fail to serialize in `ewasm_output_from`")"#,
        item,
    )
    .parse()
    .unwrap()
}

/// `Key` derive help you implement Key trait for the kv feature
///
/// ```
/// use sewup_derive::Key;
/// #[derive(Key)]
/// struct SimpleStruct {
///     trust: bool,
///     description: String,
/// }
/// ```
#[cfg(feature = "kv")]
#[proc_macro_derive(Key)]
pub fn derive_key(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::DeriveInput);
    let sturct_name = &input.ident;
    return quote! {
        #[cfg(target_arch = "wasm32")]
        impl sewup::kv::traits::Key for #sturct_name {}
    }
    .into();
}

/// `Value` derive help you implement Value trait for kv feature
///
/// ```
/// use sewup_derive::Value;
/// #[derive(Value)]
/// struct SimpleStruct {
///     trust: bool,
///     description: String,
/// }
/// ```
#[cfg(feature = "kv")]
#[proc_macro_derive(Value)]
pub fn derive_value(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::DeriveInput);
    let sturct_name = &input.ident;
    return quote! {
        #[cfg(target_arch = "wasm32")]
        impl sewup::kv::traits::Value for #sturct_name {}
    }
    .into();
}

/// provides the handers for CRUD and the Protocol struct to communicate with these handlers.
///
/// ```compile_fail
/// use sewup_derive::Table;
/// #[derive(Table)]
/// struct Person {
///     trusted: bool,
///     age: u8,
/// }
/// ```
///
/// The crud handlers are generated as `{struct_name}::get`, `{struct_name}::create`,
/// `{struct_name}::update`, `{struct_name}::delete`, you can easily used these handlers as
/// following example.
///
/// ```compile_fail
/// #[ewasm_main]
/// fn main() -> Result<()> {
///     let mut contract = Contract::new()?;
///
///     match contract.get_function_selector()? {
///         ewasm_fn_sig!(person::get) => ewasm_input_from!(contract move person::get)?,
///         ewasm_fn_sig!(person::create) => ewasm_input_from!(contract move person::create)?,
///         ewasm_fn_sig!(person::update) => ewasm_input_from!(contract move person::update)?,
///         ewasm_fn_sig!(person::delete) => ewasm_input_from!(contract move person::delete)?,
///         _ => return Err(RDBError::UnknownHandle.into()),
///     }
///
///     Ok(())
/// }
/// ```
///
/// The protocol is the input and also the output format of these handlers, besides these handlers
/// are easy to build by the `{struct_name}::protocol`, `{struct_name}::Protocol`, and use `set_id`
/// for specify the record you want to modify.
/// for examples.
///
/// ```compile_fail
/// let handler_input = person::protocol(person);
/// let mut default_person_input: person::Protocol = Person::default().into();
/// default_input.set_id(2);
/// ```
///
/// you can use `ewasm_output_from!` to get the exactly input/output binary of the protol, for
/// example:
/// ```compile_fail
/// let handler_input = person::protocol(person);
/// ewasm_output_from!(handler_input)
/// ```
///
/// Please note that the protocol default and the protocol for default instance may be different.
/// This base on the implementation of the default trait of the structure.
///
/// ```compile_fail
/// let default_input = person::Protocol::default();
/// let default_person_input: person::Protocol = Person::default().into();
/// assert!(default_input != default_person_input)
/// ```
#[cfg(feature = "rdb")]
#[proc_macro_derive(Table, attributes(belongs_to, belongs_none_or))]
pub fn derive_table(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::DeriveInput);
    let attrs = &input.attrs;
    let mut belongs_to: Option<String> = None;
    for a in attrs.iter() {
        let syn::Attribute { path, tokens, .. } = a;
        let attr_name = path.segments.first().map(|s| s.ident.to_string());
        if Some("belongs_to".to_string()) == attr_name {
            belongs_to = Some(
                tokens
                    .to_string()
                    .strip_prefix('(')
                    .expect("#[belongs_to(table_name)] is not correct")
                    .strip_suffix(')')
                    .expect("#[belongs_to(table_name)] is not correct")
                    .to_string(),
            );
        }
    }
    let struct_name = &input.ident;
    let fields_with_type = match &input.data {
        syn::Data::Struct(syn::DataStruct {
            fields: syn::Fields::Named(f),
            ..
        }) => f
            .clone()
            .named
            .into_pairs()
            .map(|p| p.into_value())
            .map(|f| (f.ident.unwrap(), f.ty))
            .collect::<Vec<_>>(),
        _ => abort!(&input.ident, "Table derive only use for struct"),
    };

    let mut wrapper_fields = vec![(
        Ident::new("id", Span::call_site()),
        syn::Type::Path(syn::TypePath {
            qself: None,
            path: syn::parse("Option<usize>".parse().unwrap()).unwrap(),
        }),
    )];
    wrapper_fields.append(
        &mut fields_with_type
            .iter()
            .map(|(f, t)| {
                (
                    f.clone(),
                    syn::parse(quote!(Option<#t>).to_string().parse().unwrap()).unwrap(),
                )
            })
            .collect::<Vec<_>>(),
    );
    let wrapper_field_names = wrapper_fields.iter().map(|(f, _)| f);
    let wrapper_field_types = wrapper_fields.iter().map(|(_, t)| t);
    let field_names = fields_with_type.iter().map(|(f, _)| f);
    let clone_field_names = field_names.clone();
    let clone_field_names2 = field_names.clone();
    let clone_field_names3 = field_names.clone();
    let clone_field_names4 = field_names.clone();
    let clone_field_names5 = field_names.clone();
    let field_types = fields_with_type.iter().map(|(_, t)| t);

    let protocol_name = Ident::new(&format!("{}Protocol", struct_name), Span::call_site());
    let wrapper_name = Ident::new(&format!("{}Wrapper", struct_name), Span::call_site());
    let captal_name = Ident::new(
        &format!("{}", struct_name).to_ascii_uppercase(),
        Span::call_site(),
    );
    let lower_name = Ident::new(
        &format!("{}", struct_name).to_ascii_lowercase(),
        Span::call_site(),
    );
    let mut output = quote!(
        impl sewup::rdb::traits::Record for #struct_name {}

        #[cfg_attr(any(feature = "debug", test), derive(Debug))]
        #[derive(Clone, sewup::Serialize, sewup::Deserialize)]
        pub struct #protocol_name {
            pub select_fields: Option<std::collections::HashSet::<String>>,
            pub filter: bool,
            pub records: Vec<#wrapper_name>
        }

        impl #protocol_name {
            pub fn set_select_fields(&mut self, fields: Vec<String>) {
                if fields.is_empty() {
                    self.select_fields = None;
                } else {
                    let mut select_fields = std::collections::HashSet::<String>::new();
                    for field in fields.iter() {
                        select_fields.insert(field.into());
                    }
                    self.select_fields = Some(select_fields);
                }
            }
        }

        impl Default for #protocol_name {
            fn default() -> Self {
                Self {
                    select_fields: None,
                    filter: false,
                    records: vec![Default::default()]
                }
            }
        }

        impl From<#struct_name> for #protocol_name {
            fn from(instance: #struct_name) -> Self {
                Self {
                    select_fields: None,
                    filter: false,
                    records: vec![instance.into()]
                }
            }
        }

        impl From<(usize, #struct_name)> for #protocol_name {
            fn from(instance: (usize, #struct_name)) -> Self {
                Self {
                    select_fields: None,
                    filter: false,
                    records: vec![instance.into()]
                }
            }
        }

        impl From<Vec<#struct_name>> for #protocol_name {
            fn from(instances: Vec<#struct_name>) -> Self {
                Self {
                    select_fields: None,
                    filter: false,
                    records: instances.into_iter().map(|i| i.into()).collect::<Vec<_>>()
                }
            }
        }

        impl From<Vec<(usize, #struct_name)>> for #protocol_name {
            fn from(instances: Vec<(usize, #struct_name)>) -> Self {
                Self {
                    select_fields: None,
                    filter: false,
                    records: instances.into_iter().map(|i| i.into()).collect::<Vec<_>>()
                }
            }
        }

        impl From<Vec<#wrapper_name>> for #protocol_name {
            fn from(records: Vec<#wrapper_name>) -> Self {
                Self {
                    select_fields: None,
                    filter: false,
                    records,
                }
            }
        }

        pub mod #captal_name {
            use sewup_derive::ewasm_fn_sig;
            pub const GET_SIG: [u8; 4] = ewasm_fn_sig!(#struct_name::get());
            pub const CREATE_SIG: [u8; 4] = ewasm_fn_sig!(#struct_name::create());
            pub const UPDATE_SIG: [u8; 4] = ewasm_fn_sig!(#struct_name::update());
            pub const DELETE_SIG: [u8; 4] = ewasm_fn_sig!(#struct_name::delete());
        }

        #[cfg_attr(any(feature = "debug", test), derive(Debug))]
        #[derive(Default, Clone, sewup::Serialize, sewup::Deserialize)]
        pub struct #wrapper_name {
            #(pub #wrapper_field_names: #wrapper_field_types,)*
        }

        impl From<#struct_name> for #wrapper_name {
            fn from(instance: #struct_name) -> Self {
                Self {
                    id: None,
                    #(#field_names: Some(instance.#field_names),)*
                }
            }
        }

        impl From<(usize, #struct_name)> for #wrapper_name {
            fn from(t: (usize, #struct_name)) -> Self {
                Self {
                    id: Some(t.0),
                    #(#clone_field_names5: Some(t.1.#clone_field_names5),)*
                }
            }
        }

        impl From<#wrapper_name> for #struct_name {
            fn from(wrapper: #wrapper_name) -> Self {
                Self {
                    #(#clone_field_names: wrapper.#clone_field_names.expect("#clone_field_names field missing"),)*
                }
            }
        }
        #[cfg(target_arch = "wasm32")]
        pub mod #lower_name {
            use super::*;
            pub type Protocol = #protocol_name;
            pub type Wrapper = #wrapper_name;
            pub type _InstanceType = #struct_name;
            pub fn get(proc: Protocol) -> sewup::Result<sewup::primitives::EwasmAny> {
                let table = sewup::rdb::Db::load(None)?.table::<_InstanceType>()?;
                if proc.filter {
                    let mut raw_output: Vec<Wrapper> = Vec::new();
                    for (idx, r) in table.all_records()?.drain(..).enumerate(){
                        let mut all_field_match = true;
                        #(
                            paste::paste! {
                                let [<#clone_field_names2 _filed_filter>] : Option<#field_types> =
                                    sewup::utils::get_field_by_name(proc.records[0].clone(), stringify!(#clone_field_names2));

                                let  [<#clone_field_names2 _field>] : #field_types =
                                    sewup::utils::get_field_by_name(&r, stringify!(#clone_field_names2));

                                if [<#clone_field_names2 _filed_filter>].is_some() {
                                    all_field_match &=
                                        [<#clone_field_names2 _filed_filter>].unwrap()
                                            == [<#clone_field_names2 _field>];
                                }
                            }
                         )*

                        if all_field_match {
                            raw_output.push((idx + 1, r).into());
                        }
                    }
                    if let Some(select_fields) = proc.select_fields {
                        for w in raw_output.iter_mut() {
                            #(
                                if (! select_fields.contains(stringify!(#clone_field_names3)))
                                    && stringify!(#clone_field_names3) != "id" {
                                    w.#clone_field_names3 = None;
                                }
                            )*
                        }
                    }
                    let p: #protocol_name = raw_output.into();
                    Ok(p.into())
                } else {
                    let raw_output = table.get_record(proc.records[0].id.unwrap_or_default())?;
                    let mut output_proc: Protocol = raw_output.into();
                    output_proc.records[0].id = proc.records[0].id;
                    Ok(output_proc.into())
                }
            }
            pub fn create(proc: Protocol) -> sewup::Result<sewup::primitives::EwasmAny> {
                let mut table = sewup::rdb::Db::load(None)?.table::<_InstanceType>()?;
                let mut output_proc = proc.clone();
                output_proc.records[0].id = Some(table.add_record(proc.records[0].clone().into())?);
                table.commit()?;
                Ok(output_proc.into())
            }
            pub fn update(proc: Protocol) -> sewup::Result<sewup::primitives::EwasmAny> {
                let mut table = sewup::rdb::Db::load(None)?.table::<_InstanceType>()?;
                let id = proc.records[0].id.unwrap_or_default();
                table.update_record(id, Some(proc.records[0].clone().into()))?;
                table.commit()?;
                Ok(proc.into())
            }
            pub fn delete(proc: Protocol) -> sewup::Result<sewup::primitives::EwasmAny> {
                let mut table = sewup::rdb::Db::load(None)?.table::<_InstanceType>()?;
                let id = proc.records[0].id.unwrap_or_default();
                table.update_record(id, None)?;
                table.commit()?;
                Ok(proc.into())
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        pub mod #lower_name {
            use super::*;
            pub type Protocol = #protocol_name;
            pub type Wrapper = #wrapper_name;
            pub type _InstanceType = #struct_name;
            pub type Query = Wrapper;

            #[inline]
            pub fn protocol(instance: _InstanceType) -> Protocol {
                instance.into()
            }
            impl Protocol {
                pub fn set_id(&mut self, id: usize) {
                    self.records[0].id = Some(id);
                }
                pub fn is_empty(&self) -> bool {
                    #(self.records[0].#clone_field_names4.is_none() && )*
                    true
                }
            }
            pub fn query(instance: _InstanceType) -> Wrapper {
                instance.into()
            }

            impl From<Query> for Protocol {
                fn from(instance: Query) -> Self {
                    Self {
                        select_fields: None,
                        filter: true,
                        records: vec![instance.into()]
                    }
                }
            }
        }
    ).to_string();

    if let Some(parent_table) = belongs_to {
        let lower_parent_table = &format!("{}", &parent_table).to_ascii_lowercase();
        let parent_table = Ident::new(&parent_table, Span::call_site());
        let lower_parent_table_ident = Ident::new(&lower_parent_table, Span::call_site());
        let field_name = &format!("{}_id", lower_parent_table);

        output += &quote! {
            impl #struct_name {
                pub fn #lower_parent_table_ident (&self) -> sewup::Result<#parent_table> {
                    let id: usize = sewup::utils::get_field_by_name(self, #field_name);
                    let parent_table = sewup::rdb::Db::load(None)?.table::<#parent_table>()?;
                    parent_table.get_record(id)
                }
            }
        }
        .to_string();
    }

    output.parse().unwrap()
}

/// helps you setup the test mododule, and test cases in contract.
/// ```compile_fail
/// #[ewasm_test]
/// mod tests {
///     use super::*;
///
///     #[ewasm_test]
///     fn test_execute_basic_operations() {
///         ewasm_assert_ok!(contract_fn());
///     }
/// }
/// ```
/// The test runtime will be create in the module, and all the test case will use the same test
/// runtime, if you can create more runtimes for testing by setup more test modules.
/// You can setup a log file when running the test as following, then use `sewup::ewasm_dbg!` to debug the
/// ewasm contract in the executing in the runtime.
/// ```compile_fail
/// #[ewasm_test(log=/path/to/logfile)]
/// mod tests {
///     use super::*;
///
///     #[ewasm_test]
///     fn test_execute_basic_operations() {
///         ewasm_assert_ok!(contract_fn());
///     }
/// }
/// ```
#[proc_macro_error]
#[proc_macro_attribute]
pub fn ewasm_test(attr: TokenStream, item: TokenStream) -> TokenStream {
    let mod_re = Regex::new(r"^mod (?P<mod_name>[^\{\s]*)(?P<to_first_bracket>[^\{]*\{)").unwrap();
    let fn_re = Regex::new(r"^fn (?P<fn_name>[^\(\s]*)(?P<to_first_bracket>[^\{]*\{)").unwrap();
    let context = item.to_string();
    if mod_re.captures(&context).is_some() {
        let attr_str = attr.to_string().replace(" ", "");
        let runtime_log_option = if attr_str.is_empty() {
            "".to_string()
        } else {
            let options = attr_str.split('=').collect::<Vec<_>>();
            match options[0].to_lowercase().as_str() {
                "log" => format!(".set_log_file({:?}.into())", options[1]),
                _ => abort_call_site!("no support option"),
            }
        };
        let template = r#"
            #[cfg(test)]
            mod $mod_name {
                use sewup::bincode;
                use sewup::runtimes::{handler::ContractHandler, test::TestRuntime};
                use std::cell::RefCell;
                use std::path::Path;
                use std::path::PathBuf;
                use std::process::Command;
                use std::sync::Arc;

                fn _build_wasm(opt: Option<String>) -> String {
                    let cargo_cmd = format!("cargo build --release --target=wasm32-unknown-unknown {}", opt.unwrap_or_default());
                    let output = Command::new("sh")
                        .arg("-c")
                        .arg(&cargo_cmd)
                        .output()
                        .expect("failed to build wasm binary");
                    if !output.status.success() {
                        panic!("return code not success: fail to build wasm binary")
                    }
                    let pkg_name = env!("CARGO_PKG_NAME");
                    let base_dir = env!("CARGO_MANIFEST_DIR");
                    let wasm_binary = format!(
                        "{}/target/wasm32-unknown-unknown/release/{}.wasm",
                        base_dir,
                        pkg_name.replace("-", "_")
                    );

                    if !Path::new(&wasm_binary).exists() {
                        panic!("wasm binary missing")
                    }
                    wasm_binary
                }

                fn _build_runtime_and_runner() -> (
                    Arc<RefCell<TestRuntime>>,
                    impl Fn(Arc<RefCell<TestRuntime>>, Option<&str>, &str, [u8; 4], Option<&[u8]>, Vec<u8>) -> (),
                ) {
                    let rt = Arc::new(RefCell::new(TestRuntime::default()"#.to_string()
                            + &runtime_log_option
                            + r#"));
                    let mut h = ContractHandler {
                        call_data: None,
                        rt: Some(rt.clone())
                    };

                    match h.run_fn(_build_wasm(Some("--features=constructor-test".to_string())), None, 1_000_000_000_000) {
                        Ok(_) => (),
                        Err(e) => {
                            panic!("vm run constructor error: {:?}", e);
                        }
                    };

                    (rt,
                        |runtime: Arc<RefCell<TestRuntime>>,
                        caller: Option<&str>,
                        fn_name: &str,
                        sig: [u8; 4],
                        input_data: Option<&[u8]>,
                        expect_output: Vec<u8>| {
                            let mut h = ContractHandler {
                                call_data: Some(_build_wasm(None)),
                                rt: Some(runtime.clone())
                            };

                            match h.execute(caller.clone(), sig, input_data, 1_000_000_000_000) {
                                Ok(r) => {
                                    if !(*r.output_data == *expect_output) {
                                        if let Some(caller) = caller {
                                            eprintln!("vm caller : {}", caller);
                                        }

                                        if let Ok(output_msg) = std::str::from_utf8(&r.output_data) {
                                            eprintln!("vm msg    : \"{}\"", output_msg);
                                        }
                                        eprintln!("vm output : {:?}", r.output_data);

                                        if let Ok(expect_msg) = std::str::from_utf8(&expect_output) {
                                            eprintln!("expected  : \"{}\"", expect_msg);
                                        }
                                        eprintln!("expected  : {:?}", expect_output);
                                        panic!("function `{}` output is unexpected", fn_name);
                                    }
                                },
                                Err(e) => {
                                    panic!("vm error: {:?}", e);
                                }
                            }
                        },
                    )
                }

                #[test]
                fn _compile_runtime_test() {
                    _build_wasm(None);
                }

                #[test]
                fn _compile_constructor_test() {
                    _build_wasm(Some("--features=constructor-test".to_string()));
                }"#;
        return mod_re
            .replace(&context, &template)
            .to_string()
            .parse()
            .unwrap();
    } else if fn_re.captures(&context).is_some() {
        let attr_str = attr.to_string().replace(" ", "");
        if !attr_str.is_empty() {
            abort_call_site!("no support option when wrapping on function")
        };
        return fn_re
            .replace(
                &context,
                r#"
            #[test]
            fn $fn_name () {
                let (_runtime, _run_wasm_fn) = _build_runtime_and_runner();
                let mut _bin: Vec<u8> = Vec::new();"#,
            )
            .to_string()
            .parse()
            .unwrap();
    } else {
        abort_call_site!("parse mod or function for testing error")
    }
}
/// helps you assert output from the handle of a contract with `Vec<u8>`.
///
/// ```compile_fail
/// #[ewasm_test]
/// mod tests {
///     use super::*;
///
///     #[ewasm_test]
///     fn test_execute_basic_operations() {
///         ewasm_assert_eq!(handler_fn(), vec![74, 111, 118, 121]);
///     }
/// }
/// ```
///
/// Besides, you can run the handler as a block chan user with `by` syntax
/// ```compile_fail
/// ewasm_assert_eq!(handler_fn() by "eD5897cCEa7aee785D31cdcA87Cf59D1D041aAFC", vec![74, 111, 118, 121]);
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_assert_eq(item: TokenStream) -> TokenStream {
    let re = Regex::new(r#"^(?P<fn_name>[^(]+?)\((?P<params>[^)]*?)\)\s*(by)?\s*(?P<caller>"[^"]*")?\s*,(?P<equivalence>.*)"#).unwrap();
    if let Some(cap) = re.captures(&item.to_string().replace("\n", "")) {
        let fn_name = cap.name("fn_name").unwrap().as_str().replace(" ", "");
        let params = cap.name("params").unwrap().as_str().replace(" ", "");
        let equivalence = cap.name("equivalence").unwrap().as_str();
        let caller = cap
            .name("caller")
            .map(|c| format!("Some({})", c.as_str()))
            .unwrap_or_else(|| "None".to_string());
        if params.is_empty() {
            format!(
                r#"_run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), None, {});"#,
                caller, fn_name, fn_name, equivalence
            )
            .parse()
            .unwrap()
        } else {
            format!(
                r#"_bin = bincode::serialize(&{}).unwrap();
                   _run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), Some(&_bin), {});"#,
                params, caller, fn_name, fn_name, equivalence
            )
            .parse()
            .unwrap()
        }
    } else {
        abort_call_site!("fail to parsing function in ewasm_assert_eq");
    }
}

/// helps you assert return instance from your handler with auto unwrap ewasm_main, namely `#[ewasm_main(auto)]`
///
/// This usage of the macro likes `ewasm_assert_eq`, but the contract main function should be
/// decorated with `#[ewasm_main(auto)]`, and the equivalence arm will be serialized into `Vec<u8>`
/// Besides, you can run the handler as a block chan user with `by` syntax as the same usage of `ewasm_assert_eq`.
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_auto_assert_eq(item: TokenStream) -> TokenStream {
    let re = Regex::new(r#"^(?P<fn_name>[^(]+?)\((?P<params>[^)]*?)\)\s*(by)?\s*(?P<caller>"[^"]*")?\s*,(?P<equivalence>.*)"#).unwrap();
    if let Some(cap) = re.captures(&item.to_string().replace("\n", "")) {
        let fn_name = cap.name("fn_name").unwrap().as_str();
        let params = cap.name("params").unwrap().as_str().replace(" ", "");
        let equivalence = cap.name("equivalence").unwrap().as_str();
        let caller = cap
            .name("caller")
            .map(|c| format!("Some({})", c.as_str()))
            .unwrap_or_else(|| "None".to_string());
        if params.is_empty() {
            format!(
                r#"_run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), None, sewup_derive::ewasm_output_from!({}));"#,
                caller, fn_name, fn_name, equivalence
            )
            .parse()
            .unwrap()
        } else {
            format!(
                r#"_bin = bincode::serialize(&{}).unwrap();
                   _run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), Some(&_bin), sewup_derive::ewasm_output_from!({}));"#,
                params, caller, fn_name, fn_name, equivalence
            )
            .parse()
            .unwrap()
        }
    } else {
        abort_call_site!("fail to parsing function in fn_select");
    }
}

/// helps you assert your handler without error and returns
///
/// ```compile_fail
/// #[ewasm_test]
/// mod tests {
///     use super::*;
///
///     #[ewasm_test]
///     fn test_execute_basic_operations() {
///         ewasm_assert_ok!(contract_fn());
///     }
/// }
/// ```
///
/// Besides, you can run the handler as a block chan user with `by` syntax.
/// ```compile_fail
/// ewasm_assert_ok!(contract_fn() by "eD5897cCEa7aee785D31cdcA87Cf59D1D041aAFC");
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_assert_ok(item: TokenStream) -> TokenStream {
    let re = Regex::new(
        r#"^(?P<fn_name>[^(]+?)\((?P<params>[^)]*?)\)\s*(by)?\s*(?P<caller>"[^"]*")?\s*"#,
    )
    .unwrap();
    if let Some(cap) = re.captures(&item.to_string().replace("\n", "")) {
        let fn_name = cap.name("fn_name").unwrap().as_str();
        let params = cap.name("params").unwrap().as_str().replace(" ", "");
        let caller = cap
            .name("caller")
            .map(|c| format!("Some({})", c.as_str()))
            .unwrap_or_else(|| "None".to_string());
        if params.is_empty() {
            format!(
                r#"_run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), None, Vec::with_capacity(0));"#,
                caller, fn_name, fn_name
            )
            .parse()
            .unwrap()
        } else {
            format!(
                r#"_bin = bincode::serialize(&{}).unwrap();
                   _run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), Some(&_bin), Vec::with_capacity(0));"#,
                params, caller, fn_name, fn_name
            )
            .parse()
            .unwrap()
        }
    } else {
        abort_call_site!("fail to parsing function in fn_select");
    }
}

/// helps you assert return Ok(()) your handler with rusty ewasm_main, namely `#[ewasm_main(rusty)]`
///
/// This usage of the macro likes `ewasm_assert_ok`, this only difference is that the contract main
/// function should be decorated with `#[ewasm_main(rusty)]`.
/// Besides, you can run the handler as a block chan user with `by` syntax as the same usage of `ewasm_assert_ok`.
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_rusty_assert_ok(item: TokenStream) -> TokenStream {
    let re = Regex::new(
        r#"^(?P<fn_name>[^(]+?)\((?P<params>[^)]*?)\)\s*(by)?\s*(?P<caller>"[^"]*")?\s*"#,
    )
    .unwrap();
    if let Some(cap) = re.captures(&item.to_string().replace("\n", "")) {
        let fn_name = cap.name("fn_name").unwrap().as_str();
        let params = cap.name("params").unwrap().as_str().replace(" ", "");
        let caller = cap
            .name("caller")
            .map(|c| format!("Some({})", c.as_str()))
            .unwrap_or_else(|| "None".to_string());
        if params.is_empty() {
            format!(
                r#"_run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), None, vec![0, 0, 0, 0]);"#,
                caller, fn_name, fn_name
            )
            .parse()
            .unwrap()
        } else {
            format!(
                r#"_bin = bincode::serialize(&{}).unwrap();
                   _run_wasm_fn( _runtime.clone(), {}, "{}", ewasm_fn_sig!({}), Some(&_bin), vec![0, 0, 0, 0]);"#,
                params, caller, fn_name, fn_name
            )
            .parse()
            .unwrap()
        }
    } else {
        abort_call_site!("fail to parsing function in fn_select");
    }
}

/// helps you assert return Err your handler with rusty ewasm_main, namely `#[ewasm_main(rusty)]`
///
/// This usage of the macro likes `ewasm_err_output`, the contract main function should be
/// decorated with `#[ewasm_main(rusty)]`.
///
/// You should pass the complete Result type, as the following example
/// `ewasm_rusty_err_output!(Err("NotTrustedInput") as Result<(), &'static str>)`
/// such that you can easy to use any kind of rust error as you like.
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_rusty_err_output(item: TokenStream) -> TokenStream {
    format!(
        r#"bincode::serialize(&({})).expect("can not serialize the output expected from ewasm").to_vec()"#,
        &item.to_string()
    )
    .parse()
    .unwrap()
}

/// helps you to get the binary result of the thiserror,
///
/// such that you can assert your handler with error.
/// for example:
/// ```compile_fail
/// #[ewasm_test]
/// mod tests {
///    use super::*;
///
///    #[ewasm_test]
///    fn test_execute_basic_operations() {
///        let mut simple_struct = SimpleStruct::default();
///
///        ewasm_assert_eq!(
///            check_input_object(simple_struct),
///            ewasm_err_output!(Error::NotTrustedInput)
///        );
///    }
///}
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn ewasm_err_output(item: TokenStream) -> TokenStream {
    format!("{}.to_string().as_bytes().to_vec()", &item.to_string())
        .parse()
        .unwrap()
}

/// help you write the field which storage string no longer than the specific size
///```compile_fail
///#[derive(Table)]
///pub struct Blog {
///     pub content: SizedString!(50),
///}
///```
#[allow(non_snake_case)]
#[proc_macro_error]
#[proc_macro]
pub fn SizedString(item: TokenStream) -> TokenStream {
    let num = item.to_string();

    if let Ok(num) = num.trim().parse::<usize>() {
        if num > 0 {
            let raw_size = num / 32usize + 1;
            return format!("[sewup::types::Raw; {}]", raw_size)
                .parse()
                .unwrap();
        }
    }
    panic!("The input of SizedString! should be a greator than zero integer")
}

/// helps you return handler when caller is not in access control list
/// ```compile_fail
/// ewasm_call_only_by!("8663..1993")
/// ```
#[proc_macro]
pub fn ewasm_call_only_by(item: TokenStream) -> TokenStream {
    let input = item.to_string().replace(" ", "");
    let output = if input.starts_with('"') {
        let addr = input.replace("\"", "");
        quote! {
            if sewup::utils::caller() != sewup::types::Address::from_str(#addr)? {
                return Err(sewup::errors::HandlerError::Unauthorized.into())
            }
        }
    } else {
        let addr = Ident::new(&input, Span::call_site());
        quote! {
            if sewup::utils::caller() != sewup::types::Address::from_str(#addr)? {
                return Err(sewup::errors::HandlerError::Unauthorized.into())
            }
        }
    };

    output.into()
}