examples: Add counter to basic-4
This commit is contained in:
parent
3646068eff
commit
9da5bccb07
|
@ -8,17 +8,38 @@ pub mod basic_4 {
|
|||
use super::*;
|
||||
|
||||
#[state]
|
||||
pub struct MyProgram {
|
||||
pub data: u64,
|
||||
pub struct Counter {
|
||||
authority: Pubkey,
|
||||
count: u64,
|
||||
}
|
||||
|
||||
impl MyProgram {
|
||||
pub fn new(ctx: Context<Ctor>, data: u64) -> Result<Self, ProgramError> {
|
||||
Ok(Self { data })
|
||||
impl Counter {
|
||||
pub fn new(ctx: Context<Auth>) -> Result<Self, ProgramError> {
|
||||
Ok(Self {
|
||||
authority: *ctx.accounts.authority.key,
|
||||
count: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn increment(&mut self, ctx: Context<Auth>) -> Result<(), Error> {
|
||||
if &self.authority != ctx.accounts.authority.key {
|
||||
return Err(ErrorCode::Unauthorized.into());
|
||||
}
|
||||
self.count += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Accounts)]
|
||||
pub struct Ctor {}
|
||||
pub struct Auth<'info> {
|
||||
#[account(signer)]
|
||||
authority: AccountInfo<'info>,
|
||||
}
|
||||
// #endregion code
|
||||
|
||||
#[error]
|
||||
pub enum ErrorCode {
|
||||
#[msg("You are not authorized to perform this action.")]
|
||||
Unauthorized,
|
||||
}
|
||||
|
|
|
@ -1,25 +1,36 @@
|
|||
const assert = require('assert');
|
||||
const anchor = require('@project-serum/anchor');
|
||||
const assert = require("assert");
|
||||
const anchor = require("@project-serum/anchor");
|
||||
|
||||
describe('basic-4', () => {
|
||||
describe("basic-4", () => {
|
||||
const provider = anchor.Provider.local();
|
||||
|
||||
// Configure the client to use the local cluster.
|
||||
anchor.setProvider(anchor.Provider.local());
|
||||
anchor.setProvider(provider);
|
||||
|
||||
it('Is initialized!', async () => {
|
||||
const program = anchor.workspace.Basic4;
|
||||
const program = anchor.workspace.Basic4;
|
||||
|
||||
it("Is runs the constructor", async () => {
|
||||
// #region code
|
||||
// The data to set on the state struct.
|
||||
const data = new anchor.BN(1234);
|
||||
|
||||
// Initialize the program's state struct.
|
||||
await program.state.rpc.new(data);
|
||||
await program.state.rpc.new({
|
||||
accounts: {
|
||||
authority: provider.wallet.publicKey,
|
||||
},
|
||||
});
|
||||
|
||||
// Fetch the state struct from the network.
|
||||
const state = await program.state();
|
||||
// #endregion code
|
||||
assert.ok(state.count.eq(new anchor.BN(0)));
|
||||
});
|
||||
|
||||
assert.ok(state.data.eq(data));
|
||||
it("Executes a method on the program", async () => {
|
||||
await program.state.rpc.increment({
|
||||
accounts: {
|
||||
authority: provider.wallet.publicKey,
|
||||
},
|
||||
});
|
||||
const state = await program.state();
|
||||
assert.ok(state.count.eq(new anchor.BN(1)));
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue