import {
getKrakenAccounts,
getKrakenWhitelistedAddresses,
createKrakenExchangeTransfer,
} from '@dynamic-labs-sdk/client';
const findFundedAccount = ({ accounts, currency, amount }) => {
for (const account of accounts) {
const balance = account.balances.find(b => b.currency === currency);
if (!balance) continue;
// availableBalance is optional; fall back to the total balance.
const available = balance.availableBalance || balance.balance;
if (available >= amount) return account;
}
return undefined;
};
const executeTransfer = async ({ currency, amount, destinationAddress }) => {
// Step 1: Get accounts and verify balance
const accounts = await getKrakenAccounts();
const fundedAccount = findFundedAccount({ accounts, amount, currency });
if (!fundedAccount) {
throw new Error(
`Insufficient ${currency} balance. Requested: ${amount}`
);
}
// Step 2: Verify destination address is whitelisted (if required)
const { destinations, enforcesAddressWhitelist } =
await getKrakenWhitelistedAddresses();
if (enforcesAddressWhitelist) {
const isWhitelisted = destinations.some(
dest =>
dest.address.toLowerCase() === destinationAddress.toLowerCase() &&
dest.tokens?.includes(currency)
);
if (!isWhitelisted) {
throw new Error(
`Address ${destinationAddress} is not whitelisted for ${currency}. ` +
'Add it in your Kraken account settings.'
);
}
}
// Step 3: Create the transfer
const transfer = await createKrakenExchangeTransfer({
accountId: fundedAccount.id,
to: destinationAddress,
amount,
currency,
});
return {
success: true,
transferId: transfer.id,
status: transfer.status,
amount: transfer.amount,
currency: transfer.currency,
};
};
// Usage
try {
const result = await executeTransfer({
currency: 'ETH',
amount: 0.5,
destinationAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f7ABCD',
});
console.log('Transfer successful:', result);
} catch (error) {
console.error('Transfer failed:', error.message);
}