Skip to content

Commit

Permalink
API: Delete Token (#132)
Browse files Browse the repository at this point in the history
Signed-off-by: Ivy Astrix <[email protected]>
  • Loading branch information
poi-son-ivy authored Mar 14, 2024
1 parent ec19741 commit 9f4cb35
Show file tree
Hide file tree
Showing 20 changed files with 446 additions and 56 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*-
*
* Hedera Wallet Snap
*
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { FC, useContext, useRef, useState } from 'react';
import {
MetaMaskContext,
MetamaskActions,
} from '../../../contexts/MetamaskContext';
import useModal from '../../../hooks/useModal';
import { Account, DeleteTokenRequestParams } from '../../../types/snap';
import { deleteToken, shouldDisplayReconnectButton } from '../../../utils';
import { Card, SendHelloButton } from '../../base';
import ExternalAccount, {
GetExternalAccountRef,
} from '../../sections/ExternalAccount';

type Props = {
network: string;
mirrorNodeUrl: string;
setAccountInfo: React.Dispatch<React.SetStateAction<Account>>;
};

const DeleteToken: FC<Props> = ({ network, mirrorNodeUrl, setAccountInfo }) => {
const [state, dispatch] = useContext(MetaMaskContext);
const [loading, setLoading] = useState(false);
const { showModal } = useModal();
const [tokenId, setTokenId] = useState<string>();

const externalAccountRef = useRef<GetExternalAccountRef>(null);

const handleDeleteTokenClick = async () => {
setLoading(true);
try {
const externalAccountParams =
externalAccountRef.current?.handleGetAccountParams();

const deleteTokenParams = {
tokenId,
} as DeleteTokenRequestParams;

const response: any = await deleteToken(
network,
mirrorNodeUrl,
deleteTokenParams,
externalAccountParams,
);

const { receipt, currentAccount } = response;

setAccountInfo(currentAccount);
console.log('receipt: ', receipt);

showModal({
title: 'Transaction Receipt',
content: JSON.stringify({ receipt }, null, 4),
});
} catch (error) {
console.error(error);
dispatch({ type: MetamaskActions.SetError, payload: error });
}
setLoading(false);
};

return (
<Card
content={{
title: 'deleteToken',
description:
'Delete a token from your Hedera account. This will allow you to manage your fungible and non-fungible tokens from your Hedera account.',
form: (
<>
<ExternalAccount ref={externalAccountRef} />
<label>
Enter the token ID to delete
<input
type="text"
style={{ width: '100%' }}
value={tokenId}
placeholder="Token Id"
onChange={(error) => setTokenId(error.target.value)}
/>
</label>
<br />
</>
),
button: (
<SendHelloButton
buttonText="Delete"
onClick={handleDeleteTokenClick}
disabled={!state.installedSnap}
loading={loading}
/>
),
}}
disabled={!state.installedSnap}
fullWidth={
state.isFlask &&
Boolean(state.installedSnap) &&
!shouldDisplayReconnectButton(state.installedSnap)
}
/>
);
};

export { DeleteToken };
7 changes: 7 additions & 0 deletions packages/hedera-wallet-snap/packages/site/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import {
import { MetaMaskContext, MetamaskActions } from '../contexts/MetamaskContext';
import { Account } from '../types/snap';
import { connectSnap, getSnap } from '../utils';
import {DeleteToken} from "../components/cards/hts/DeleteToken";

const Index = () => {
const [state, dispatch] = useContext(MetaMaskContext);
Expand Down Expand Up @@ -206,6 +207,12 @@ const Index = () => {
setAccountInfo={setAccountInfo}
/>

<DeleteToken
network={currentNetwork.value}
mirrorNodeUrl={mirrorNodeUrl}
setAccountInfo={setAccountInfo}
/>

<MintToken
network={currentNetwork.value}
mirrorNodeUrl={mirrorNodeUrl}
Expand Down
4 changes: 4 additions & 0 deletions packages/hedera-wallet-snap/packages/site/src/types/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ export type DissociateTokensRequestParams = {
tokenIds: string[];
};

export type DeleteTokenRequestParams = {
tokenId: string | undefined;
};

export type FreezeAccountRequestParams = {
tokenId: string;
accountId: string;
Expand Down
32 changes: 32 additions & 0 deletions packages/hedera-wallet-snap/packages/site/src/utils/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
CreateTokenRequestParams,
DeleteAccountRequestParams,
DeleteAllowanceRequestParams,
DeleteTokenRequestParams,
DissociateTokensRequestParams,
FreezeAccountRequestParams,
GetAccountInfoRequestParams,
Expand Down Expand Up @@ -598,6 +599,37 @@ export const dissociateTokens = async (
});
};

/**
* Invoke the "deleteToken" method from the snap.
*
* @param network
* @param mirrorNodeUrl
* @param deleteTokenRequestParams
* @param externalAccountparams
*/
export const deleteToken = async (
network: string,
mirrorNodeUrl: string,
deleteTokenRequestParams: DeleteTokenRequestParams,
externalAccountparams?: ExternalAccountParams,
) => {
return await window.ethereum.request({
method: 'wallet_invokeSnap',
params: {
snapId: defaultSnapOrigin,
request: {
method: 'hts/deleteToken',
params: {
network,
mirrorNodeUrl,
...deleteTokenRequestParams,
...externalAccountparams,
},
},
},
});
};

/**
* Invoke the "freezeAccount" method from the snap.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "git+https://github.com/hashgraph/hedera-metamask-snaps.git"
},
"source": {
"shasum": "kRIaknNsqGISYu34WSSYINHgQzaZJpZKPhNJDcposIw=",
"shasum": "CmjZhzdElS0nKOZTNa0JYjaBmNATyqvbF52KPjWqgPQ=",
"location": {
"npm": {
"filePath": "dist/snap.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
*/

import { AccountId, Client, TokenAssociateTransaction } from '@hashgraph/sdk';
import { TxReceipt } from '../types/hedera';
import { Utils } from '../utils/Utils';
import { CryptoUtils } from '../utils/CryptoUtils';
import { TxReceipt } from '../../types/hedera';
import { Utils } from '../../utils/Utils';
import { CryptoUtils } from '../../utils/CryptoUtils';

export class AssociateTokensCommand {
readonly #tokenIds: string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
*/

import { Client, TokenBurnTransaction } from '@hashgraph/sdk';
import { TxReceipt } from '../types/hedera';
import { CryptoUtils } from '../utils/CryptoUtils';
import { Utils } from '../utils/Utils';
import { TxReceipt } from '../../types/hedera';
import { CryptoUtils } from '../../utils/CryptoUtils';
import { Utils } from '../../utils/Utils';

export class BurnTokenCommand {
readonly #assetType: 'TOKEN' | 'NFT';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*
*/

import { TokenCustomFee } from '../types/params';
import { TokenCustomFee } from '../../types/params';
import {
AccountId,
Client,
Expand All @@ -30,9 +30,9 @@ import {
TokenSupplyType,
TokenType,
} from '@hashgraph/sdk';
import { TxReceipt } from '../types/hedera';
import { Utils } from '../utils/Utils';
import { CryptoUtils } from '../utils/CryptoUtils';
import { TxReceipt } from '../../types/hedera';
import { Utils } from '../../utils/Utils';
import { CryptoUtils } from '../../utils/CryptoUtils';

export class CreateTokenCommand {
readonly #assetType: 'TOKEN' | 'NFT';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*-
*
* Hedera Wallet Snap
*
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

import { Client, PrivateKey, TokenDeleteTransaction } from '@hashgraph/sdk';
import { TxReceipt } from '../../types/hedera';
import { CryptoUtils } from '../../utils/CryptoUtils';
import { Utils } from '../../utils/Utils';

export class DeleteTokenCommand {
readonly #tokenId: string;

readonly #adminKey: PrivateKey;

constructor(tokenId: string, adminKey: PrivateKey) {
this.#tokenId = tokenId;
this.#adminKey = adminKey;
}

public async execute(client: Client): Promise<TxReceipt> {
const transaction = await new TokenDeleteTransaction()
.setTokenId(this.#tokenId)
.freezeWith(client)
.sign(this.#adminKey);

const txResponse = await transaction.execute(client);

const receipt = await txResponse.getReceipt(client);

let newExchangeRate;
if (receipt.exchangeRate) {
newExchangeRate = {
...receipt.exchangeRate,
expirationTime: Utils.timestampToString(
receipt.exchangeRate.expirationTime,
),
};
}

return {
status: receipt.status.toString(),
accountId: receipt.accountId ? receipt.accountId.toString() : '',
fileId: receipt.fileId ? receipt.fileId : '',
contractId: receipt.contractId ? receipt.contractId : '',
topicId: receipt.topicId ? receipt.topicId : '',
tokenId: receipt.tokenId ? receipt.tokenId : '',
scheduleId: receipt.scheduleId ? receipt.scheduleId : '',
exchangeRate: newExchangeRate,
topicSequenceNumber: receipt.topicSequenceNumber
? String(receipt.topicSequenceNumber)
: '',
topicRunningHash: CryptoUtils.uint8ArrayToHex(receipt.topicRunningHash),
totalSupply: receipt.totalSupply ? String(receipt.totalSupply) : '',
scheduledTransactionId: receipt.scheduledTransactionId
? receipt.scheduledTransactionId.toString()
: '',
serials: JSON.parse(JSON.stringify(receipt.serials)),
duplicates: JSON.parse(JSON.stringify(receipt.duplicates)),
children: JSON.parse(JSON.stringify(receipt.children)),
} as TxReceipt;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AccountId, Client, TokenDissociateTransaction } from '@hashgraph/sdk';
import { TxReceipt } from '../types/hedera';
import { Utils } from '../utils/Utils';
import { CryptoUtils } from '../utils/CryptoUtils';
import { TxReceipt } from '../../types/hedera';
import { Utils } from '../../utils/Utils';
import { CryptoUtils } from '../../utils/CryptoUtils';

export class DissociateTokensCommand {
readonly #tokenIds: string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
*/

import { Client, TokenMintTransaction } from '@hashgraph/sdk';
import { TxReceipt } from '../types/hedera';
import { CryptoUtils } from '../utils/CryptoUtils';
import { Utils } from '../utils/Utils';
import { TxReceipt } from '../../types/hedera';
import { CryptoUtils } from '../../utils/CryptoUtils';
import { Utils } from '../../utils/Utils';

export class MintTokenCommand {
readonly #assetType: 'TOKEN' | 'NFT';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@
*
*/

import { WalletSnapParams, SnapDialogParams } from '../types/state';
import { AssociateTokensRequestParams } from '../types/params';
import { TxReceipt } from '../types/hedera';
import { WalletSnapParams, SnapDialogParams } from '../../types/state';
import { AssociateTokensRequestParams } from '../../types/params';
import { TxReceipt } from '../../types/hedera';
import { divider, heading, text } from '@metamask/snaps-ui';
import { CryptoUtils } from '../utils/CryptoUtils';
import { CryptoUtils } from '../../utils/CryptoUtils';
import _ from 'lodash';
import { SnapUtils } from '../utils/SnapUtils';
import { SnapUtils } from '../../utils/SnapUtils';
import { providerErrors } from '@metamask/rpc-errors';
import { HederaClientImplFactory } from '../client/HederaClientImplFactory';
import { AssociateTokensCommand } from '../commands/AssociateTokensCommand';
import { HederaClientImplFactory } from '../../client/HederaClientImplFactory';
import { AssociateTokensCommand } from '../../commands/hts/AssociateTokensCommand';

export class AssociateTokensFacade {
/**
Expand Down
Loading

0 comments on commit 9f4cb35

Please sign in to comment.