Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Local and Ledger wallet support #167

Merged
merged 6 commits into from
Feb 2, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 37 additions & 22 deletions gauntlet/packages/gauntlet-serum-multisig/src/commands/multisig.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SolanaCommand, RawTransaction } from '@chainlink/gauntlet-solana'
import { logger, BN, prompt } from '@chainlink/gauntlet-core/dist/utils'
import { PublicKey, SYSVAR_RENT_PUBKEY, Keypair, AccountMeta, Transaction } from '@solana/web3.js'
import { PublicKey, SYSVAR_RENT_PUBKEY, Keypair, AccountMeta, SystemProgram } from '@solana/web3.js'
import { CONTRACT_LIST, getContract, makeTx } from '@chainlink/gauntlet-solana-contracts'
import { Idl, Program } from '@project-serum/anchor'
import { MAX_BUFFER_SIZE } from '../lib/constants'
Expand All @@ -26,32 +26,30 @@ export const wrapCommand = (command) => {
logger.info(`Running ${command.id} command using Serum Multisig`)

this.command = new command({ ...flags, bufferSize: MAX_BUFFER_SIZE }, args)
this.command.invokeMiddlewares(this.command, this.command.middlewares)
this.require(!!process.env.MULTISIG_ADDRESS, 'Please set MULTISIG_ADDRESS env var')
this.multisigAddress = new PublicKey(process.env.MULTISIG_ADDRESS)
}

