From ad9c88b6c58f31570b2ae8fb64e3b90982a65697 Mon Sep 17 00:00:00 2001 From: yp945 Date: Thu, 25 Jan 2024 14:51:57 +0800 Subject: [PATCH] add function output decode. --- package-lock.json | 13 +++++++++++++ src/abi.rs | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 package-lock.json diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..8097a1f --- /dev/null +++ b/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "ola-lang-abi", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ola-lang-abi", + "version": "1.0.0", + "license": "MIT" + } + } +} diff --git a/src/abi.rs b/src/abi.rs index 7fa3bf1..7801bbb 100644 --- a/src/abi.rs +++ b/src/abi.rs @@ -43,6 +43,24 @@ impl Abi { Ok((f, decoded_params)) } + // Decode function input from slice. + pub fn decode_output_from_slice<'a>( + &'a self, + output: &[u64], + ) -> Result<(&'a Function, DecodedParams)> { + let f = self + .functions + .iter() + .find(|f| f.method_id() == output[output.len()-1]) + .ok_or_else(|| anyhow!("ABI function not found"))?; + + // output = [param1, param2, .. , param-len, method_id,] + + let decoded_params = f.decode_input_from_slice(&output[0..output.len()-2])?; + + Ok((f, decoded_params)) + } + pub fn encode_input_with_signature( &self, signature: &str, @@ -61,7 +79,7 @@ impl Abi { Ok(params) } - pub fn encode_input_values(&self, params: &[Value]) -> Result> { + pub fn encode_values(&self, params: &[Value]) -> Result> { let mut params = Value::encode(params); params.push(params.len() as u64); @@ -150,6 +168,23 @@ impl Function { .collect::>(), )) } + + // Decode function output from slice. + pub fn decode_output_from_slice(&self, output: &[u64]) -> Result { + let ouputs_types = self + .outputs + .iter() + .map(|f_output| f_output.type_.clone()) + .collect::>(); + + Ok(DecodedParams::from( + self.outputs + .iter() + .cloned() + .zip(Value::decode_from_slice(output, &ouputs_types)?) + .collect::>(), + )) + } } #[derive(Debug, Serialize, Deserialize)]