use crate::address::Address;
use crate::api::node_provider::{CallContractParams, CallContractResult, CompileResult, NodeProvider};
use crate::error::{Error, Result};
use crate::transaction::UnsignedTransaction;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct Contract {
pub address: Address,
pub code_hash: String,
pub bytecode: String,
}
impl Contract {
pub fn new(address: Address, code_hash: String, bytecode: String) -> Self {
Self {
address,
code_hash,
bytecode,
}
}
pub fn at(address: Address) -> Self {
Self {
address,
code_hash: String::new(),
bytecode: String::new(),
}
}
pub async fn call_method(
&self,
node_provider: &NodeProvider,
method_index: u32,
args: Option<Vec<serde_json::Value>>,
) -> Result<CallContractResult> {
let group = self.address.group_index().unwrap_or(0);
let params = CallContractParams {
group,
address: self.address.to_base58(),
method_index,
args,
};
node_provider.call_contract(params).await
}
}
#[derive(Debug, Clone)]
pub struct ContractFactory {
pub bytecode: String,
pub initial_fields: HashMap<String, ContractField>,
}
impl ContractFactory {
pub fn new(bytecode: String) -> Self {
Self {
bytecode,
initial_fields: HashMap::new(),
}
}
pub fn set_field(mut self, name: String, value: ContractField) -> Self {
self.initial_fields.insert(name, value);
self
}
pub async fn build_deploy_tx(
&self,
node_provider: &NodeProvider,
_from_public_key: String,
_initial_alph_amount: String,
) -> Result<UnsignedTransaction> {
let _url = format!("{}/contracts/unsigned-tx/deploy-contract", node_provider.base_url);
let _body = serde_json::json!({
"fromPublicKey": _from_public_key,
"bytecode": self.bytecode,
"initialAttoAlphAmount": _initial_alph_amount,
"initialFields": self.serialize_fields()?,
});
Err(Error::ApiError(
"Deploy contract not fully implemented".to_string(),
))
}
fn serialize_fields(&self) -> Result<Vec<serde_json::Value>> {
let mut fields = Vec::new();
for (_, field) in &self.initial_fields {
fields.push(field.to_json());
}
Ok(fields)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum ContractField {
Bool(bool),
U256(String),
I256(String),
Address(String),
ByteVec(String),
Array(Vec<ContractField>),
}
impl ContractField {
fn to_json(&self) -> serde_json::Value {
match self {
ContractField::Bool(b) => serde_json::json!({ "type": "Bool", "value": b }),
ContractField::U256(s) => serde_json::json!({ "type": "U256", "value": s }),
ContractField::I256(s) => serde_json::json!({ "type": "I256", "value": s }),
ContractField::Address(s) => serde_json::json!({ "type": "Address", "value": s }),
ContractField::ByteVec(s) => serde_json::json!({ "type": "ByteVec", "value": s }),
ContractField::Array(arr) => {
let values: Vec<_> = arr.iter().map(|f| f.to_json()).collect();
serde_json::json!({ "type": "Array", "value": values })
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractEvent {
#[serde(rename = "blockHash")]
pub block_hash: String,
#[serde(rename = "txId")]
pub tx_id: String,
#[serde(rename = "contractAddress")]
pub contract_address: String,
#[serde(rename = "eventIndex")]
pub event_index: i32,
pub fields: Vec<EventField>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventField {
#[serde(rename = "type")]
pub field_type: String,
pub value: serde_json::Value,
}
#[derive(Debug, Clone)]
pub struct Script {
pub bytecode: String,
}
impl Script {
pub fn new(bytecode: String) -> Self {
Self { bytecode }
}
pub async fn compile(node_provider: &NodeProvider, code: &str) -> Result<Self> {
let result = node_provider.compile_script(code).await?;
Ok(Self {
bytecode: result.bytecode,
})
}
pub async fn build_execute_tx(
&self,
_from_public_key: String,
_atto_alph_amount: Option<String>,
) -> Result<UnsignedTransaction> {
Err(Error::ApiError(
"Execute script not fully implemented".to_string(),
))
}
}
pub struct ContractCompiler;
impl ContractCompiler {
pub async fn compile_contract(
node_provider: &NodeProvider,
source_code: &str,
) -> Result<CompileResult> {
node_provider.compile_contract(source_code).await
}
pub async fn compile_script(
node_provider: &NodeProvider,
source_code: &str,
) -> Result<CompileResult> {
node_provider.compile_script(source_code).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_contract_field_serialization() {
let field = ContractField::Bool(true);
let json = field.to_json();
assert_eq!(json["type"], "Bool");
assert_eq!(json["value"], true);
}
#[test]
fn test_contract_field_u256() {
let field = ContractField::U256("1000000000000000000".to_string());
let json = field.to_json();
assert_eq!(json["type"], "U256");
assert_eq!(json["value"], "1000000000000000000");
}
#[test]
fn test_contract_field_address() {
let field =
ContractField::Address("1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string());
let json = field.to_json();
assert_eq!(json["type"], "Address");
}
#[test]
fn test_contract_field_array() {
let field = ContractField::Array(vec![
ContractField::Bool(true),
ContractField::Bool(false),
]);
let json = field.to_json();
assert_eq!(json["type"], "Array");
}
}