Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adapt indexer to ts-rs exported interfaces #921

Merged
merged 4 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 22 additions & 13 deletions applications/tari_indexer/src/json_rpc/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use log::{error, warn};
use serde_json::{self as json, json, Value};
use tari_base_node_client::{grpc::GrpcBaseNodeClient, types::BaseLayerConsensusConstants, BaseNodeClient};
use tari_dan_app_utilities::{keypair::RistrettoKeypair, substate_file_cache::SubstateFileCache};
use tari_dan_common_types::{optional::Optional, public_key_to_peer_id, Epoch, PeerAddress};
use tari_dan_common_types::{optional::Optional, public_key_to_peer_id, PeerAddress};
use tari_dan_p2p::TariMessagingSpec;
use tari_dan_storage::consensus_models::Decision;
use tari_epoch_manager::{base_layer::EpochManagerHandle, EpochManagerReader};
Expand All @@ -43,12 +43,19 @@ use tari_indexer_client::{
AddAddressRequest,
AddPeerRequest,
AddPeerResponse,
ClearAddressesResponse,
ConnectionDirection,
DeleteAddressRequest,
GetAddressesResponse,
GetAllVnsRequest,
GetAllVnsResponse,
GetCommsStatsResponse,
GetConnectionsResponse,
GetEpochManagerStatsResponse,
GetIdentityResponse,
GetNonFungibleCollectionsResponse,
GetNonFungibleCountRequest,
GetNonFungibleCountResponse,
GetNonFungiblesRequest,
GetNonFungiblesResponse,
GetRelatedTransactionsRequest,
Expand Down Expand Up @@ -156,13 +163,10 @@ impl JsonRpcHandlers {

pub async fn get_all_vns(&self, value: JsonRpcExtractor) -> JrpcResult {
let answer_id = value.get_answer_id();
let epoch: u64 = value.parse_params()?;
let epoch_blocks = self.consensus_constants.epoch_to_height(Epoch(epoch));
let GetAllVnsRequest { epoch } = value.parse_params()?;
let epoch_blocks = self.consensus_constants.epoch_to_height(epoch);
match self.base_node_client().get_validator_nodes(epoch_blocks).await {
Ok(vns) => {
let response = json!({ "vns": vns });
Ok(JsonRpcResponse::success(answer_id, response))
},
Ok(vns) => Ok(JsonRpcResponse::success(answer_id, GetAllVnsResponse { vns })),
Err(e) => Err(Self::internal_error(answer_id, format!("Failed to get all vns: {}", e))),
}
}
Expand Down Expand Up @@ -216,8 +220,9 @@ impl JsonRpcHandlers {
.map_err(internal_error(answer_id))?;

let status = if peers.is_empty() { "Offline" } else { "Online" };
let response = json!({ "connection_status": status });
Ok(JsonRpcResponse::success(answer_id, response))
Ok(JsonRpcResponse::success(answer_id, GetCommsStatsResponse {
connection_status: status.to_string(),
}))
}

pub async fn get_connections(&self, value: JsonRpcExtractor) -> JrpcResult {
Expand Down Expand Up @@ -385,7 +390,7 @@ impl JsonRpcHandlers {
let res = self.substate_manager.get_all_addresses_from_db().await;

match res {
Ok(addresses) => Ok(JsonRpcResponse::success(answer_id, addresses)),
Ok(addresses) => Ok(JsonRpcResponse::success(answer_id, GetAddressesResponse { addresses })),
Err(e) => {
warn!(target: LOG_TARGET, "Error getting addresses: {}", e);
Err(Self::internal_error(
Expand Down Expand Up @@ -433,7 +438,7 @@ impl JsonRpcHandlers {
let answer_id = value.get_answer_id();

match self.substate_manager.delete_all_substates_from_db().await {
Ok(_) => Ok(JsonRpcResponse::success(answer_id, ())),
Ok(_) => Ok(JsonRpcResponse::success(answer_id, ClearAddressesResponse {})),
Err(e) => {
warn!(target: LOG_TARGET, "Error clearing addresses: {}", e);
Err(Self::internal_error(
Expand All @@ -450,7 +455,9 @@ impl JsonRpcHandlers {
let res = self.substate_manager.get_non_fungible_collections().await;

match res {
Ok(collections) => Ok(JsonRpcResponse::success(answer_id, collections)),
Ok(collections) => Ok(JsonRpcResponse::success(answer_id, GetNonFungibleCollectionsResponse {
collections,
})),
Err(e) => {
warn!(target: LOG_TARGET, "Error getting non fungible collections: {}", e);
Err(Self::internal_error(
Expand All @@ -473,7 +480,9 @@ impl JsonRpcHandlers {
Self::internal_error(answer_id, format!("Error getting non fungible count: {}", e))
})?;

Ok(JsonRpcResponse::success(answer_id, count))
Ok(JsonRpcResponse::success(answer_id, GetNonFungibleCountResponse {
count,
}))
}

pub async fn get_non_fungibles(&self, value: JsonRpcExtractor) -> JrpcResult {
Expand Down
35 changes: 29 additions & 6 deletions applications/tari_indexer_web_ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions applications/tari_indexer_web_ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"react-icons": "^4.9.0",
"react-router-dom": "^6.4.3",
"react-scripts": "5.0.1",
"tari-bindings": "file:../../bindings",
"typescript": "^4.8.4",
"use-react-router-breadcrumbs": "^4.0.1",
"web-vitals": "^2.1.4"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,7 @@ import { TextField } from "@mui/material";
import { Form } from "react-router-dom";
import Fade from "@mui/material/Fade";
import CopyToClipboard from "../../../Components/CopyToClipboard";

interface IConnection {
connection_id: number;
address: string;
age: Duration;
direction: boolean;
peer_id: string;
ping_latency: Duration | null;
// public_key: string;
}
import { Connection } from "tari-bindings";

interface Duration {
secs: number;
Expand All @@ -72,7 +63,7 @@ const useInterval = (fn: () => Promise<unknown>, ms: number) => {
};

function Connections() {
const [connections, setConnections] = useState<IConnection[]>([]);
const [connections, setConnections] = useState<Array<Connection>>([]);
const [showPeerDialog, setShowAddPeerDialog] = useState(false);
const [formState, setFormState] = useState({ publicKey: "", address: "" });

Expand All @@ -81,7 +72,11 @@ function Connections() {
};

const onSubmitAddPeer = async () => {
await addPeer(formState.publicKey, formState.address ? [formState.address] : []);
await addPeer({
public_key: formState.publicKey,
addresses: formState.address ? [formState.address] : [],
wait_for_dial: false,
});
setFormState({ publicKey: "", address: "" });
setShowAddPeerDialog(false);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import { IIdentity } from "../../../utils/interfaces";
import "./Info.css";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableRow from "@mui/material/TableRow";
import { DataTableCell } from "../../../Components/StyledComponents";
import { GetIdentityResponse } from "tari-bindings";

function Info({ identity }: { identity: IIdentity }) {
function Info({ identity }: { identity: GetIdentityResponse }) {
return (
<div>
<TableContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ function MonitoredNftCollections() {
setShowAddAddressDialog(setElseToggle);
};
const onSubmitAddAddress = () => {
addAddress(formState.address).then((resp) => {
// TODO: We always use Component, because it's anyway to be serialized as a string, but maybe we should parse the address and use the correct type?
addAddress({ address: { Component: formState.address } }).then((resp) => {
updatedAddresses();
});
setFormState({ address: "" });
Expand All @@ -124,7 +125,7 @@ function MonitoredNftCollections() {
const updatedAddresses = () => {
getNonFungibleCollections().then((resp) => {
setAddresses(
resp.map(([address, count]: [string, number]) => ({
resp.collections.map(([address, count]: [string, number]) => ({
id: address,
address: address,
count: count,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ function RowData({
size="small"
onClick={() => {
if (data === null) {
inspectSubstate(address)
// TODO: We always use Component, because it's anyway to be serialized as a string, but maybe we should parse the address and use the correct type?
inspectSubstate({ address: { Component: address }, version: null })
.then((resp) => {
setData(JSON.stringify(resp));
})
Expand Down Expand Up @@ -142,7 +143,8 @@ function MonitoredSubstates() {
setShowAddAddressDialog(setElseToggle);
};
const onSubmitAddAddress = () => {
addAddress(formState.address).then((resp) => {
// TODO: We always use Component, because it's anyway to be serialized as a string, but maybe we should parse the address and use the correct type?
addAddress({ address: { Component: formState.address } }).then((resp) => {
updatedAddresses();
});
setFormState({ address: "" });
Expand All @@ -167,7 +169,7 @@ function MonitoredSubstates() {
const updatedAddresses = () => {
getAddresses().then((resp) => {
setAddresses(
resp.map(([address, version]: [string, number]) => ({
resp.addresses.map(([address, version]: [string, number]) => ({
id: address,
address: address,
version: version,
Expand All @@ -181,8 +183,8 @@ function MonitoredSubstates() {
}, []);

const onDelete = (address: string) => {
deleteAddress(address).then((resp) => {
console.log(`Address ${address} deleted`);
// TODO: We always use Component, because it's anyway to be serialized as a string, but maybe we should parse the address and use the correct type?
deleteAddress({ address: { Component: address } }).then((resp) => {
updatedAddresses();
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import Typography from "@mui/material/Typography";
import { Button, ImageList, ImageListItem, ImageListItemBar, TextField } from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import { ConfirmDialog } from "../../../Components/AlertDialog";
import { NonFungibleSubstate } from "tari-bindings";

interface IImageData {
img: string;
Expand All @@ -53,17 +54,20 @@ function NftGallery() {

const updateCollection = () => {
if (resourceAddress !== undefined) {
getNonFungibles(resourceAddress, 0, 10).then((resp) => {
console.log({ resp });

getNonFungibles({ address: { Resource: resourceAddress }, start_index: 0, end_index: 10 }).then((resp) => {
let nfts: any = [];
resp.forEach((nft: any, i: number) => {
resp.non_fungibles.forEach((nft: NonFungibleSubstate, i: number) => {
console.log(nft);
let nft_data = nft.substate.substate.NonFungible.data["@@TAGGED@@"][1];
let { image_url, name } = nft_data;
console.log(image_url);
console.log(name);
nfts.push({ image_url, name, index: i });
if (!("NonFungible" in nft.substate.substate)) {
return;
}
let nft_data = nft.substate.substate.NonFungible?.data;
// Was this is a work in progress? There was no image_url coming from the jrpc before this change.
// TODO: make this work
// let { image_url, name } = nft_data;
// console.log(image_url);
// console.log(name);
// nfts.push({ image_url, name, index: i });
});

setItems(
Expand All @@ -79,7 +83,7 @@ function NftGallery() {

useEffect(() => {
updateCollection();
}, []);
});

return (
<ImageList cols={4} gap={8}>
Expand Down
Loading
Loading