-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathindex.ts
234 lines (216 loc) · 7.7 KB
/
index.ts
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { parseVaa, postVaaSolana } from "@certusone/wormhole-sdk";
import { signTransactionFactory } from "@certusone/wormhole-sdk/lib/cjs/solana";
import { derivePostedVaaKey } from "@certusone/wormhole-sdk/lib/cjs/solana/wormhole";
import { AnchorProvider, BN, Program } from "@coral-xyz/anchor";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { AccountType, parseProductData } from "@pythnetwork/client";
import {
getPythClusterApiUrl,
PythCluster,
} from "@pythnetwork/client/lib/cluster";
import {
AccountMeta,
Commitment,
ComputeBudgetProgram,
Connection,
Keypair,
PublicKey,
TransactionInstruction,
} from "@solana/web3.js";
import * as fs from "fs";
import {
decodeGovernancePayload,
ExecutePostedVaa,
getCreateAccountWithSeedInstruction,
MultisigParser,
PythMultisigInstruction,
WORMHOLE_ADDRESS,
WORMHOLE_API_ENDPOINT,
CLAIM_RECORD_SEED,
mapKey,
REMOTE_EXECUTOR_ADDRESS,
envOrErr,
PriceStoreMultisigInstruction,
createDeterministicPublisherBufferAccountInstruction,
} from "@pythnetwork/xc-admin-common";
const CLUSTER: PythCluster = envOrErr("CLUSTER") as PythCluster;
const EMITTER: PublicKey = new PublicKey(envOrErr("EMITTER"));
const KEYPAIR: Keypair = Keypair.fromSecretKey(
Uint8Array.from(JSON.parse(fs.readFileSync(envOrErr("WALLET"), "ascii")))
);
const OFFSET: number = Number(process.env.OFFSET ?? "-1");
const SKIP_FAILED_REMOTE_INSTRUCTIONS: boolean =
process.env.SKIP_FAILED_REMOTE_INSTRUCTIONS == "true";
const COMMITMENT: Commitment =
(process.env.COMMITMENT as Commitment) ?? "confirmed";
const GUARDIAN_RPC = process.env.GUARDIAN_RPC;
const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL;
async function run() {
const provider = new AnchorProvider(
new Connection(SOLANA_RPC_URL ?? getPythClusterApiUrl(CLUSTER), COMMITMENT),
new NodeWallet(KEYPAIR),
{
commitment: COMMITMENT,
preflightCommitment: COMMITMENT,
}
);
const multisigParser = MultisigParser.fromCluster(CLUSTER);
const remoteExecutor = await Program.at(REMOTE_EXECUTOR_ADDRESS, provider);
const claimRecordAddress: PublicKey = PublicKey.findProgramAddressSync(
[Buffer.from(CLAIM_RECORD_SEED), EMITTER.toBuffer()],
remoteExecutor.programId
)[0];
const executorKey: PublicKey = mapKey(EMITTER);
const claimRecord = await remoteExecutor.account.claimRecord.fetchNullable(
claimRecordAddress
);
let lastSequenceNumber: number = claimRecord
? (claimRecord.sequence as BN).toNumber()
: -1;
lastSequenceNumber = Math.max(lastSequenceNumber, OFFSET);
const wormholeApi = GUARDIAN_RPC ?? WORMHOLE_API_ENDPOINT[CLUSTER];
const productAccountToSymbol: { [key: string]: string } = {};
while (true) {
lastSequenceNumber += 1;
console.log(`Trying sequence number : ${lastSequenceNumber}`);
const response = await (
await fetch(
`${wormholeApi}/v1/signed_vaa/1/${EMITTER.toBuffer().toString(
"hex"
)}/${lastSequenceNumber}`
)
).json();
if (response.vaaBytes) {
const vaa = parseVaa(Buffer.from(response.vaaBytes, "base64"));
const governancePayload = decodeGovernancePayload(vaa.payload);
if (
governancePayload instanceof ExecutePostedVaa &&
governancePayload.targetChainId == "pythnet"
) {
const preInstructions: TransactionInstruction[] = [];
console.log(`Found VAA ${lastSequenceNumber}, relaying vaa ...`);
await postVaaSolana(
provider.connection,
signTransactionFactory(KEYPAIR),
WORMHOLE_ADDRESS[CLUSTER]!,
provider.wallet.publicKey,
Buffer.from(response.vaaBytes, "base64"),
{ commitment: COMMITMENT }
);
console.log(`VAA ${lastSequenceNumber} relayed. executing ...`);
let extraAccountMetas: AccountMeta[] = [
{ pubkey: executorKey, isSigner: false, isWritable: true },
];
for (const ix of governancePayload.instructions) {
extraAccountMetas.push({
pubkey: ix.programId,
isSigner: false,
isWritable: false,
});
extraAccountMetas.push(
...ix.keys.filter((acc) => {
return !acc.pubkey.equals(executorKey);
})
);
const parsedInstruction = multisigParser.parseInstruction(ix);
console.log("Parsed instruction:");
console.dir(parsedInstruction, { depth: null });
if (
parsedInstruction instanceof PythMultisigInstruction &&
parsedInstruction.name == "addProduct"
) {
preInstructions.push(
await getCreateAccountWithSeedInstruction(
provider.connection,
CLUSTER,
provider.wallet.publicKey,
parsedInstruction.args.symbol,
AccountType.Product
)
);
productAccountToSymbol[
parsedInstruction.accounts.named.productAccount.pubkey.toBase58()
] = parsedInstruction.args.symbol;
} else if (
parsedInstruction instanceof PythMultisigInstruction &&
parsedInstruction.name == "addPrice"
) {
const productAccount = await provider.connection.getAccountInfo(
parsedInstruction.accounts.named.productAccount.pubkey
);
const productSymbol = productAccount
? parseProductData(productAccount.data).product.symbol
: productAccountToSymbol[
parsedInstruction.accounts.named.productAccount.pubkey.toBase58()
];
if (productSymbol) {
preInstructions.push(
await getCreateAccountWithSeedInstruction(
provider.connection,
CLUSTER,
provider.wallet.publicKey,
productSymbol,
AccountType.Price
)
);
} else {
throw Error("Product account not found");
}
} else if (
parsedInstruction instanceof PriceStoreMultisigInstruction &&
parsedInstruction.name == "InitializePublisher"
) {
preInstructions.push(
await createDeterministicPublisherBufferAccountInstruction(
provider.connection,
provider.wallet.publicKey,
parsedInstruction.args.publisherKey
)
);
}
}
try {
await remoteExecutor.methods
.executePostedVaa()
.accounts({
claimRecord: claimRecordAddress,
postedVaa: derivePostedVaaKey(
WORMHOLE_ADDRESS[CLUSTER]!,
vaa.hash
),
})
.remainingAccounts(extraAccountMetas)
.preInstructions(preInstructions)
// Use a high compute unit limit to avoid running out of compute units
// as some operations can use a lot of compute units.
.postInstructions([
ComputeBudgetProgram.setComputeUnitLimit({ units: 1000000 }),
])
.rpc({ skipPreflight: false });
} catch (e) {
if (SKIP_FAILED_REMOTE_INSTRUCTIONS) {
console.error(e);
} else throw e;
}
}
} else if (response.code == 5) {
console.log(`All VAAs have been relayed`);
console.log(
`${wormholeApi}/v1/signed_vaa/1/${EMITTER.toBuffer().toString(
"hex"
)}/${lastSequenceNumber}`
);
break;
} else {
throw new Error("Could not connect to wormhole api");
}
}
}
(async () => {
try {
await run();
} catch (err) {
console.error(err);
throw new Error();
}
})();