Add solana bridge CLI
Change-Id: I79f7abdb7472c63b3a03f4e3c2ede70953a5037a
This commit is contained in:
parent
dfdf31dcce
commit
2a6f7eaa0e
|
@ -0,0 +1,256 @@
|
|||
import yargs from "yargs";
|
||||
|
||||
const {hideBin} = require('yargs/helpers')
|
||||
import * as bridge from "bridge";
|
||||
import * as web3 from '@solana/web3.js';
|
||||
import {PublicKey, Transaction, TransactionInstruction, AccountMeta, Keypair, Connection} from "@solana/web3.js";
|
||||
import {post_message_ix} from "bridge";
|
||||
|
||||
yargs(hideBin(process.argv))
|
||||
.command('post_message [nonce] [message] [consistency]', 'post a message', (yargs) => {
|
||||
return yargs
|
||||
.positional('nonce', {
|
||||
describe: 'nonce of the message',
|
||||
type: "number",
|
||||
required: true
|
||||
})
|
||||
.positional('message', {
|
||||
describe: 'message to post',
|
||||
type: "string",
|
||||
required: true
|
||||
})
|
||||
.positional('consistency', {
|
||||
describe: 'confirmation level that this message requires <CONFIRMED|FINALIZED>',
|
||||
type: "string",
|
||||
required: true
|
||||
})
|
||||
}, async (argv: any) => {
|
||||
let connection = setupConnection(argv);
|
||||
let bridge_id = new PublicKey(argv.bridge);
|
||||
|
||||
// Generate a new random public key
|
||||
let from = web3.Keypair.generate();
|
||||
let emitter = web3.Keypair.generate();
|
||||
let airdropSignature = await connection.requestAirdrop(
|
||||
from.publicKey,
|
||||
web3.LAMPORTS_PER_SOL,
|
||||
);
|
||||
await connection.confirmTransaction(airdropSignature);
|
||||
|
||||
let fee_acc = await bridge.fee_collector_address(bridge_id.toString());
|
||||
let bridge_state = await get_bridge_state(connection, bridge_id);
|
||||
let transferIx = web3.SystemProgram.transfer({
|
||||
fromPubkey: from.publicKey,
|
||||
toPubkey: new PublicKey(fee_acc),
|
||||
lamports: bridge_state.config.fee,
|
||||
});
|
||||
|
||||
if (argv.consistency !== "CONFIRMED" && argv.consistency !== "FINALIZED") {
|
||||
throw new Error("invalid consistency level")
|
||||
}
|
||||
|
||||
let ix = ixFromRust(post_message_ix(bridge_id.toString(), from.publicKey.toString(), emitter.publicKey.toString(), argv.nonce, Buffer.from(argv.message, "hex"), argv.consistency));
|
||||
// Add transfer instruction to transaction
|
||||
let transaction = new web3.Transaction().add(transferIx, ix);
|
||||
|
||||
// Sign transaction, broadcast, and confirm
|
||||
let signature = await web3.sendAndConfirmTransaction(
|
||||
connection,
|
||||
transaction,
|
||||
[from, emitter],
|
||||
{
|
||||
skipPreflight: true
|
||||
}
|
||||
);
|
||||
console.log('SIGNATURE', signature);
|
||||
})
|
||||
.command('post_vaa [vaa]', 'post a VAA on Solana', (yargs) => {
|
||||
return yargs
|
||||
.positional('vaa', {
|
||||
describe: 'vaa to post',
|
||||
type: "string",
|
||||
required: true
|
||||
})
|
||||
}, async (argv: any) => {
|
||||
let connection = setupConnection(argv);
|
||||
let bridge_id = new PublicKey(argv.bridge);
|
||||
|
||||
// Generate a new random public key
|
||||
let from = web3.Keypair.generate();
|
||||
let airdropSignature = await connection.requestAirdrop(
|
||||
from.publicKey,
|
||||
web3.LAMPORTS_PER_SOL,
|
||||
);
|
||||
await connection.confirmTransaction(airdropSignature);
|
||||
|
||||
let vaa = Buffer.from(argv.vaa, "hex");
|
||||
await post_vaa(connection, bridge_id, from, vaa);
|
||||
})
|
||||
.command('execute_governance_vaa [vaa]', 'execute a governance VAA on Solana', (yargs) => {
|
||||
return yargs
|
||||
.positional('vaa', {
|
||||
describe: 'vaa to post',
|
||||
type: "string",
|
||||
required: true
|
||||
})
|
||||
}, async (argv: any) => {
|
||||
let connection = setupConnection(argv);
|
||||
let bridge_id = new PublicKey(argv.bridge);
|
||||
|
||||
// Generate a new random public key
|
||||
let from = web3.Keypair.generate();
|
||||
let airdropSignature = await connection.requestAirdrop(
|
||||
from.publicKey,
|
||||
web3.LAMPORTS_PER_SOL,
|
||||
);
|
||||
await connection.confirmTransaction(airdropSignature);
|
||||
|
||||
let vaa = Buffer.from(argv.vaa, "hex");
|
||||
await post_vaa(connection, bridge_id, from, vaa);
|
||||
|
||||
let parsed_vaa = await bridge.parse_vaa(vaa);
|
||||
let ix: TransactionInstruction;
|
||||
switch (parsed_vaa.payload[32]) {
|
||||
case 1:
|
||||
console.log("Upgrading contract")
|
||||
ix = bridge.upgrade_contract_ix(bridge_id.toString(), from.publicKey.toString(), from.publicKey.toString(), vaa);
|
||||
break
|
||||
case 2:
|
||||
console.log("Updating guardian set")
|
||||
ix = bridge.update_guardian_set_ix(bridge_id.toString(), from.publicKey.toString(), vaa);
|
||||
break
|
||||
case 3:
|
||||
console.log("Setting fees")
|
||||
ix = bridge.set_fees_ix(bridge_id.toString(), from.publicKey.toString(), vaa);
|
||||
break
|
||||
case 4:
|
||||
console.log("Transferring fees")
|
||||
ix = bridge.transfer_fees_ix(bridge_id.toString(), from.publicKey.toString(), vaa);
|
||||
break
|
||||
default:
|
||||
throw new Error("unknown governance action")
|
||||
}
|
||||
let transaction = new web3.Transaction().add(ixFromRust(ix));
|
||||
|
||||
// Sign transaction, broadcast, and confirm
|
||||
let signature = await web3.sendAndConfirmTransaction(
|
||||
connection,
|
||||
transaction,
|
||||
[from],
|
||||
{
|
||||
skipPreflight: true
|
||||
}
|
||||
);
|
||||
console.log('SIGNATURE', signature);
|
||||
})
|
||||
.option('rpc', {
|
||||
alias: 'u',
|
||||
type: 'string',
|
||||
description: 'URL of the Solana RPC',
|
||||
default: "http://localhost:8899"
|
||||
})
|
||||
.option('bridge', {
|
||||
alias: 'b',
|
||||
type: 'string',
|
||||
description: 'Bridge address',
|
||||
default: "Bridge1p5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o"
|
||||
})
|
||||
.argv;
|
||||
|
||||
async function post_vaa(connection: Connection, bridge_id: PublicKey, payer: Keypair, vaa: Buffer) {
|
||||
let bridge_state = await get_bridge_state(connection, bridge_id);
|
||||
let guardian_addr = new PublicKey(bridge.guardian_set_address(bridge_id.toString(), bridge_state.guardian_set_index));
|
||||
let acc = await connection.getAccountInfo(guardian_addr);
|
||||
if (acc?.data === undefined) {
|
||||
return
|
||||
}
|
||||
let guardian_data = bridge.parse_guardian_set(new Uint8Array(acc?.data));
|
||||
|
||||
let signature_set = Keypair.generate();
|
||||
let txs = bridge.verify_signatures_ix(bridge_id.toString(), payer.publicKey.toString(), bridge_state.guardian_set_index, guardian_data, signature_set.publicKey.toString(), vaa)
|
||||
// Add transfer instruction to transaction
|
||||
for (let tx of txs) {
|
||||
let ixs: Array<TransactionInstruction> = tx.map((v: any) => {
|
||||
return ixFromRust(v)
|
||||
})
|
||||
let transaction = new web3.Transaction().add(ixs[0], ixs[1]);
|
||||
|
||||
// Sign transaction, broadcast, and confirm
|
||||
await web3.sendAndConfirmTransaction(
|
||||
connection,
|
||||
transaction,
|
||||
[payer, signature_set],
|
||||
{
|
||||
skipPreflight: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let ix = ixFromRust(bridge.post_vaa_ix(bridge_id.toString(), payer.publicKey.toString(), signature_set.publicKey.toString(), vaa));
|
||||
let transaction = new web3.Transaction().add(ix);
|
||||
|
||||
// Sign transaction, broadcast, and confirm
|
||||
let signature = await web3.sendAndConfirmTransaction(
|
||||
connection,
|
||||
transaction,
|
||||
[payer],
|
||||
{
|
||||
skipPreflight: true
|
||||
}
|
||||
);
|
||||
console.log('SIGNATURE', signature);
|
||||
}
|
||||
|
||||
async function get_bridge_state(connection: Connection, bridge_id: PublicKey): Promise<BridgeState> {
|
||||
let bridge_state = new PublicKey(bridge.state_address(bridge_id.toString()));
|
||||
let acc = await connection.getAccountInfo(bridge_state);
|
||||
if (acc?.data === undefined) {
|
||||
throw new Error("bridge state not found")
|
||||
}
|
||||
return bridge.parse_state(new Uint8Array(acc?.data));
|
||||
}
|
||||
|
||||
function setupConnection(argv: yargs.Arguments): web3.Connection {
|
||||
return new web3.Connection(
|
||||
argv.rpc as string,
|
||||
'confirmed',
|
||||
);
|
||||
}
|
||||
|
||||
function ixFromRust(data: any): TransactionInstruction {
|
||||
let keys: Array<AccountMeta> = data.accounts.map(accountMetaFromRust)
|
||||
return new TransactionInstruction({
|
||||
programId: new PublicKey(data.program_id),
|
||||
data: Buffer.from(data.data),
|
||||
keys: keys,
|
||||
})
|
||||
}
|
||||
|
||||
function accountMetaFromRust(meta: any): AccountMeta {
|
||||
return {
|
||||
pubkey: new PublicKey(meta.pubkey),
|
||||
isSigner: meta.is_signer,
|
||||
isWritable: meta.is_writable,
|
||||
}
|
||||
}
|
||||
|
||||
interface BridgeState {
|
||||
// The current guardian set index, used to decide which signature sets to accept.
|
||||
guardian_set_index: number,
|
||||
|
||||
// Lamports in the collection account
|
||||
last_lamports: number,
|
||||
|
||||
// Bridge configuration, which is set once upon initialization.
|
||||
config: BridgeConfig,
|
||||
}
|
||||
|
||||
interface BridgeConfig {
|
||||
// Period for how long a guardian set is valid after it has been replaced by a new one. This
|
||||
// guarantees that VAAs issued by that set can still be submitted for a certain period. In
|
||||
// this period we still trust the old guardian set.
|
||||
guardian_set_expiration_time: number,
|
||||
|
||||
// Amount of lamports that needs to be paid to the protocol to post a message
|
||||
fee: number,
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"name": "wormhole-client-solana",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@solana/web3.js": "^1.22.0",
|
||||
"bn.js": "^5.2.0",
|
||||
"bs58": "^4.0.1",
|
||||
"buffer-layout": "^1.2.2",
|
||||
"npm": "^7.20.0",
|
||||
"yargs": "^17.0.1"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "tsc && node main.js",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bs58": "^4.0.1",
|
||||
"@types/bn.js": "^5.1.0",
|
||||
"@types/yargs": "^17.0.2",
|
||||
"bridge": "file:./pkg",
|
||||
"typescript": "^4.3.5"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Basic Options */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
|
||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
||||
// "lib": [], /* Specify library files to be included in the compilation. */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||
// "sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
// "outDir": "./", /* Redirect output structure to the directory. */
|
||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
// "composite": true, /* Enable project compilation */
|
||||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
||||
// "removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
||||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "types": [], /* Type declaration files to be included in compilation. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
|
||||
/* Advanced Options */
|
||||
"skipLibCheck": true, /* Skip type checking of declaration files. */
|
||||
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue