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

chore: fix balance and address recovery retry #504

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ export const getERC20TokenBalanceForOwner = publicProcedure
})
)
.query(async ({ input, ctx }) => {
// If the token address and owner address are not the same length, the balance is 0
// This is because a sui address can't have evm balances and vice versa
if (input.tokenAddress?.length !== input.owner?.length) {
return {
isTokenOwner: false,
isTokenMinter: false,
tokenBalance: "0",
decimals: 0,
isTokenPendingOwner: false,
hasPendingOwner: false,
hasMinterRole: false,
hasOperatorRole: false,
hasFlowLimiterRole: false,
};
}
// Sui address length is 66
if (input.tokenAddress?.length === 66) {
let isTokenOwner = false;
Expand Down
67 changes: 36 additions & 31 deletions apps/maestro/src/server/routers/sui/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { TxBuilder } from "@axelar-network/axelar-cgp-sui";
import {
getFullnodeUrl,
SuiClient,
SuiObjectChange,
type DynamicFieldPage,
} from "@mysten/sui/client";
import { getFullnodeUrl, SuiClient, SuiObjectChange } from "@mysten/sui/client";
import { Transaction } from "@mysten/sui/transactions";

import config from "../config/devnet-amplifier.json";
Expand Down Expand Up @@ -86,13 +81,6 @@ export const getTokenOwner = async (tokenAddress: string) => {
export const getCoinAddressAndManagerByTokenId = async (input: {
tokenId: string;
}) => {
let cursor = null;
let filteredResult = [];
let result = {
hasNextPage: true,
nextCursor: null,
data: [],
} as DynamicFieldPage;
try {
const suiClient = new SuiClient({
url: config["sui"].rpc,
Expand All @@ -111,27 +99,18 @@ export const getCoinAddressAndManagerByTokenId = async (input: {
const registeredCoinsBagId = (registeredCoinsObject.data?.content as any)
?.fields?.value?.fields.registered_coins.fields.id.id;

do {
result = await suiClient.getDynamicFields({
parentId: registeredCoinsBagId,
cursor: cursor,
});
cursor = result.nextCursor;
filteredResult = result.data.filter((item: any) => {
return (
item.name.value.id.toString().toLowerCase() ===
input.tokenId.toLowerCase()
);
});
if (filteredResult.length) {
break;
}
} while (result?.hasNextPage && !filteredResult?.length);
const filteredResult = await findInPaginatedDynamicFields(
suiClient,
registeredCoinsBagId,
(item: any) =>
item.name.value.id.toString().toLowerCase() ===
input.tokenId.toLowerCase()
);

if (filteredResult.length > 0) {
if (filteredResult) {
return extractTokenDetails(filteredResult);
} else {
console.log("Token ID not found.");
console.log("getCoinAddressAndManagerByTokenId: Token ID not found.");
return null;
}
} catch (error) {
Expand All @@ -142,6 +121,32 @@ export const getCoinAddressAndManagerByTokenId = async (input: {
}
};

export async function findInPaginatedDynamicFields<T>(
suiClient: SuiClient,
parentId: string,
filterFn: (item: any) => boolean
): Promise<T[] | null> {
let cursor: string | null = null;
let result;
let filteredResult: any[] = [];

do {
result = await suiClient
.getDynamicFields({
parentId,
cursor: cursor,
})
.catch((error) => {
console.error("Failed to get dynamic fields:", error);
return null;
});

cursor = result?.nextCursor ?? null;
filteredResult = result?.data?.filter(filterFn) ?? [];
} while (result?.hasNextPage && !filteredResult?.length);
return filteredResult?.length ? filteredResult : null;
}

function extractTokenDetails(filteredResult: any[]) {
return filteredResult.map((item) => {
// Extract the token manager (objectId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,9 @@ const ConnectedInterchainTokensPage: FC<ConnectedInterchainTokensPageProps> = (
const { mutateAsync: updateEVMAddresses } =
trpc.interchainToken.updateEVMRemoteTokenAddress.useMutation();

// Update Sui remote token addresses
// the address is wrong on the Sui chain on deployment because it's the EVM address,
// we wait for the tx to be executed then we update the address on the Sui chain
useEffect(() => {
if (
!isAlreadyUpdatingRemoteSui &&
Expand All @@ -257,9 +260,10 @@ const ConnectedInterchainTokensPage: FC<ConnectedInterchainTokensPageProps> = (
setAlreadyUpdatingRemoteSui(false);
refetchPageData();
})
.catch((error) => {
setAlreadyUpdatingRemoteSui(false);
console.error("Failed to update Sui remote token addresses:", error);
.catch(() => {
setTimeout(() => {
setAlreadyUpdatingRemoteSui(false);
}, 5000);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what event this set timeout is waiting for? improve if there's a better way to do this or add a todo to improve later if it's not trivial.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

waiting for sui token to be registered, sui is the destination chain

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so we're waiting for full cross-chain tx with 5 seconds? i think i might misunderstand something 😅

});
}
}, [
Expand All @@ -273,6 +277,13 @@ const ConnectedInterchainTokensPage: FC<ConnectedInterchainTokensPageProps> = (

const [isUpdating, setIsUpdating] = useState<Record<string, boolean>>({});

const setChainUpdateStatus = useCallback(
(chainId: string | undefined, status: boolean) => {
setIsUpdating((prev) => ({ ...prev, [chainId ?? ""]: status }));
},
[]
);

useEffect(() => {
interchainToken?.matchingTokens?.forEach((x) => {
// check if the EVM token address is the same as sui, which is wrong
Expand All @@ -282,22 +293,19 @@ const ConnectedInterchainTokensPage: FC<ConnectedInterchainTokensPageProps> = (
x.tokenAddress === props.tokenAddress &&
!isUpdating[x.chain?.id ?? ""]
) {
setIsUpdating((prev) => ({ ...prev, [x.chain?.id ?? ""]: true }));
setChainUpdateStatus(x.chain?.id, true);
updateEVMAddresses({
tokenId: props?.tokenId as `0x${string}`,
axelarChainId: x.chain?.id,
})
.then(() => {
setChainUpdateStatus(x.chain?.id, false);
refetchPageData();
})
.catch((error) => {
console.error(
"Failed to update EVM remote token addresses:",
error
);
})
.finally(() => {
setIsUpdating((prev) => ({ ...prev, [x.chain?.id ?? ""]: false }));
.catch(() => {
setTimeout(() => {
setChainUpdateStatus(x.chain?.id, false);
}, 5000);
});
}
});
Expand All @@ -309,6 +317,7 @@ const ConnectedInterchainTokensPage: FC<ConnectedInterchainTokensPageProps> = (
updateEVMAddresses,
isUpdating,
refetchPageData,
setChainUpdateStatus,
]);

const remoteChainsExecuted = useMemo(
Expand Down