execute = async () => {
// TODO: Command underneath will try to load its own provider and wallet if invoke middlewares, but we should be able to specify which ones to use, in an obvious better way
this.command.provider = this.provider
this.command.wallet = this.wallet

const multisig = getContract(CONTRACT_LIST.MULTISIG, '')
this.program = this.loadProgram(multisig.idl, multisig.programId.toString())

// Falling back on default wallet if signer is not provided or execute flag is provided
const signer = this.flags.execute
? this.wallet.payer.publicKey
: new PublicKey(this.flags.signer || this.wallet.payer.publicKey)
// If execute flag is provided, a signer cannot, as the Keypair is required
const isInvalidSigner = !!this.flags.execute && !!this.flags.signer
this.require(!isInvalidSigner, 'To execute the transaction the signer must be loaded from a wallet')
const signer = new PublicKey(this.flags.signer || this.wallet.publicKey)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not executing but preparing a rawTx for a specific signer - Do we even need this functionality anymore?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need it

const rawTxs = await this.makeRawTransaction(signer)
// If proposal is not provided, we are at creation time, and a new proposal acc should have been created
const proposal = new PublicKey(this.flags.proposal || rawTxs[0].accounts[1].pubkey)
const latestSlot = await this.provider.connection.getSlot()
const recentBlock = await this.provider.connection.getBlock(latestSlot)
const tx = makeTx(rawTxs, {
recentBlockhash: recentBlock.blockhash,
feePayer: signer,
})

if (this.flags.execute) {
await prompt('CREATION,APPROVAL or EXECUTION TX will be executed. Continue?')
logger.loading(`Executing action...`)
const txhash = await this.provider.send(tx, [this.wallet.payer])
const txhash = await this.withIDL(this.signAndSendRawTx, this.program.idl)(rawTxs)
await this.inspectProposalState(proposal)
return {
responses: [
Expand All @@ -63,15 +61,22 @@ export const wrapCommand = (command) => {
}
}

const txData = tx.compileMessage().serialize().toString('base64')
const latestSlot = await this.provider.connection.getSlot()
const recentBlock = await this.provider.connection.getBlock(latestSlot)
const tx = makeTx(rawTxs, {
recentBlockhash: recentBlock.blockhash,
feePayer: signer,
})

const msgData = tx.serializeMessage().toString('base64')
logger.line()
logger.success(
`Transaction generated with blockhash ID: ${recentBlock.blockhash.toString()} (${new Date(
`Message generated with blockhash ID: ${recentBlock.blockhash.toString()} (${new Date(
recentBlock.blockTime * 1000,
).toLocaleString()}). TX DATA:`,
).toLocaleString()}). MESSAGE DATA:`,
)
logger.log()
logger.log(txData)
logger.log(msgData)
logger.log()
logger.line()

Expand All @@ -81,7 +86,7 @@ export const wrapCommand = (command) => {
tx: this.wrapResponse('', this.multisigAddress.toString()),
contract: this.multisigAddress.toString(),
data: {
transactionData: txData,
transactionData: msgData,
},
},
],
Expand Down Expand Up @@ -153,7 +158,7 @@ export const wrapCommand = (command) => {
try {
return await this.program.account.transaction.fetch(proposal)
} catch (e) {
logger.info('Proposal state not found')
logger.info('Proposal state not found. Should be empty at CREATION time')
return
}
}
Expand All @@ -175,9 +180,19 @@ export const wrapCommand = (command) => {
logger.log('Creating proposal account...')
const proposal = Keypair.generate()
const txSize = 1300 // Space enough
const proposalAccount = await this.program.account.transaction.createInstruction(proposal, txSize)
const accountTx = new Transaction().add(proposalAccount)
await this.provider.send(accountTx, [proposal, this.wallet.payer])
const proposalInstruction = await SystemProgram.createAccount({
fromPubkey: this.wallet.publicKey,
newAccountPubkey: proposal.publicKey,
space: txSize,
lamports: await this.provider.connection.getMinimumBalanceForRentExemption(txSize),
programId: this.program.programId,
})
const rawTx: RawTransaction = {
data: proposalInstruction.data,
accounts: proposalInstruction.keys,
programId: proposalInstruction.programId,
}
await this.signAndSendRawTx([rawTx], [proposal])
logger.success(`Proposal account created at: ${proposal.publicKey.toString()}`)
return proposal.publicKey
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Result } from '@chainlink/gauntlet-core'
import { logger } from '@chainlink/gauntlet-core/dist/utils'
import { SolanaCommand, TransactionResponse } from '@chainlink/gauntlet-solana'
import { Message, Transaction } from '@solana/web3.js'
import { CONTRACT_LIST } from '@chainlink/gauntlet-solana-contracts'

export default class SendRawTx extends SolanaCommand {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, why is this part of gauntlet-serum-multisig?
IMO this base command should be exposed from guntlet-solana.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. Was there for testing purposes only

static id = 'send_tx'
static category = CONTRACT_LIST.MULTISIG

static examples = ['yarn gauntlet-serum-multisig send_tx --network=local --data=MULTISIG_ACCOUNT']

constructor(flags, args) {
super(flags, args)

this.requireFlag('message', 'Include a base64 encoded message')
this.requireFlag('signature', 'Include a base58 encoded signature')
}

execute = async () => {
const msg = Message.from(Buffer.from(this.flags.message, 'base64'))
const signature = this.flags.signature

logger.log('Message', msg)
logger.log('Signature:', signature)
const transaction = Transaction.populate(msg, [signature])

logger.log('TRANSACTION:', transaction)

logger.log('Sending tx...')
const txHash = await this.provider.connection.sendRawTransaction(transaction.serialize())

logger.log(txHash)
return {
responses: [
{
tx: this.wrapResponse(txHash, ''),
contract: '',
},
],
} as Result<TransactionResponse>
}
}
3 changes: 2 additions & 1 deletion gauntlet/packages/gauntlet-serum-multisig/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { io } from '@chainlink/gauntlet-core/dist/utils'
import { wrapCommand } from './commands/multisig'
import multisigSpecificCommands from './commands'
import CreateMultisig from './commands/create'
import SendRawTx from './commands/sendRawTx'

export const multisigCommands = {
custom: [...commands.custom.concat(multisigSpecificCommands).map(wrapCommand), CreateMultisig],
custom: [...commands.custom.concat(multisigSpecificCommands).map(wrapCommand), CreateMultisig, SendRawTx],
loadDefaultFlags: () => ({}),
abstract: {
findPolymorphic: () => undefined,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Result } from '@chainlink/gauntlet-core'
import { SolanaCommand, TransactionResponse } from '@chainlink/gauntlet-solana'
import { Keypair, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from '@solana/web3.js'
import { RawTransaction, SolanaCommand, TransactionResponse } from '@chainlink/gauntlet-solana'
import { AccountMeta, Keypair, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from '@solana/web3.js'
import { ASSOCIATED_TOKEN_PROGRAM_ID, Token, TOKEN_PROGRAM_ID } from '@solana/spl-token'
import { CONTRACT_LIST, getContract } from '../../../lib/contracts'
import { utils } from '@project-serum/anchor'
Expand Down Expand Up @@ -39,28 +39,23 @@ export default class Initialize extends SolanaCommand {
this.requireFlag('billingAccessController', 'Provide a --billingAccessController flag with a valid address')
}

execute = async () => {
makeRawTransaction = async (signer: PublicKey, state?: PublicKey): Promise<RawTransaction[]> => {
if (!state) throw new Error('State account is required')

const ocr2 = getContract(CONTRACT_LIST.OCR_2, '')
const address = ocr2.programId.toString()
const program = this.loadProgram(ocr2.idl, address)

// STATE ACCOUNTS
const state = Keypair.generate()
const owner = this.wallet.payer
const input = this.makeInput(this.flags.input)

// ARGS
const [vaultAuthority, vaultNonce] = await PublicKey.findProgramAddress(
[Buffer.from(utils.bytes.utf8.encode('vault')), state.publicKey.toBuffer()],
[Buffer.from(utils.bytes.utf8.encode('vault')), state.toBuffer()],
program.programId,
)

const [storeAuthority, _storeNonce] = await PublicKey.findProgramAddress(
[Buffer.from(utils.bytes.utf8.encode('store')), state.publicKey.toBuffer()],
program.programId,
)

const linkPublicKey = new PublicKey(this.flags.link)
const linkPublicKey = new PublicKey(this.flags.link || process.env.LINK)
const requesterAccessController = new PublicKey(this.flags.requesterAccessController)
const billingAccessController = new PublicKey(this.flags.billingAccessController)

Expand All @@ -76,47 +71,132 @@ export default class Initialize extends SolanaCommand {
true,
)

const accounts = {
state: state.publicKey,
transmissions: transmissions,
payer: this.provider.wallet.publicKey,
owner: owner.publicKey,
tokenMint: linkPublicKey,
tokenVault,
vaultAuthority,
requesterAccessController,
billingAccessController,
rent: SYSVAR_RENT_PUBKEY,
systemProgram: SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
}

Object.entries(accounts).map(([k, v]) => console.log('KEY:', k, '=', v.toString()))
console.log(`
- Min Answer: ${minAnswer.toString()}
- Max Answer: ${maxAnswer.toString()}
- Vault Nonce: ${vaultNonce}
`)

logger.log('Feed information:', input)
await prompt('Continue initializing OCR 2 feed?')

const txHash = await program.rpc.initialize(vaultNonce, minAnswer, maxAnswer, {
accounts,
signers: [owner, state],
instructions: [await program.account.state.createInstruction(state)],
const data = program.coder.instruction.encode('initialize', {
nonce: vaultNonce,
minAnswer,
maxAnswer,
})

const accounts: AccountMeta[] = [
{
pubkey: state,
isWritable: true,
isSigner: false,
},
{
pubkey: transmissions,
isWritable: false,
isSigner: false,
},
{
pubkey: signer,
isWritable: false,
isSigner: false,
},
{
pubkey: signer,
isWritable: false,
isSigner: true,
},
{
pubkey: linkPublicKey,
isWritable: false,
isSigner: false,
},
{
pubkey: tokenVault,
isWritable: true,
isSigner: false,
},
{
pubkey: vaultAuthority,
isWritable: false,
isSigner: false,
},
{
pubkey: requesterAccessController,
isWritable: false,
isSigner: false,
},
{
pubkey: billingAccessController,
isWritable: false,
isSigner: false,
},
{
pubkey: SYSVAR_RENT_PUBKEY,
isWritable: false,
isSigner: false,
},
{
pubkey: SystemProgram.programId,
isWritable: false,
isSigner: false,
},
{
pubkey: TOKEN_PROGRAM_ID,
isWritable: false,
isSigner: false,
},
{
pubkey: ASSOCIATED_TOKEN_PROGRAM_ID,
isWritable: false,
isSigner: false,
},
]

console.log(`
STATE ACCOUNTS:
- State: ${state.publicKey}
- State: ${state?.toString()}
- Transmissions: ${transmissions}
- StoreAuthority: ${storeAuthority.toString()}
- Payer: ${this.provider.wallet.publicKey}
- Owner: ${owner.publicKey}
- Owner: ${signer.toString()}
`)

const defaultAccountSize = new BN(program.account.state.size)
const feedCreationInstruction = await SystemProgram.createAccount({
fromPubkey: signer,
newAccountPubkey: state,
space: defaultAccountSize.toNumber(),
lamports: await this.provider.connection.getMinimumBalanceForRentExemption(defaultAccountSize.toNumber()),
programId: program.programId,
})

const rawTxs: RawTransaction[] = [
{
data: feedCreationInstruction.data,
accounts: feedCreationInstruction.keys,
programId: feedCreationInstruction.programId,
},
{
data,
accounts,
programId: program.programId,
},
]

return rawTxs
}

execute = async () => {
const ocr2 = getContract(CONTRACT_LIST.OCR_2, '')
const address = ocr2.programId.toString()
const program = this.loadProgram(ocr2.idl, address)

const state = Keypair.generate()
const rawTx = await this.makeRawTransaction(this.wallet.publicKey, state.publicKey)
await prompt(`Commit Offchain config?`)

const txhash = await this.withIDL(this.signAndSendRawTx, program.idl)(rawTx, [state])
logger.success(`Committing offchain config on tx ${txhash}`)

const transmissions = rawTx[1].accounts[1].pubkey

const [storeAuthority, _storeNonce] = await PublicKey.findProgramAddress(
[Buffer.from(utils.bytes.utf8.encode('store')), state.publicKey.toBuffer()],
program.programId,
)

return {
data: {
state: state.publicKey.toString(),
Expand All @@ -125,7 +205,7 @@ export default class Initialize extends SolanaCommand {
},
responses: [
{
tx: this.wrapResponse(txHash, address, {
tx: this.wrapResponse(txhash, address, {
state: state.publicKey.toString(),
transmissions: transmissions.toString(),
}),
Expand Down
Loading