|
| 1 | +import { walletClient, exchClient, infoClient } from "../../../config.js"; |
| 2 | +import type { getStakingInput, getUnstakingInput } from "./schemas.js"; |
| 3 | + |
| 4 | +export async function performStaking(stakingDetails: getStakingInput) { |
| 5 | + try { |
| 6 | + const validators = await infoClient.validatorSummaries(); |
| 7 | + |
| 8 | + const validator = validators.find( |
| 9 | + v => v.validator === stakingDetails.validatorAddress |
| 10 | + ); |
| 11 | + |
| 12 | + if (!validator) { |
| 13 | + throw new Error(`Validator ${stakingDetails.validatorAddress} not found`); |
| 14 | + } |
| 15 | + |
| 16 | + const amountScaled = Number( |
| 17 | + (parseFloat(stakingDetails.amountToStake) * 1e8).toFixed(0) |
| 18 | + ); |
| 19 | + |
| 20 | + const depositResult = await exchClient.cDeposit({ |
| 21 | + wei: amountScaled, |
| 22 | + }); |
| 23 | + |
| 24 | + if (depositResult.status !== "ok") { |
| 25 | + throw new Error(`Deposit failed: ${JSON.stringify(depositResult)}`); |
| 26 | + } |
| 27 | + |
| 28 | + // Wait for deposit to process |
| 29 | + await new Promise(resolve => setTimeout(resolve, 3000)); |
| 30 | + |
| 31 | + const delegationResult = await exchClient.tokenDelegate({ |
| 32 | + validator: stakingDetails.validatorAddress, |
| 33 | + wei: amountScaled, |
| 34 | + isUndelegate: false, |
| 35 | + }); |
| 36 | + |
| 37 | + if (delegationResult.status !== "ok") { |
| 38 | + throw new Error(`Delegation failed: ${JSON.stringify(delegationResult)}`); |
| 39 | + } |
| 40 | + |
| 41 | + const userAddress = walletClient.account?.address; |
| 42 | + if (!userAddress) { |
| 43 | + throw new Error("Failed to load wallet client account"); |
| 44 | + } |
| 45 | + |
| 46 | + const updatedDelegations = await infoClient.delegations({ |
| 47 | + user: userAddress, |
| 48 | + }); |
| 49 | + |
| 50 | + const newDelegation = updatedDelegations.find( |
| 51 | + d => d.validator === stakingDetails.validatorAddress |
| 52 | + ); |
| 53 | + |
| 54 | + return { |
| 55 | + content: [ |
| 56 | + { |
| 57 | + type: "text", |
| 58 | + text: `Staking successful!\nValidator: ${validator.name}\nAmount Staked: ${stakingDetails.amountToStake} HYPE\nTotal Delegated to Validator: ${newDelegation?.amount || "0"} HYPE\nDeposit TX: ${depositResult.response?.type}\nDelegation TX: ${delegationResult.response?.type}`, |
| 59 | + }, |
| 60 | + ], |
| 61 | + }; |
| 62 | + } catch (error) { |
| 63 | + console.error("Error performing staking:", error); |
| 64 | + throw new Error( |
| 65 | + `Failed to perform staking: ${error instanceof Error ? error.message : String(error)}` |
| 66 | + ); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +export async function performUnstaking(unstakingDetails: getUnstakingInput) { |
| 71 | + try { |
| 72 | + const userAddress = walletClient.account?.address; |
| 73 | + if (!userAddress) { |
| 74 | + throw new Error("Failed to load wallet client account"); |
| 75 | + } |
| 76 | + const currentDelegations = await infoClient.delegations({ |
| 77 | + user: userAddress, |
| 78 | + }); |
| 79 | + |
| 80 | + if (currentDelegations.length === 0) { |
| 81 | + throw new Error("No active delegations found to unstake from"); |
| 82 | + } |
| 83 | + |
| 84 | + const totalDelegated = currentDelegations.reduce( |
| 85 | + (sum, delegation) => |
| 86 | + sum + Number(parseFloat(delegation.amount).toFixed(8)), |
| 87 | + 0 |
| 88 | + ); |
| 89 | + |
| 90 | + const requestedAmount = parseFloat(unstakingDetails.amountToUnstake); |
| 91 | + |
| 92 | + if (requestedAmount > totalDelegated) { |
| 93 | + throw new Error( |
| 94 | + `Insufficient staked amount. Available: ${totalDelegated}, Requested: ${requestedAmount}` |
| 95 | + ); |
| 96 | + } |
| 97 | + |
| 98 | + let remainingToUnstake = requestedAmount; |
| 99 | + const undelegationResults = []; |
| 100 | + |
| 101 | + for (const delegation of currentDelegations) { |
| 102 | + if (remainingToUnstake <= 0) { |
| 103 | + break; |
| 104 | + } |
| 105 | + |
| 106 | + const delegatedAmount = parseFloat(delegation.amount); |
| 107 | + const amountToUndelegateFromThis = Math.min( |
| 108 | + remainingToUnstake, |
| 109 | + delegatedAmount |
| 110 | + ); |
| 111 | + const newUndelegatedAmountScaled = Number( |
| 112 | + (amountToUndelegateFromThis * 1e8).toFixed(0) |
| 113 | + ); |
| 114 | + |
| 115 | + const undelegateResult = await exchClient.tokenDelegate({ |
| 116 | + validator: delegation.validator, |
| 117 | + wei: newUndelegatedAmountScaled, |
| 118 | + isUndelegate: true, |
| 119 | + }); |
| 120 | + |
| 121 | + if (undelegateResult.status !== "ok") { |
| 122 | + throw new Error(`Failed to undelegate from ${delegation.validator}:`); |
| 123 | + } else { |
| 124 | + undelegationResults.push({ |
| 125 | + validator: delegation.validator, |
| 126 | + undelegatedAmount: amountToUndelegateFromThis, |
| 127 | + result: undelegateResult, |
| 128 | + }); |
| 129 | + remainingToUnstake -= amountToUndelegateFromThis; |
| 130 | + } |
| 131 | + |
| 132 | + // Small delay between undelegations |
| 133 | + await new Promise(resolve => setTimeout(resolve, 1000)); |
| 134 | + } |
| 135 | + |
| 136 | + if (remainingToUnstake > 0) { |
| 137 | + throw new Error( |
| 138 | + `Could not undelegate full amount. Remaining: ${remainingToUnstake}` |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + // Wait for undelegations to process |
| 143 | + await new Promise(resolve => setTimeout(resolve, 5000)); |
| 144 | + |
| 145 | + const amountScaledWithdraw = Number( |
| 146 | + (parseFloat(unstakingDetails.amountToUnstake) * 1e8).toFixed(0) |
| 147 | + ); |
| 148 | + |
| 149 | + const withdrawResult = await exchClient.cWithdraw({ |
| 150 | + wei: amountScaledWithdraw, |
| 151 | + }); |
| 152 | + |
| 153 | + if (withdrawResult.status !== "ok") { |
| 154 | + throw new Error(`Withdrawal failed: ${JSON.stringify(withdrawResult)}`); |
| 155 | + } |
| 156 | + |
| 157 | + const finalSummary = await infoClient.delegatorSummary({ |
| 158 | + user: userAddress, |
| 159 | + }); |
| 160 | + |
| 161 | + return { |
| 162 | + content: [ |
| 163 | + { |
| 164 | + type: "text", |
| 165 | + text: `Unstaking successful!\nAmount Unstaked: ${unstakingDetails.amountToUnstake} HYPE\nValidators Affected: ${undelegationResults.length}\nWithdrawal Status: ${withdrawResult.response?.type}\nRemaining Staked: ${finalSummary.delegated || "0"} HYPE\nAvailable in Staking Account: ${finalSummary.totalPendingWithdrawal || "0"} HYPE`, |
| 166 | + }, |
| 167 | + ], |
| 168 | + }; |
| 169 | + } catch (error) { |
| 170 | + console.error("Error performing unstaking:", error); |
| 171 | + throw new Error( |
| 172 | + `Failed to perform unstaking: ${error instanceof Error ? error.message : String(error)}` |
| 173 | + ); |
| 174 | + } |
| 175 | +} |
0 commit comments