Skip to content

Commit

Permalink
feat: Add has_one relations inference so you don't need to pass accou…
Browse files Browse the repository at this point in the history
…nts that are referenced by a has_one (coral-xyz#2160)
  • Loading branch information
ChewingGlass authored and henrye committed Dec 6, 2022
1 parent 5de084f commit d7cb300
Show file tree
Hide file tree
Showing 20 changed files with 380 additions and 9 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/no-cashing-tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,8 @@ jobs:
path: tests/multiple-suites
- cmd: cd tests/pda-derivation && anchor test --skip-lint && npx tsc --noEmit
path: tests/pda-derivation
- cmd: cd tests/relations-derivation && anchor test --skip-lint && npx tsc --noEmit
path: tests/relations-derivation
- cmd: cd tests/anchor-cli-idl && ./test.sh
path: tests/anchor-cli-idl
steps:
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,8 @@ jobs:
path: tests/multiple-suites
- cmd: cd tests/pda-derivation && anchor test --skip-lint && npx tsc --noEmit
path: tests/pda-derivation
- cmd: cd tests/relations-derivation && anchor test --skip-lint && npx tsc --noEmit
path: tests/relations-derivation
- cmd: cd tests/anchor-cli-idl && ./test.sh
path: tests/anchor-cli-idl
steps:
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ The minor version will be incremented upon a breaking change and the patch versi
* lang: Add parsing for consts from impl blocks for IDL PDA seeds generation ([#2128](https://github.com/coral-xyz/anchor/pull/2014))
* lang: Account closing reassigns to system program and reallocates ([#2169](https://github.com/coral-xyz/anchor/pull/2169)).
* ts: Add coders for SPL programs ([#2143](https://github.com/coral-xyz/anchor/pull/2143)).
* ts: Add `has_one` relations inference so accounts mapped via has_one relationships no longer need to be provided
* ts: Add ability to set args after setting accounts and retriving pubkyes
* ts: Add `.prepare()` to builder pattern
* spl: Add `freeze_delegated_account` and `thaw_delegated_account` wrappers ([#2164](https://github.com/coral-xyz/anchor/pull/2164))

### Fixes
Expand Down
1 change: 1 addition & 0 deletions lang/syn/src/idl/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,7 @@ fn idl_accounts(
},
docs: if !no_docs { acc.docs.clone() } else { None },
pda: pda::parse(ctx, accounts, acc, seeds_feature),
relations: relations::parse(acc, seeds_feature),
}),
})
.collect::<Vec<_>>()
Expand Down
3 changes: 3 additions & 0 deletions lang/syn/src/idl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use serde_json::Value as JsonValue;

pub mod file;
pub mod pda;
pub mod relations;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Idl {
Expand Down Expand Up @@ -77,6 +78,8 @@ pub struct IdlAccount {
pub docs: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub pda: Option<IdlPda>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub relations: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
Expand Down
19 changes: 19 additions & 0 deletions lang/syn/src/idl/relations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use crate::Field;
use syn::Expr;

pub fn parse(acc: &Field, seeds_feature: bool) -> Vec<String> {
if !seeds_feature {
return vec![];
}
acc.constraints
.has_one
.iter()
.flat_map(|s| match &s.join_target {
Expr::Path(path) => path.path.segments.first().map(|l| l.ident.to_string()),
_ => {
println!("WARNING: unexpected seed: {:?}", s);
None
}
})
.collect()
}
1 change: 1 addition & 0 deletions tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"multisig",
"permissioned-markets",
"pda-derivation",
"relations-derivation",
"pyth",
"realloc",
"spl/token-proxy",
Expand Down
15 changes: 15 additions & 0 deletions tests/relations-derivation/Anchor.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[features]
seeds = true

[provider]
cluster = "localnet"
wallet = "~/.config/solana/id.json"

[programs.localnet]
relations_derivation = "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"

[workspace]
members = ["programs/relations-derivation"]

[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
4 changes: 4 additions & 0 deletions tests/relations-derivation/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[workspace]
members = [
"programs/*"
]
22 changes: 22 additions & 0 deletions tests/relations-derivation/migrations/deploy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.

const anchor = require("@project-serum/anchor");

module.exports = async function (provider) {
// Configure client to use the provider.
anchor.setProvider(provider);

// Add your deploy script here.
async function deployAsync(exampleString: string): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
console.log(exampleString);
resolve();
}, 2000);
});
}

await deployAsync("Typescript migration example complete.");
};
19 changes: 19 additions & 0 deletions tests/relations-derivation/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "relations-derivation",
"version": "0.25.0",
"license": "(MIT OR Apache-2.0)",
"homepage": "https://github.com/coral-xyz/anchor#readme",
"bugs": {
"url": "https://github.com/coral-xyz/anchor/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/coral-xyz/anchor.git"
},
"engines": {
"node": ">=11"
},
"scripts": {
"test": "anchor test"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "relations-derivation"
version = "0.1.0"
description = "Created with Anchor"
rust-version = "1.56"
edition = "2021"

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

[features]
no-entrypoint = []
no-idl = []
cpi = ["no-entrypoint"]
default = []

[dependencies]
anchor-lang = { path = "../../../../lang" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.bpfel-unknown-unknown.dependencies.std]
features = []
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! The typescript example serves to show how one would setup an Anchor
//! workspace with TypeScript tests and migrations.

use anchor_lang::prelude::*;

declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

#[program]
pub mod relations_derivation {
use super::*;

pub fn init_base(ctx: Context<InitBase>) -> Result<()> {
ctx.accounts.account.my_account = ctx.accounts.my_account.key();
ctx.accounts.account.bump = ctx.bumps["account"];
Ok(())
}
pub fn test_relation(_ctx: Context<TestRelation>) -> Result<()> {
Ok(())
}
}

#[derive(Accounts)]
pub struct InitBase<'info> {
/// CHECK: yeah I know
#[account(mut)]
my_account: Signer<'info>,
#[account(
init,
payer = my_account,
seeds = [b"seed"],
space = 100,
bump,
)]
account: Account<'info, MyAccount>,
system_program: Program<'info, System>
}

#[derive(Accounts)]
pub struct Nested<'info> {
/// CHECK: yeah I know
my_account: UncheckedAccount<'info>,
#[account(
has_one = my_account,
seeds = [b"seed"],
bump = account.bump
)]
account: Account<'info, MyAccount>,
}

