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

ported memo to anchor #3024

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 19 additions & 0 deletions memo/anchor_program/memo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "memo"
version = "0.1.0"
description = "Created with Anchor"
edition = "2018"

[lib]
crate-type = ["cdylib", "lib"]
name = "memo"

[features]
no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []

[dependencies]
anchor-lang = "0.22.0"
2 changes: 2 additions & 0 deletions memo/anchor_program/memo/Xargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.bpfel-unknown-unknown.dependencies.std]
features = []
50 changes: 50 additions & 0 deletions memo/anchor_program/memo/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use anchor_lang::prelude::*;

declare_id!("4ARKJpztrkSJXJQ8ii9pr6NjJdwKrC6M3jA8LG21tvjG");

#[program]
pub mod memo {
use super::*;
use std::str;
pub fn build_memo(ctx: Context<BuildMemo>,input:Vec<u8>) -> Result<()> {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: the name build_memo is a bit misleading, since you're actually printing the memo in your program, and not building it. Maybe log_memo would be a better name?

Also, for input, since it could be a large buffer, it's better to accept a &[u8] rather than a Vec<u8> to avoid copying.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

  • Changed the function name to log_memo
  • Anchor deserialize function won't allow the input to be &[u8], tried a lot of different ways to make it happen but well Anchor complains a lot in this particular scenario.
    Error:
    the function or associated item `deserialize` exists for struct `instruction::LogMemo`, but its trait bounds were not satisfied

Copy link
Contributor

Choose a reason for hiding this comment

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

Ah, this might be the place for zero-copy deserialization! Here's an example for you to follow: https://github.com/project-serum/anchor/blob/master/tests/zero-copy/programs/zero-copy/src/lib.rs


msg!("Initializing");
Saviour1001 marked this conversation as resolved.
Show resolved Hide resolved

let accounts = ctx.remaining_accounts;

let mut missing_required_signature = false;
for account_info in accounts.iter() {
if let Some(address) = account_info.signer_key() {
msg!("Signed by: {:?}", address);
}
else{
missing_required_signature = true;
}
}
if missing_required_signature{
return err!(MyError::MissingRequiredSignature);
Saviour1001 marked this conversation as resolved.
Show resolved Hide resolved
}

let memo = str::from_utf8(&input).map_err(|err| {
msg!("Invalid UTF-8, from bytes: {:?}", err);
ProgramError::InvalidInstructionData
})?;
msg!("Memo (len {}): {:?}", memo.len(), memo);
Ok(())
}
}

#[derive(Accounts)]
pub struct BuildMemo<> {

}


#[error_code]
pub enum MyError {
#[msg("Missing required signature")]
MissingRequiredSignature,
#[msg("Invalid Instruction Data")]
InvalidInstructionData
}

Saviour1001 marked this conversation as resolved.
Show resolved Hide resolved
98 changes: 98 additions & 0 deletions memo/anchor_program/tests/memo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const anchor = require("@project-serum/anchor");
const assert = require("assert");

describe("memo", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.env());
const program = anchor.workspace.Memo;

it("Test 1 => Sending Buffers", async () => {
const string = "letters";
var codedString = Buffer.from(string);

const tx = await program.rpc.buildMemo(codedString);
console.log("Transaction Signature:", tx);
});

it("Test 2 => Asserting Emojis and Bytes", async () => {
let emoji = Uint8Array.from(Buffer.from("🐆"));
let bytes = Uint8Array.from([0xf0, 0x9f, 0x90, 0x86]);
assert.equal(emoji.toString(), bytes.toString());

const tx1 = await program.rpc.buildMemo(Buffer.from("🐆"));

const tx2 = await program.rpc.buildMemo(Buffer.from(bytes));
console.log("Transaction Signature One:", tx1);
console.log("Transaction Signature Two:", tx2);
});

it("Test 3 => Sending Signed Transaction", async () => {
const pubkey1 = anchor.web3.Keypair.generate();
const pubkey2 = anchor.web3.Keypair.generate();
const pubkey3 = anchor.web3.Keypair.generate();
Saviour1001 marked this conversation as resolved.
Show resolved Hide resolved

const tx = await program.rpc.buildMemo(Buffer.from("🐆"), {
accounts: [],
remainingAccounts: [
{ pubkey: pubkey1.publicKey, isWritable: false, isSigner: true },
{ pubkey: pubkey2.publicKey, isWritable: false, isSigner: true },
{ pubkey: pubkey3.publicKey, isWritable: false, isSigner: true },
],
signers: [pubkey1, pubkey2, pubkey3],
});
console.log("Transaction Signature:", tx);
});

it("Test 4 => Sending Unsigned Transaction with a Memo", async () => {
// This test should fail because the transaction is not signed.
const pubkey1 = anchor.web3.Keypair.generate();
const pubkey2 = anchor.web3.Keypair.generate();
const pubkey3 = anchor.web3.Keypair.generate();

assert.rejects(() => {
program.rpc.buildMemo(Buffer.from("🐆"), {
accounts: [],
remainingAccounts: [
{ pubkey: pubkey1.publicKey, isWritable: false, isSigner: false },
{ pubkey: pubkey2.publicKey, isWritable: false, isSigner: false },
{ pubkey: pubkey3.publicKey, isWritable: false, isSigner: false },
],
signers: [pubkey1, pubkey2, pubkey3],
});
}, new Error("unknown signer"));

console.log("Test failed successfully :)");
});

it("Test 5 => Sending a transaction with missing signers", async () => {
// This test should fail because the transaction is not signed completely.
const pubkey1 = anchor.web3.Keypair.generate();
const pubkey2 = anchor.web3.Keypair.generate();
const pubkey3 = anchor.web3.Keypair.generate();

assert.rejects(async () => {
await program.rpc.buildMemo(Buffer.from("🐆"), {
accounts: [],
remainingAccounts: [
{ pubkey: pubkey1.publicKey, isWritable: false, isSigner: true },
{ pubkey: pubkey2.publicKey, isWritable: false, isSigner: false },
{ pubkey: pubkey3.publicKey, isWritable: false, isSigner: true },
],
signers: [pubkey1, pubkey2, pubkey3],
});
}, new Error("unknown signer"));
console.log("Test failed successfully :)");
});

it("Test 6 => Testing invalid input", async () => {
// This test should fail because the input is invalid.
let invalid_utf8 = Uint8Array.from([
0xf0, 0x9f, 0x90, 0x86, 0xf0, 0x9f, 0xff, 0x86,
]);

assert.rejects(() => {
program.rpc.buildMemo(Buffer.from(invalid_utf8));
}, new Error());
console.log("Test failed successfully :)");
});
});