Skip to content

Commit

Permalink
feat(jstz_proto): migrate to new account
Browse files Browse the repository at this point in the history
  • Loading branch information
ryutamago committed Jan 20, 2025
1 parent 4fb8290 commit 3f36e33
Show file tree
Hide file tree
Showing 21 changed files with 136 additions and 379 deletions.
9 changes: 9 additions & 0 deletions crates/jstz_cli/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,9 @@ pub enum Command {
// // TODO: https://linear.app/tezos/issue/JSTZ-260/add-validation-check-for-address-type
fn parse_smart_function_address(s: &str) -> Result<NewAddress> {
let address = NewAddress::from_str(s).map_err(|e| user_error!("{}", e))?;
if !matches!(address, NewAddress::SmartFunction(_)) {
bail_user_error!("Invalid smart function address: {}", s);
}
Ok(address)
}

Expand All @@ -369,4 +372,10 @@ mod tests {
parse_smart_function_address("KT1TxqZ8QtKvLu3V3JH7Gx58n7Co8pgtpQU5").unwrap();
assert!(matches!(address, NewAddress::SmartFunction(_)));
}

#[test]
fn test_parse_user_address() {
let address = parse_smart_function_address("tz1VJk1a4Y4FdZyFtsm6zL2k9KjYtS5tYF9");
assert!(address.is_err());
}
}
2 changes: 1 addition & 1 deletion crates/jstz_cli/src/deploy.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use boa_engine::JsError;
use jstz_crypto::public_key_hash::PublicKeyHash;
use jstz_proto::{
context::{account::ParsedCode, new_account::NewAddress},
context::{new_account::NewAddress, new_account::ParsedCode},
operation::{Content, DeployFunction, Operation, SignedOperation},
receipt::{ReceiptContent, ReceiptResult},
};
Expand Down
2 changes: 1 addition & 1 deletion crates/jstz_cli/src/jstz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::time::Duration;
use anyhow::{bail, Result};
use jstz_proto::{
api::KvValue,
context::{account::Nonce, new_account::NewAddress},
context::{new_account::NewAddress, new_account::Nonce},
operation::{OperationHash, SignedOperation},
receipt::Receipt,
};
Expand Down
6 changes: 3 additions & 3 deletions crates/jstz_cli/src/repl/debug_api/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use boa_engine::{
JsResult, JsValue, NativeFunction,
};
use jstz_core::runtime;
use jstz_proto::context::{account::Account, new_account::NewAddress};
use jstz_proto::context::{new_account::Account, new_account::NewAddress};

