This section assumes you have followed the instructions and run the code in the deposit funds example.
Call the withdraw function
Note that there is a fee for withdrawals, in our case, it should be 1 USDC. The amount sent to the withdraw function is exclusive of fee, hence depositAmount - toFixedPoint(1, 6)
Retrieve and log the subaccount balances using getSubaccountSummary. You should see that your balance for USDC (product ID of 0) is now 0.
Full example - deposit and withdraw
import { toFixedPoint } from '@vertex-protocol/utils';
import { getVertexClient, prettyPrintJson } from './common';
async function main() {
const vertexClient = getVertexClient();
const { walletClient, publicClient } = vertexClient.context;
// If you have access to `walletClient`, you can call `walletClient.account.address`
// directly instead of reaching into `vertexClient.context`
const address = walletClient!.account.address;
const subaccountName = 'default';
// 10 USDC (6 decimals)
const depositAmount = toFixedPoint(10, 6);
// TESTNET ONLY - Mint yourself some tokens
const mintTxHash = await vertexClient.spot._mintMockERC20({
amount: depositAmount,
productId: 0,
});
// Mint goes on-chain, so wait for confirmation
await publicClient.waitForTransactionReceipt({
hash: mintTxHash,
});
// Deposits require approval on the ERC20 token, this is on-chain as well
const approveTxHash = await vertexClient.spot.approveAllowance({
amount: depositAmount,
productId: 0,
});
await publicClient.waitForTransactionReceipt({
hash: approveTxHash,
});
// Now execute the deposit, which goes on-chain
const depositTxHash = await vertexClient.spot.deposit({
// Your choice of name for the subaccount, this subaccount will be credited with the deposit balance
subaccountName: 'default',
amount: depositAmount,
productId: 0,
});
await publicClient.waitForTransactionReceipt({
hash: depositTxHash,
});
await new Promise((resolve) => setTimeout(resolve, 10000));
// For on-chain state, you can use `getSubaccountSummary` - these should match up
const subaccountData =
await vertexClient.subaccount.getEngineSubaccountSummary({
subaccountOwner: address,
subaccountName,
});
prettyPrintJson('Subaccount Data After Deposit', subaccountData);
// Now withdraw your funds, this goes to the off-chain engine
// We're withdrawing less than 10 as there are withdrawal fees of 1 USDC
const withdrawTx = await vertexClient.spot.withdraw({
amount: depositAmount - toFixedPoint(1, 6),
productId: 0,
subaccountName,
});
prettyPrintJson('Withdraw Tx', withdrawTx);
// Your new subaccount summary should have zero balances
const subaccountDataAfterWithdraw =
await vertexClient.subaccount.getEngineSubaccountSummary({
subaccountOwner: address,
subaccountName,
});
prettyPrintJson(
'Subaccount Data After Withdrawal',
subaccountDataAfterWithdraw,
);
}
main();