mod.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. use serde::{Deserialize, Serialize};
  2. use serde_json::Value as JsonValue;
  3. pub mod file;
  4. pub mod pda;
  5. pub mod relations;
  6. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  7. pub struct Idl {
  8. pub version: String,
  9. pub name: String,
  10. #[serde(skip_serializing_if = "Option::is_none", default)]
  11. pub docs: Option<Vec<String>>,
  12. #[serde(skip_serializing_if = "Vec::is_empty", default)]
  13. pub constants: Vec<IdlConst>,
  14. pub instructions: Vec<IdlInstruction>,
  15. #[serde(skip_serializing_if = "Vec::is_empty", default)]
  16. pub accounts: Vec<IdlTypeDefinition>,
  17. #[serde(skip_serializing_if = "Vec::is_empty", default)]
  18. pub types: Vec<IdlTypeDefinition>,
  19. #[serde(skip_serializing_if = "Option::is_none", default)]
  20. pub events: Option<Vec<IdlEvent>>,
  21. #[serde(skip_serializing_if = "Option::is_none", default)]
  22. pub errors: Option<Vec<IdlErrorCode>>,
  23. #[serde(skip_serializing_if = "Option::is_none", default)]
  24. pub metadata: Option<JsonValue>,
  25. }
  26. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  27. pub struct IdlConst {
  28. pub name: String,
  29. #[serde(rename = "type")]
  30. pub ty: IdlType,
  31. pub value: String,
  32. }
  33. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  34. pub struct IdlState {
  35. #[serde(rename = "struct")]
  36. pub strct: IdlTypeDefinition,
  37. pub methods: Vec<IdlInstruction>,
  38. }
  39. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  40. pub struct IdlInstruction {
  41. pub name: String,
  42. #[serde(skip_serializing_if = "Option::is_none")]
  43. pub docs: Option<Vec<String>>,
  44. pub accounts: Vec<IdlAccountItem>,
  45. pub args: Vec<IdlField>,
  46. #[serde(skip_serializing_if = "Option::is_none")]
  47. pub returns: Option<IdlType>,
  48. }
  49. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  50. #[serde(rename_all = "camelCase")]
  51. pub struct IdlAccounts {
  52. pub name: String,
  53. pub accounts: Vec<IdlAccountItem>,
  54. }
  55. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  56. #[serde(untagged)]
  57. pub enum IdlAccountItem {
  58. IdlAccount(IdlAccount),
  59. IdlAccounts(IdlAccounts),
  60. }
  61. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  62. #[serde(rename_all = "camelCase")]
  63. pub struct IdlAccount {
  64. pub name: String,
  65. pub is_mut: bool,
  66. pub is_signer: bool,
  67. #[serde(skip_serializing_if = "Option::is_none")]
  68. pub is_optional: Option<bool>,
  69. #[serde(skip_serializing_if = "Option::is_none")]
  70. pub docs: Option<Vec<String>>,
  71. #[serde(skip_serializing_if = "Option::is_none", default)]
  72. pub pda: Option<IdlPda>,
  73. #[serde(skip_serializing_if = "Vec::is_empty", default)]
  74. pub relations: Vec<String>,
  75. }
  76. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  77. #[serde(rename_all = "camelCase")]
  78. pub struct IdlPda {
  79. pub seeds: Vec<IdlSeed>,
  80. #[serde(skip_serializing_if = "Option::is_none", default)]
  81. pub program_id: Option<IdlSeed>,
  82. }
  83. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  84. #[serde(rename_all = "camelCase", tag = "kind")]
  85. pub enum IdlSeed {
  86. Const(IdlSeedConst),
  87. Arg(IdlSeedArg),
  88. Account(IdlSeedAccount),
  89. }
  90. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  91. #[serde(rename_all = "camelCase")]
  92. pub struct IdlSeedAccount {
  93. #[serde(rename = "type")]
  94. pub ty: IdlType,
  95. // account_ty points to the entry in the "accounts" section.
  96. // Some only if the `Account<T>` type is used.
  97. #[serde(skip_serializing_if = "Option::is_none")]
  98. pub account: Option<String>,
  99. pub path: String,
  100. }
  101. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  102. #[serde(rename_all = "camelCase")]
  103. pub struct IdlSeedArg {
  104. #[serde(rename = "type")]
  105. pub ty: IdlType,
  106. pub path: String,
  107. }
  108. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  109. #[serde(rename_all = "camelCase")]
  110. pub struct IdlSeedConst {
  111. #[serde(rename = "type")]
  112. pub ty: IdlType,
  113. pub value: serde_json::Value,
  114. }
  115. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  116. pub struct IdlField {
  117. pub name: String,
  118. #[serde(skip_serializing_if = "Option::is_none")]
  119. pub docs: Option<Vec<String>>,
  120. #[serde(rename = "type")]
  121. pub ty: IdlType,
  122. }
  123. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  124. pub struct IdlEvent {
  125. pub name: String,
  126. pub fields: Vec<IdlEventField>,
  127. }
  128. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  129. pub struct IdlEventField {
  130. pub name: String,
  131. #[serde(rename = "type")]
  132. pub ty: IdlType,
  133. pub index: bool,
  134. }
  135. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  136. pub struct IdlTypeDefinition {
  137. pub name: String,
  138. #[serde(skip_serializing_if = "Option::is_none")]
  139. pub docs: Option<Vec<String>>,
  140. #[serde(rename = "type")]
  141. pub ty: IdlTypeDefinitionTy,
  142. }
  143. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  144. #[serde(rename_all = "lowercase", tag = "kind")]
  145. pub enum IdlTypeDefinitionTy {
  146. Struct { fields: Vec<IdlField> },
  147. Enum { variants: Vec<IdlEnumVariant> },
  148. }
  149. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  150. pub struct IdlEnumVariant {
  151. pub name: String,
  152. #[serde(skip_serializing_if = "Option::is_none", default)]
  153. pub fields: Option<EnumFields>,
  154. }
  155. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  156. #[serde(untagged)]
  157. pub enum EnumFields {
  158. Named(Vec<IdlField>),
  159. Tuple(Vec<IdlType>),
  160. }
  161. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  162. #[serde(rename_all = "camelCase")]
  163. pub enum IdlType {
  164. Bool,
  165. U8,
  166. I8,
  167. U16,
  168. I16,
  169. U32,
  170. I32,
  171. F32,
  172. U64,
  173. I64,
  174. F64,
  175. U128,
  176. I128,
  177. U256,
  178. I256,
  179. Bytes,
  180. String,
  181. PublicKey,
  182. Defined(String),
  183. Option(Box<IdlType>),
  184. Vec(Box<IdlType>),
  185. Array(Box<IdlType>, usize),
  186. }
  187. impl std::str::FromStr for IdlType {
  188. type Err = anyhow::Error;
  189. fn from_str(s: &str) -> Result<Self, Self::Err> {
  190. let mut s = s.to_string();
  191. fn array_from_str(inner: &str) -> IdlType {
  192. match inner.strip_suffix(']') {
  193. None => {
  194. let (raw_type, raw_length) = inner.rsplit_once(';').unwrap();
  195. let ty = IdlType::from_str(raw_type).unwrap();
  196. let len = raw_length.replace('_', "").parse::<usize>().unwrap();
  197. IdlType::Array(Box::new(ty), len)
  198. }
  199. Some(nested_inner) => array_from_str(&nested_inner[1..]),
  200. }
  201. }
  202. s.retain(|c| !c.is_whitespace());
  203. let r = match s.as_str() {
  204. "bool" => IdlType::Bool,
  205. "u8" => IdlType::U8,
  206. "i8" => IdlType::I8,
  207. "u16" => IdlType::U16,
  208. "i16" => IdlType::I16,
  209. "u32" => IdlType::U32,
  210. "i32" => IdlType::I32,
  211. "f32" => IdlType::F32,
  212. "u64" => IdlType::U64,
  213. "i64" => IdlType::I64,
  214. "f64" => IdlType::F64,
  215. "u128" => IdlType::U128,
  216. "i128" => IdlType::I128,
  217. "u256" => IdlType::U256,
  218. "i256" => IdlType::I256,
  219. "Vec<u8>" => IdlType::Bytes,
  220. "String" | "&str" | "&'staticstr" => IdlType::String,
  221. "Pubkey" => IdlType::PublicKey,
  222. _ => match s.to_string().strip_prefix("Option<") {
  223. None => match s.to_string().strip_prefix("Vec<") {
  224. None => {
  225. if s.to_string().starts_with('[') {
  226. array_from_str(&s)
  227. } else {
  228. IdlType::Defined(s.to_string())
  229. }
  230. }
  231. Some(inner) => {
  232. let inner_ty = Self::from_str(
  233. inner
  234. .strip_suffix('>')
  235. .ok_or_else(|| anyhow::anyhow!("Invalid option"))?,
  236. )?;
  237. IdlType::Vec(Box::new(inner_ty))
  238. }
  239. },
  240. Some(inner) => {
  241. let inner_ty = Self::from_str(
  242. inner
  243. .strip_suffix('>')
  244. .ok_or_else(|| anyhow::anyhow!("Invalid option"))?,
  245. )?;
  246. IdlType::Option(Box::new(inner_ty))
  247. }
  248. },
  249. };
  250. Ok(r)
  251. }
  252. }
  253. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
  254. pub struct IdlErrorCode {
  255. pub code: u32,
  256. pub name: String,
  257. #[serde(skip_serializing_if = "Option::is_none", default)]
  258. pub msg: Option<String>,
  259. }
  260. #[cfg(test)]
  261. mod tests {
  262. use crate::idl::IdlType;
  263. use std::str::FromStr;
  264. #[test]
  265. fn multidimensional_array() {
  266. assert_eq!(
  267. IdlType::from_str("[[u8;16];32]").unwrap(),
  268. IdlType::Array(Box::new(IdlType::Array(Box::new(IdlType::U8), 16)), 32)
  269. );
  270. }
  271. #[test]
  272. fn array() {
  273. assert_eq!(
  274. IdlType::from_str("[Pubkey;16]").unwrap(),
  275. IdlType::Array(Box::new(IdlType::PublicKey), 16)
  276. );
  277. }
  278. #[test]
  279. fn array_with_underscored_length() {
  280. assert_eq!(
  281. IdlType::from_str("[u8;50_000]").unwrap(),
  282. IdlType::Array(Box::new(IdlType::U8), 50000)
  283. );
  284. }
  285. #[test]
  286. fn option() {
  287. assert_eq!(
  288. IdlType::from_str("Option<bool>").unwrap(),
  289. IdlType::Option(Box::new(IdlType::Bool))
  290. )
  291. }
  292. #[test]
  293. fn vector() {
  294. assert_eq!(
  295. IdlType::from_str("Vec<bool>").unwrap(),
  296. IdlType::Vec(Box::new(IdlType::Bool))
  297. )
  298. }
  299. }