Skip to content

Commit

Permalink
celanup
Browse files Browse the repository at this point in the history
  • Loading branch information
karczuRF committed Nov 15, 2024
1 parent c4f4cad commit dcc90b9
Show file tree
Hide file tree
Showing 13 changed files with 25 additions and 107 deletions.
5 changes: 1 addition & 4 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ pub async fn create_account(tokens: State<'_, Tokens>) -> Result<(), Error> {

#[tauri::command]
pub async fn get_free_coins(tokens: State<'_, Tokens>) -> Result<(), Error> {
println!("=============> get free coins");
// Use default account
let account_name = "tester".to_string();
let account_name = "default".to_string();
let permission_token = tokens.permission
.lock()
.map_err(|_| FailedToObtainPermissionTokenLock)?
Expand Down Expand Up @@ -92,7 +91,6 @@ pub async fn call_wallet(
params: String,
tokens: State<'_, Tokens>
) -> Result<serde_json::Value, Error> {
println!("======== HELLO THERE CALL WALLET {:?}", method);
let permission_token = tokens.permission
.lock()
.map_err(|_| FailedToObtainPermissionTokenLock)?
Expand All @@ -103,7 +101,6 @@ pub async fn call_wallet(
make_request(Some(permission_token), method, req_params).await
});
let response = handle.await?.map_err(|_| Error::ProviderError { method: method_clone, params })?;
println!("======== HELLO THERE CALL WALLET RESPOSNE {:?}", response);
Ok(response)
}

Expand Down
2 changes: 0 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,10 @@ async fn try_get_tokens() -> (String, String) {
loop {
match permission_token().await {
Ok(tokens) => {
println!("permission token ok {:?}", tokens);
info!(target: LOG_TARGET, "permission token ok {:?}", tokens);
return tokens;
}
Err(e) => {
println!("permission token ERR {:?}", e);
warn!(target: LOG_TARGET, "permission token ERR {:?}", e);
sleep(Duration::from_millis(500));
continue;
Expand Down
11 changes: 2 additions & 9 deletions src-tauri/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,13 @@ pub async fn permission_token() -> Result<(String, String), anyhow::Error> {

pub async fn account_create(account_name: Option<String>, permissions_token: String) -> Result<(), anyhow::Error> {
let create_acc_params = AccountsCreateRequest {
account_name: Some("User".to_string()),
account_name,
custom_access_rules: None,
is_default: false,
key_id: None,
max_fee: None,
};
println!("----------- REQEST {:?}", create_acc_params);
let resp = make_request(Some(permissions_token), "accounts.create".to_string(), create_acc_params).await?;
println!("----------- REQEST resp {:?}", resp);

Ok(())
}
Expand All @@ -62,13 +60,11 @@ pub async fn free_coins(account_name: Option<String>, permissions_token: String)
max_fee: None,
key_id: None,
};
println!("----------- REQEST free test coins {:?}", free_coins_params);
let resp = make_request(
let _resp = make_request(
Some(permissions_token),
"accounts.create_free_test_coins".to_string(),
free_coins_params
).await?;
println!("----------- REQEST resp {:?}", resp);
Ok(())
}

Expand Down Expand Up @@ -111,10 +107,7 @@ pub async fn make_request<T: Serialize>(
if let Some(token) = token {
builder = builder.header(AUTHORIZATION, format!("Bearer {token}"));
}
println!("------- JSON REQ BODY ");
println!("{:?}", &body);
let resp = builder.json(&body).send().await?.json::<JsonRpcResponse>().await?;
println!("------- JSON RESPONSE {:?} ", resp.result);
match resp.result {
JsonRpcAnswer::Result(result) => Ok(result),
JsonRpcAnswer::Error(error) => Err(anyhow::Error::msg(error.to_string())),
Expand Down
3 changes: 0 additions & 3 deletions src/components/SelectAccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ function SelectAccount({ onSubmit, accountsList }: SelectAccountProps) {
const [newAccountName, setNewAccountName] = useState("")

const handleChange = (event: SelectChangeEvent) => {
console.log("TODO: set active account from the list")
dispatch(
accountActions.setAccountRequest({
accountName: event.target.value,
Expand All @@ -31,12 +30,10 @@ function SelectAccount({ onSubmit, accountsList }: SelectAccountProps) {
}

const handleSubmit = useCallback(async () => {
console.log("submit handle new account", newAccountName)
return onSubmit(newAccountName)
}, [newAccountName, onSubmit])

const onAddAccountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(accountsList)
setNewAccountName(e.target.value)
}

Expand Down
1 change: 0 additions & 1 deletion src/components/Tapplet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ type TappletProps = {
export const Tapplet: React.FC<TappletProps> = ({ source }) => {
const tappletRef = useRef<HTMLIFrameElement | null>(null)
const provider = useSelector(providerSelector.selectProvider)
console.log(">>>>>>>>>>> PROVIDER", provider)

function sendWindowSize() {
if (tappletRef.current) {
Expand Down
54 changes: 9 additions & 45 deletions src/components/Wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,16 @@ export const Wallet: React.FC = () => {
const dispatch = useDispatch()
const provider = useSelector(providerSelector.selectProvider)
const currentAccount = useSelector(accountSelector.selectAccount)
// const [accountAddress, setAccountAddress] = useState("")
const [accountsList, setAccountsList] = useState<AccountInfo[]>([])

useEffect(() => {
refreshAccount()
}, [provider])

const refreshAccount = useCallback(async () => {
console.log("fetch")
try {
const { accounts, total } = await provider.getAccountsList() //TODO fix to get value not empty array
const { accounts } = await provider.getAccountsList() //TODO fix to get value not empty array - https://github.com/tari-project/tari-universe/issues/141
setAccountsList(accounts)
console.log(accountsList)
} catch (error) {
console.error(error)
if (typeof error === "string") {
Expand All @@ -40,20 +37,14 @@ export const Wallet: React.FC = () => {

async function handleCreateAccount(accountName: string) {
try {
const account = await provider.createFreeTestCoins(accountName)
console.log("HANDLE CREATE ACCOUNT", account)
const tst = await provider.client.accountsSetDefault({
account: {
ComponentAddress: account.address,
},
})
console.log("HANDLE SET DEFAULT ACCOUNT", tst)
await provider.createFreeTestCoins(accountName)
dispatch(
accountActions.setAccountRequest({
accountName,
})
)
} catch (error) {
console.error(error)
if (typeof error === "string") {
dispatch(errorActions.showError({ message: error, errorSource: ErrorSource.BACKEND }))
}
Expand All @@ -62,50 +53,23 @@ export const Wallet: React.FC = () => {

async function get_free_coins() {
try {
console.log("==================================================")
// needs to have account name - otherwise it throws error
if (!currentAccount) return
const currentAccountName = currentAccount?.account.name ?? undefined
console.log(currentAccountName)
const account = await provider.createFreeTestCoins(currentAccountName)
// setAccountAddress(acc.address)
// dispatch(
// accountActions.setAccount({
// account: {
// account: {
// name: account.address,
// address: account.address as any,
// key_index: account.account_id,
// is_default: true,
// },
// public_key: account.public_key,
// },
// })
// )
// console.log("GET ACCOUNT", acc)
await provider.createFreeTestCoins(currentAccountName)
} catch (error) {
console.log("GET ACCOUNT ERROR", error)
console.error(error)
if (typeof error === "string") {
console.log(error)
dispatch(errorActions.showError({ message: error, errorSource: ErrorSource.BACKEND }))
}
}
}

async function get_balances() {
try {
console.log("==================================================")
// const addr = (currentAccount && currentAccount.account.address as { Component: string }).Component,
const addr = currentAccount?.account.address as any

console.log("get balances acc store", currentAccount)
console.log("get balances acc store", currentAccount?.account.address)
console.log("get balances acc store addr", addr)
// setBalances(await invoke("get_balances", {}))
const resp = await provider.getAccountBalances(addr)
console.log("get balances resp", resp)
const accountAddress = substateIdToString(currentAccount?.account.address ?? null)
const resp = await provider.getAccountBalances(accountAddress)
setBalances(resp.balances)
} catch (error) {
console.error(error)
if (typeof error === "string") {
dispatch(errorActions.showError({ message: error, errorSource: ErrorSource.BACKEND }))
}
Expand All @@ -119,7 +83,7 @@ export const Wallet: React.FC = () => {
</Typography>
<Box display="flex" flexDirection="column" gap={2} alignItems="center" py={4}>
<SelectAccount onSubmit={handleCreateAccount} accountsList={accountsList} />
<Paper variant="outlined" elevation={0} sx={{ padding: 1, borderRadius: 2, width: "35%" }}>
<Paper variant="outlined" elevation={0} sx={{ padding: 1, borderRadius: 2, width: "50%" }}>
<Stack direction="column" justifyContent="flex-end">
<Typography variant="caption" textAlign="left">{`Name: ${currentAccount?.account.name}`}</Typography>
<Typography variant="caption" textAlign="left">{`${t("address", {
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ export function shortenSubstateAddress(input: string, startChars = 5, endChars =

// Check if the input has the expected format
if (parts.length < 2) {
return input // Return the original string if it doesn't match the expected format
return input
}

const prefix = parts[0] // SubstateId
const longString = parts[1] // Address

// Ensure the long string is long enough to shorten
if (longString.length <= startChars + endChars) {
return input // Return the original string if it's too short to shorten
return input
}

const startPart = longString.substring(0, startChars)
Expand Down
29 changes: 3 additions & 26 deletions src/provider/TariUniverseProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,31 +81,17 @@ export class TariUniverseProvider implements TariProvider {
}

async runOne(method: TUProviderMethod, args: any[]): Promise<any> {
console.log(">>> runOne", method, args)
const isAuth = this.client.isAuthenticated()
console.log(">>> runOne isAuth", isAuth)
let res = (this[method] as (...args: any) => Promise<any>)(...args)
console.log(">>> runOne", res)
return res
}

public async createFreeTestCoins(accountName?: string, amount = 1_000_000, fee?: number): Promise<Account> {
//TODO tmp solution to debug rpc call problem
console.log(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ")
console.log("create coins - TARI UNIVERSE PROVIDER")
// const res = await accountsCreateFreeTestCoins({
// account: (accountName && { Name: accountName }) || null,
// amount,
// max_fee: fee ?? null,
// key_id: null,
// })
const res = await this.client.createFreeTestCoins({
account: (accountName && { Name: accountName }) || null,
amount,
max_fee: fee ?? null,
key_id: null,
})
console.log("create coins res", res)
return {
account_id: res.account.key_index,
address: (res.account.address as { Component: string }).Component,
Expand All @@ -120,16 +106,13 @@ export class TariUniverseProvider implements TariProvider {
customAccessRules?: ComponentAccessRules,
isDefault = true
): Promise<Account> {
console.log("create account")

const res = await this.client.accountsCreate({
account_name: accountName ?? null,
custom_access_rules: customAccessRules ?? null,
is_default: isDefault,
key_id: null,
max_fee: fee ?? null,
})
console.log("create account res", res)
return {
account_id: 0,
address: (res.address as { Component: string }).Component,
Expand All @@ -153,7 +136,6 @@ export class TariUniverseProvider implements TariProvider {
account_id: account.key_index,
address: account.address.Component,
public_key,
// TODO
resources: balances.map((b: any) => ({
type: b.resource_type,
resource_address: b.resource_address,
Expand All @@ -172,12 +154,12 @@ export class TariUniverseProvider implements TariProvider {
}

public async getAccountsList(limit = 0, offset = 10): Promise<AccountsListResponse> {
const l = await this.client.accountsList({
// TODO https://github.com/tari-project/tari-universe/issues/141
const res = await this.client.accountsList({
limit,
offset,
})
console.log("get list", l)
return l
return res
}

public async getAccountsBalances(
Expand All @@ -200,9 +182,6 @@ export class TariUniverseProvider implements TariProvider {
}

public async submitTransaction(req: SubmitTransactionRequest): Promise<SubmitTransactionResponse> {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
console.log(" submit tx TU Provider", req)

const params = {
transaction: {
instructions: req.instructions as Instruction[],
Expand All @@ -220,10 +199,8 @@ export class TariUniverseProvider implements TariProvider {
detect_inputs: false, //TODO check if works for 'false'
proof_ids: [],
} as TransactionSubmitRequest
console.log("!!!!!!!!!!!!!!!!!!!!!!!!! submit tx TU Provider", params)

const res = await this.client.submitTransaction(params)

return { transaction_id: res.transaction_id }
}

Expand Down
1 change: 0 additions & 1 deletion src/provider/ipc_transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { invoke } from "@tauri-apps/api/core"

export class IPCRpcTransport implements transports.RpcTransport {
async sendRequest<T>(request: transports.RpcRequest, _: transports.RpcTransportOptions): Promise<T> {
console.log("!!!!!!!!!!!!!!! IPC RPC send request", request)
return await invoke("call_wallet", {
method: request.method,
params: JSON.stringify(request.params),
Expand Down
10 changes: 5 additions & 5 deletions src/store/account/account.action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,21 @@ export const setAccountAction = () => ({
dispatch(errorActions.showError({ message: "failed-to-find-provider", errorSource: ErrorSource.FRONTEND }))
return
}

// if tapplet uses TU Provider it gets default account
// this is to make sure tapplet uses the account selected by the user
await provider.client.accountsSetDefault({
account: {
Name: action.payload.accountName,
},
})
const _account = await provider.client.accountsGet({
const account = await provider.client.accountsGet({
name_or_address: { Name: action.payload.accountName },
})
console.log("set action ", _account)
const list = await provider.client.accountsList({ limit: 0, offset: 10 })
console.log("set action ", list)

listenerApi.dispatch(
accountActions.setAccountSuccess({
account: _account,
account,
})
)
} catch (error) {
Expand Down
1 change: 0 additions & 1 deletion src/store/devTapplets/devTapplets.action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ export const addDevTappletAction = () => ({
) => {
const endpoint = action.payload.endpoint
try {
console.log("ADD DEV TAPP")
await invoke("add_dev_tapplet", { endpoint })
listenerApi.dispatch(devTappletsActions.addDevTappletSuccess({}))
listenerApi.dispatch(devTappletsActions.initializeRequest({}))
Expand Down
Loading

0 comments on commit dcc90b9

Please sign in to comment.