rpc_contracts.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::str::FromStr;
  19. use log::error;
  20. use tinyjson::JsonValue;
  21. use darkfi::rpc::jsonrpc::{
  22. ErrorCode::{InternalError, InvalidParams},
  23. JsonError, JsonResponse, JsonResult,
  24. };
  25. use darkfi_sdk::crypto::ContractId;
  26. use crate::Explorerd;
  27. impl Explorerd {
  28. // RPCAPI:
  29. // Retrieves the native contracts deployed in the DarkFi network.
  30. // Returns a JSON array containing Contract IDs along with their associated metadata upon success.
  31. //
  32. // **Params:**
  33. // * `None`
  34. //
  35. // **Returns:**
  36. // * Array of `ContractRecord`s encoded into a JSON.
  37. //
  38. // --> {"jsonrpc": "2.0", "method": "contracts.get_native_contracts", "params": ["5cc...2f9"], "id": 1}
  39. // <-- {"jsonrpc": "2.0", "result": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o", "Money Contract", "The money contract..."], "id": 1}
  40. pub async fn contracts_get_native_contracts(&self, id: u16, params: JsonValue) -> JsonResult {
  41. // Ensure that the parameters are empty
  42. let params = params.get::<Vec<JsonValue>>().unwrap();
  43. if !params.is_empty() {
  44. return JsonError::new(InvalidParams, None, id).into()
  45. }
  46. // Retrieve native contracts and handle potential errors
  47. let contract_records = match self.service.get_native_contracts() {
  48. Ok(v) => v,
  49. Err(e) => {
  50. error!(target: "explorerd::rpc_contracts::contracts_get_native_contracts", "Failed fetching native contracts: {}", e);
  51. return JsonError::new(InternalError, None, id).into()
  52. }
  53. };
  54. // Transform contract records into a JSON array and return the result
  55. if contract_records.is_empty() {
  56. JsonResponse::new(JsonValue::Array(vec![]), id).into()
  57. } else {
  58. let json_blocks: Vec<JsonValue> = contract_records
  59. .into_iter()
  60. .map(|contract_record| contract_record.to_json_array())
  61. .collect();
  62. JsonResponse::new(JsonValue::Array(json_blocks), id).into()
  63. }
  64. }
  65. // RPCAPI:
  66. // Retrieves the source code paths for the contract associated with the specified Contract ID.
  67. // Returns a JSON array containing the source code paths upon success.
  68. //
  69. // **Params:**
  70. // * `array[0]`: `String` Contract ID
  71. //
  72. // **Returns:**
  73. // * `JsonArray` containing source code paths for the specified Contract ID.
  74. //
  75. // Example Call:
  76. // --> {"jsonrpc": "2.0", "method": "contracts.get_contract_source_code_paths", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o"], "id": 1}
  77. // <-- {"jsonrpc": "2.0", "result": ["path/to/source1.rs", "path/to/source2.rs"], "id": 1}
  78. pub async fn contracts_get_contract_source_code_paths(
  79. &self,
  80. id: u16,
  81. params: JsonValue,
  82. ) -> JsonResult {
  83. // Validate that a single required parameter is provided and is of type String
  84. let params = params.get::<Vec<JsonValue>>().unwrap();
  85. if params.len() != 1 || !params[0].is_string() {
  86. return JsonError::new(InvalidParams, None, id).into()
  87. }
  88. // Validate the provided contract ID and convert it into a ContractId object
  89. let contact_id_str = params[0].get::<String>().unwrap();
  90. let contract_id = match ContractId::from_str(contact_id_str) {
  91. Ok(contract_id) => contract_id,
  92. Err(e) => return JsonError::new(InternalError, Some(e.to_string()), id).into(),
  93. };
  94. // Retrieve source code paths for the contract, transform them into a JsonResponse, and return the result
  95. match self.service.get_contract_source_paths(&contract_id) {
  96. Ok(paths) => {
  97. let transformed_paths =
  98. paths.iter().map(|path| JsonValue::String(path.clone())).collect();
  99. JsonResponse::new(JsonValue::Array(transformed_paths), id).into()
  100. }
  101. Err(e) => {
  102. error!(
  103. target: "explorerd::rpc_contracts::contracts_get_contract_source_code_paths",
  104. "Failed fetching contract source code paths: {e:?}");
  105. JsonError::new(InternalError, None, id).into()
  106. }
  107. }
  108. }
  109. // RPCAPI:
  110. // Retrieves contract source code content using the provided Contract ID and source path.
  111. // Returns the source code content as a JSON string upon success.
  112. //
  113. // **Params:**
  114. // * `array[0]`: `String` Contract ID
  115. // * `array[1]`: `String` Source path
  116. //
  117. // **Returns:**
  118. // * `String` containing the content of the contract source file.
  119. //
  120. // Example Call:
  121. // --> {"jsonrpc": "2.0", "method": "contracts.get_contract_source", "params": ["BZHKGQ26bzmBithTQYTJtjo2QdCqpkR9tjSBopT4yf4o", "client/lib.rs"], "id": 1}
  122. // <-- {"jsonrpc": "2.0", "result": "/* This file is ...", "id": 1}
  123. pub async fn contracts_get_contract_source(&self, id: u16, params: JsonValue) -> JsonResult {
  124. // Validate that the required parameters are provided
  125. let params = params.get::<Vec<JsonValue>>().unwrap();
  126. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  127. return JsonError::new(InvalidParams, None, id).into()
  128. }
  129. // Validate and extract the provided Contract ID
  130. let contact_id_str = params[0].get::<String>().unwrap();
  131. let contract_id = match ContractId::from_str(contact_id_str) {
  132. Ok(contract_id) => contract_id,
  133. Err(e) => return JsonError::new(InternalError, Some(e.to_string()), id).into(),
  134. };
  135. // Extract the provided source path
  136. let source_path = params[1].get::<String>().unwrap();
  137. // Retrieve the contract source code, transform it into a JsonResponse, and return the result
  138. match self.service.get_contract_source_content(&contract_id, source_path) {
  139. Ok(Some(source_file)) => JsonResponse::new(JsonValue::String(source_file), id).into(),
  140. Ok(None) => {
  141. let empty_value =
  142. JsonValue::from(std::collections::HashMap::<String, JsonValue>::new());
  143. JsonResponse::new(empty_value, id).into()
  144. }
  145. Err(e) => {
  146. error!(
  147. target: "explorerd::rpc_contracts::contracts_get_contract_source",
  148. "Failed fetching contract source code: {}", e
  149. );
  150. JsonError::new(InternalError, None, id).into()
  151. }
  152. }
  153. }
  154. }