fn try_parse_address(account: &str) -> JsResult<NewAddress> {
NewAddress::from_base58(account).map_err(|_| {
Expand Down Expand Up @@ -62,8 +62,8 @@ impl AccountApi {

runtime::with_js_hrt_and_tx(|hrt, tx| -> JsResult<JsValue> {
match Account::function_code(hrt.deref(), tx, &address)? {
Some(value) => Ok(JsValue::String(value.to_string().into())),
None => Ok(JsValue::null()),
"" => Ok(JsValue::null()),
value => Ok(JsValue::String(value.to_string().into())),
}
})
}
Expand Down
10 changes: 6 additions & 4 deletions crates/jstz_kernel/src/inbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ pub fn read_message(
#[cfg(test)]
mod test {
use jstz_crypto::hash::Hash;
use jstz_crypto::public_key_hash::PublicKeyHash;
use jstz_crypto::smart_function_hash::SmartFunctionHash;
use jstz_mock::message::native_deposit::MockNativeDeposit;
use jstz_mock::{host::JstzMockHost, message::fa_deposit::MockFaDeposit};
use jstz_proto::context::new_account::NewAddress;
Expand Down Expand Up @@ -294,11 +294,13 @@ mod test {
assert_eq!(300, amount);
assert_eq!(fa_deposit.receiver.to_b58check(), receiver.to_base58());
assert_eq!(
Some(PublicKeyHash::from_base58(jstz_mock::host::MOCK_PROXY).unwrap()),
Some(
SmartFunctionHash::from_base58(jstz_mock::host::MOCK_PROXY).unwrap()
),
proxy_smart_function.map(|p| {
match p {
NewAddress::User(pkh) => pkh,
NewAddress::SmartFunction(_) => panic!("Unexpected proxy"),
NewAddress::User(_) => panic!("Unexpected proxy"),
NewAddress::SmartFunction(sfh) => sfh,
}
})
);
Expand Down
12 changes: 5 additions & 7 deletions crates/jstz_kernel/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ mod test {
message::{fa_deposit::MockFaDeposit, native_deposit::MockNativeDeposit},
};
use jstz_proto::context::{
account::{Account, ParsedCode},
new_account::NewAddress,
new_account::{Account, ParsedCode},
ticket_table::TicketTable,
};
use tezos_smart_rollup::types::{Contract, PublicKeyHash};
Expand Down Expand Up @@ -128,11 +128,9 @@ mod test {
.unwrap();
tx.commit(host.rt()).unwrap();

// TODO: use sf address
// https://linear.app/tezos/issue/JSTZ-260/add-validation-check-for-address-type
let proxy = match proxy {
NewAddress::User(pkh) => pkh,
NewAddress::SmartFunction(_) => panic!("Unexpected proxy"),
NewAddress::User(_) => panic!("proxy is not a user address"),
NewAddress::SmartFunction(sfh) => sfh,
};

let deposit = MockFaDeposit {
Expand All @@ -149,7 +147,7 @@ mod test {
let proxy_balance = TicketTable::get_balance(
host.rt(),
tx,
&NewAddress::User(proxy),
&NewAddress::SmartFunction(proxy),
&ticket_hash,
)
.unwrap();
Expand Down Expand Up @@ -180,7 +178,7 @@ mod test {
let proxy_balance = TicketTable::get_balance(
host.rt(),
&mut tx,
&NewAddress::User(proxy),
&NewAddress::SmartFunction(proxy),
&ticket_hash,
)
.unwrap();
Expand Down
2 changes: 0 additions & 2 deletions crates/jstz_kernel/src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ use tezos_smart_rollup::types::{Contract, PublicKeyHash as TezosPublicKeyHash};

pub fn try_parse_contract(contract: &Contract) -> Result<NewAddress> {
match contract {
// TODO: remove implicit account?
// https://linear.app/tezos/issue/JSTZ-260/add-validation-check-for-address-type
Contract::Implicit(TezosPublicKeyHash::Ed25519(tz1)) => {
Ok(NewAddress::User(PublicKeyHash::Tz1(tz1.clone().into())))
}
Expand Down
2 changes: 1 addition & 1 deletion crates/jstz_mock/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub const MOCK_RECEIVER: &str = "tz1PCXYfph1FQBy1jBEXVAhzgzoBww4vkjC8";
pub const MOCK_SENDER: &str = "KT1R7WEtNNim3YgkxPt8wPMczjH3eyhbJMtz";
pub const MOCK_SOURCE: &str = "tz1WXDeZmSpaCCJqes9GknbeUtdKhJJ8QDA2";

pub const MOCK_PROXY: &str = "tz1ZpKsSVbrQmUeFEjMFK7zWaZ1N9AudDWqy";
pub const MOCK_PROXY: &str = "KT1RJ6PbjHpwc3M5rw5s2Nbmefwbuwbdxton";
pub const MOCK_PROXY_FUNCTION: &str = r#"
export default (request) => {
const url = new URL(request.url)
Expand Down
8 changes: 5 additions & 3 deletions crates/jstz_mock/src/message/fa_deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub struct MockFaDeposit {
pub ticket_amount: u32,
pub ticket_content: (u32, Option<Vec<u8>>),
pub smart_rollup: Option<SmartRollupAddress>,
pub proxy_contract: Option<jstz_crypto::public_key_hash::PublicKeyHash>, // proxy must be tz1 for nows
pub proxy_contract: Option<jstz_crypto::smart_function_hash::SmartFunctionHash>,
}

impl Default for MockFaDeposit {
Expand All @@ -47,8 +47,10 @@ impl Default for MockFaDeposit {
// use sf hash
// https://linear.app/tezos/issue/JSTZ-260/add-validation-check-for-address-type
proxy_contract: Some(
jstz_crypto::public_key_hash::PublicKeyHash::from_base58(MOCK_PROXY)
.unwrap(),
jstz_crypto::smart_function_hash::SmartFunctionHash::from_base58(
MOCK_PROXY,
)
.unwrap(),
),
}
}
Expand Down
39 changes: 28 additions & 11 deletions crates/jstz_node/src/services/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use axum::{
use jstz_core::BinEncodable;
use jstz_proto::{
api::KvValue,
context::account::{Account, Nonce, ParsedCode},
context::new_account::{
Account, Nonce, ParsedCode, SmartFunctionAccount, UserAccount,
ACCOUNTS_PATH_PREFIX,
},
};
use serde::Deserialize;
use utoipa_axum::{router::OpenApiRouter, routes};
Expand All @@ -30,6 +33,10 @@ fn deserialize_account(data: &[u8]) -> ServiceResult<Account> {
Ok(Account::decode(data).map_err(|_| anyhow!("Failed to deserialize account"))?)
}

fn construct_accounts_key(address: &str) -> String {
format!("{}/{}", ACCOUNTS_PATH_PREFIX, address)
}

#[derive(Deserialize)]
struct KvQuery {
key: Option<String>,
Expand All @@ -52,10 +59,13 @@ async fn get_nonce(
State(AppState { rollup_client, .. }): State<AppState>,
Path(address): Path<String>,
) -> ServiceResult<Json<Nonce>> {
let key = format!("/jstz_account/{}", address);
let key = construct_accounts_key(&address);
let value = rollup_client.get_value(&key).await?;
let account_nonce = match value {
Some(value) => deserialize_account(value.as_slice())?.nonce,
Some(value) => match deserialize_account(value.as_slice())? {
Account::User(UserAccount { nonce, .. }) => nonce,
Account::SmartFunction(SmartFunctionAccount { nonce, .. }) => nonce,
},
None => Err(ServiceError::NotFound)?,
};
Ok(Json(account_nonce))
Expand All @@ -77,15 +87,19 @@ async fn get_code(
State(AppState { rollup_client, .. }): State<AppState>,
Path(address): Path<String>,
) -> ServiceResult<Json<ParsedCode>> {
let key = format!("/jstz_account/{}", address);
let key = construct_accounts_key(&address);
let value = rollup_client.get_value(&key).await?;
let account_code = match value {
Some(value) => deserialize_account(value.as_slice())?.function_code,
Some(value) => match deserialize_account(value.as_slice())? {
Account::User { .. } => Err(ServiceError::BadRequest(
"Account is not a smart function".to_string(),
))?,
Account::SmartFunction(SmartFunctionAccount { function_code, .. }) => {
function_code
}
},
None => Err(ServiceError::NotFound)?,
}
.ok_or_else(|| {
ServiceError::BadRequest("Account is not a smart function".to_string())
})?;
};
Ok(Json(account_code))
}

Expand All @@ -104,10 +118,13 @@ async fn get_balance(
State(AppState { rollup_client, .. }): State<AppState>,
Path(address): Path<String>,
) -> ServiceResult<Json<u64>> {
let key = format!("/jstz_account/{}", address);
let key = construct_accounts_key(&address);
let value = rollup_client.get_value(&key).await?;
let account_balance = match value {
Some(value) => deserialize_account(value.as_slice())?.amount,
Some(value) => match deserialize_account(value.as_slice())? {
Account::User(UserAccount { amount, .. }) => amount,
Account::SmartFunction(SmartFunctionAccount { amount, .. }) => amount,
},
None => Err(ServiceError::NotFound)?,
};
Ok(Json(account_balance))
Expand Down
2 changes: 1 addition & 1 deletion crates/jstz_proto/src/api/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use jstz_core::{

use crate::{
context::{
account::{Account, Amount},
new_account::NewAddress,
new_account::{Account, Amount},
},
error::Result,
};
Expand Down
10 changes: 6 additions & 4 deletions crates/jstz_proto/src/api/smart_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use jstz_core::{

use crate::{
context::{
account::{Account, Amount, ParsedCode},
new_account::NewAddress,
new_account::{Account, Amount, ParsedCode},
},
executor::{
smart_function::{headers, HostScript, Script},
Expand Down Expand Up @@ -260,14 +260,15 @@ mod test {
use jstz_crypto::{
hash::{Blake2b, Hash},
public_key_hash::PublicKeyHash,
smart_function_hash::SmartFunctionHash,
};
use jstz_mock::host::JstzMockHost;
use serde_json::json;

use crate::{
context::{
account::{Account, ParsedCode},
new_account::NewAddress,
new_account::{Account, ParsedCode},
ticket_table::TicketTable,
},
executor::smart_function::{self, register_web_apis, Script},
Expand All @@ -289,8 +290,9 @@ mod test {

// TODO: Use sf address instead
// https://linear.app/tezos/issue/JSTZ-260/add-validation-check-for-address-type
let self_address =
NewAddress::User(PublicKeyHash::digest(b"random bytes").unwrap());
let self_address = NewAddress::SmartFunction(
SmartFunctionHash::digest(b"random bytes").unwrap(),
);
let amount = 100;

let operation_hash = Blake2b::from(b"operation_hash".as_ref());
Expand Down
Loading

0 comments on commit 3f36e33

Please sign in to comment.