-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathunassign.ts
More file actions
196 lines (171 loc) · 6.09 KB
/
Copy pathunassign.ts
File metadata and controls
196 lines (171 loc) · 6.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { publicProcedure } from "@/server/api/procedures";
import { createSolanaConnection, getCluster } from "@/lib/solana";
import {
generateTransactionTag,
TRANSACTION_TYPES,
} from "@/lib/utils/transaction-tags";
import { getTotalTransactionFees } from "@/lib/utils/balance-validation";
import { getJitoTipAmountLamports } from "@/lib/utils/jito";
import { toTokenAmountOutput } from "@/lib/utils/token-math";
import {
requirePositionOwnershipWithMessage,
buildBatchedTransactions,
} from "../helpers";
import type { InstructionGroup } from "../helpers";
import { init as initProxy, proxyAssignmentKey } from "@helium/nft-proxy-sdk";
import { init as initVsr, positionKey } from "@helium/voter-stake-registry-sdk";
import { getAssociatedTokenAddressSync, NATIVE_MINT } from "@solana/spl-token";
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
import BN from "bn.js";
export const unassign = publicProcedure.governance.unassignProxies.handler(
async ({ input, errors }) => {
const { walletAddress, proxyKey, positionMints } = input;
const { connection, provider } = createSolanaConnection(walletAddress);
const walletPubkey = new PublicKey(walletAddress);
const proxyKeyPubkey = new PublicKey(proxyKey);
const vsrProgram = await initVsr(provider);
const proxyProgram = await initProxy(provider);
const positionMintPubkeys = positionMints.map((m) => new PublicKey(m));
const positionPubkeys = positionMintPubkeys.map((m) => positionKey(m)[0]);
const positionAccounts =
await vsrProgram.account.positionV0.fetchMultiple(positionPubkeys);
const registrarCache = new Map<
string,
Awaited<ReturnType<typeof vsrProgram.account.registrar.fetch>>
>();
const allInstructions: TransactionInstruction[][] = [];
for (let i = 0; i < positionMints.length; i++) {
const positionMintPubkey = positionMintPubkeys[i];
const positionAcc = positionAccounts[i];
if (!positionAcc) {
throw errors.NOT_FOUND({
message: `Position ${positionMints[i]} not found`,
});
}
await requirePositionOwnershipWithMessage(
connection,
positionMintPubkey,
walletPubkey,
positionMints[i],
errors,
);
const registrarKey = positionAcc.registrar.toBase58();
let registrar = registrarCache.get(registrarKey);
if (!registrar) {
registrar = await vsrProgram.account.registrar.fetch(
positionAcc.registrar,
);
registrarCache.set(registrarKey, registrar);
}
const proxyConfig = registrar.proxyConfig;
const ownedAssetProxyAssignmentAddress = proxyAssignmentKey(
proxyConfig,
positionMintPubkey,
PublicKey.default,
)[0];
const baseAssignment =
await proxyProgram.account.proxyAssignmentV0.fetchNullable(
ownedAssetProxyAssignmentAddress,
);
if (
!baseAssignment ||
baseAssignment.nextVoter.equals(PublicKey.default)
) {
continue;
}
const chain: { address: PublicKey; voter: PublicKey }[] = [];
let currentVoter = baseAssignment.nextVoter;
while (!currentVoter.equals(PublicKey.default)) {
const addr = proxyAssignmentKey(
proxyConfig,
positionMintPubkey,
currentVoter,
)[0];
chain.push({ address: addr, voter: currentVoter });
const acc =
await proxyProgram.account.proxyAssignmentV0.fetchNullable(addr);
if (!acc) break;
currentVoter = acc.nextVoter;
}
const targetIndex = chain.findIndex((c) =>
c.voter.equals(proxyKeyPubkey),
);
if (targetIndex === -1) {
continue;
}
const prevAddress =
targetIndex === 0
? ownedAssetProxyAssignmentAddress
: chain[targetIndex - 1].address;
allInstructions.push([
await proxyProgram.methods
.unassignProxyV0()
.accountsPartial({
asset: positionMintPubkey,
prevProxyAssignment: prevAddress,
currentProxyAssignment: ownedAssetProxyAssignmentAddress,
proxyAssignment: chain[targetIndex].address,
voter: PublicKey.default,
approver: walletPubkey,
tokenAccount: getAssociatedTokenAddressSync(
positionMintPubkey,
walletPubkey,
),
})
.instruction(),
]);
}
const groups: InstructionGroup[] = allInstructions.map((instructions) => ({
instructions,
metadata: {
type: "proxy_unassign",
description: `Remove voting proxy ${proxyKey.slice(0, 8)}...`,
},
}));
if (groups.length === 0) {
throw errors.BAD_REQUEST({
message:
"No proxy assignments to remove - positions have no active proxy for this key",
});
}
const { transactions, versionedTransactions, hasMore } =
await buildBatchedTransactions({
groups,
connection,
feePayer: walletPubkey,
});
const cluster = getCluster();
const jitoTipCost =
(cluster === "mainnet" || cluster === "mainnet-beta") &&
versionedTransactions.length > 1
? getJitoTipAmountLamports()
: 0;
const totalFee = getTotalTransactionFees(versionedTransactions) + jitoTipCost;
const walletBalance = await connection.getBalance(walletPubkey);
if (walletBalance < totalFee) {
throw errors.INSUFFICIENT_FUNDS({
message: "Insufficient SOL balance for transaction fees",
data: { required: totalFee, available: walletBalance },
});
}
const tag = generateTransactionTag({
type: TRANSACTION_TYPES.PROXY_UNASSIGN,
walletAddress,
proxyKey,
positionCount: positionMints.length,
});
return {
transactionData: {
transactions,
parallel: true,
tag,
actionMetadata: { type: "proxy_unassign", proxyKey, positionCount: positionMints.length },
},
hasMore,
estimatedSolFee: await toTokenAmountOutput(
new BN(totalFee),
NATIVE_MINT.toBase58(),
),
};
},
);