import { ethers } from 'ethers';
import { getSubAccountId } from './authentication';
/**
* Withdraw USDC collateral from LogX Network
* @param {number} chainId - Destination chain ID
* @param {string} address - User's Ethereum address
* @param {string} withdrawAmount - Amount to withdraw
* @returns {Promise<object>} Withdrawal result
*/
async function withdrawCollateral(chainId, address, withdrawAmount) {
try {
// Constants
const API_BASE_URL = 'https://mainnetapiserverwriter.logx.network';
const LOGX_CHAIN_ID = 1337;
const ENDPOINT_CONTRACT_ADDRESS = '0xBC87C2397601391E66adeC581786dF3F8eeE6124';
// USDC product ID for ARB USDC on LogX Network
const USDC_PRODUCT_ID = 4;
// Get authentication session data
const {
sessionKey, // Private key for signing
logx_key, // LogX API key
logx_secret, // LogX API secret
subAccountIdString,
subAccountIdHash,
nonce,
publicKey, // Public key for the session
} = await getAuthSessionData(address);
// Prepare the message for EIP-712 signing
const message = {
subAccountId: subAccountIdHash,
sessionKey: publicKey,
productId: USDC_PRODUCT_ID,
amount: withdrawAmount,
nonce,
destinationChainId: chainId,
receiver: address,
chainId: LOGX_CHAIN_ID,
};
// Define the domain for EIP-712 signature
const domain = {
name: 'LogX',
version: '1',
chainId: LOGX_CHAIN_ID,
verifyingContract: ENDPOINT_CONTRACT_ADDRESS,
};
// Sign message with ethers
const signer = new ethers.Wallet(sessionKey);
// Define types for EIP-712 signing
const typeDefinition = {
WithdrawCollateral: [
{ name: 'subAccountId', type: 'bytes32' },
{ name: 'sessionKey', type: 'address' },
{ name: 'productId', type: 'uint32' },
{ name: 'amount', type: 'uint128' },
{ name: 'nonce', type: 'uint128' },
{ name: 'destinationChainId', type: 'uint256' },
{ name: 'receiver', type: 'address' },
{ name: 'chainId', type: 'uint256' },
]
};
const signingSignature = await signer.signTypedData(
domain,
typeDefinition,
message
);
console.log(`Sending withdrawal request for ${withdrawAmount} USDC...`);
// Send API request
const response = await fetch(
`${API_BASE_URL}/api/v1/token/withdrawCollateral`,
{
method: 'POST',
body: JSON.stringify({
subAccountId: subAccountIdString,
sessionKey: publicKey,
productId: USDC_PRODUCT_ID,
amount: withdrawAmount,
nonce,
destinationChainId: chainId,
receiver: address,
chainId: LOGX_CHAIN_ID,
}),
headers: {
'Content-Type': 'application/json',
'broker-id': '1',
'logx-signer-address': publicKey,
'logx-user-address': address,
'logx-timestamp': new Date().getTime().toString(),
'logx-key': logx_key,
'logx-secret': logx_secret,
'logx-signature': signingSignature,
},
}
);
// Handle API errors
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`Failed to withdraw: ${errorData.message || response.statusText}`);
}
// Process successful response
const result = await response.json();
console.log(`Withdrawal initiated successfully. Transaction ID: ${result.body?.txId || 'N/A'}`);
console.log(`Your ${withdrawAmount} USDC should reflect on your destination chain in a few minutes`);
return result;
} catch (error) {
console.error("Error during withdrawal:", error);
throw error;
}
}