#[derive(Accounts)]
pub struct TestRelation<'info> {
/// CHECK: yeah I know
my_account: UncheckedAccount<'info>,
#[account(
has_one = my_account,
seeds = [b"seed"],
bump = account.bump
)]
account: Account<'info, MyAccount>,
nested: Nested<'info>,
}


#[account]
pub struct MyAccount {
pub my_account: Pubkey,
pub bump: u8
}
43 changes: 43 additions & 0 deletions tests/relations-derivation/tests/typescript.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as anchor from "@project-serum/anchor";
import { AnchorProvider, Program } from "@project-serum/anchor";
import { PublicKey } from "@solana/web3.js";
import { expect } from "chai";
import { RelationsDerivation } from "../target/types/relations_derivation";

describe("typescript", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.AnchorProvider.env());

const program = anchor.workspace
.RelationsDerivation as Program<RelationsDerivation>;
const provider = anchor.getProvider() as AnchorProvider;

it("Inits the base account", async () => {
await program.methods
.initBase()
.accounts({
myAccount: provider.wallet.publicKey,
})
.rpc();
});

it("Derives relationss", async () => {
const tx = await program.methods.testRelation().accounts({
nested: {
account: (
await PublicKey.findProgramAddress(
[Buffer.from("seed", "utf-8")],
program.programId
)
)[0],
},
});

await tx.instruction();
const keys = await tx.pubkeys();

expect(keys.myAccount.equals(provider.wallet.publicKey)).is.true;

await tx.rpc();
});
});
11 changes: 11 additions & 0 deletions tests/relations-derivation/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"types": ["mocha", "chai"],
"typeRoots": ["./node_modules/@types"],
"lib": ["es2015"],
"module": "commonjs",
"target": "es6",
"esModuleInterop": true,
"skipLibCheck": true
}
}
12 changes: 12 additions & 0 deletions ts/packages/anchor/src/coder/borsh/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ export class BorshAccountsCoder<A extends string = string>
return this.decodeUnchecked(accountName, data);
}

public decodeAny<T = any>(data: Buffer): T {
const accountDescriminator = data.slice(0, 8);
const accountName = Array.from(this.accountLayouts.keys()).find((key) =>
BorshAccountsCoder.accountDiscriminator(key).equals(accountDescriminator)
);
if (!accountName) {
throw new Error("Account descriminator not found");
}

return this.decodeUnchecked<T>(accountName as any, data);
}

public decodeUnchecked<T = any>(accountName: A, ix: Buffer): T {
// Chop off the discriminator before decoding.
const data = ix.slice(ACCOUNT_DISCRIMINATOR_SIZE);
Expand Down
1 change: 1 addition & 0 deletions ts/packages/anchor/src/idl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export type IdlAccount = {
isMut: boolean;
isSigner: boolean;
docs?: string[];
relations?: string[];
pda?: IdlPda;
};

Expand Down
Loading

0 comments on commit d7cb300

Please sign in to comment.