Skip to content

Commit

Permalink
Add relations inference
Browse files Browse the repository at this point in the history
  • Loading branch information
ChewingGlass committed Aug 30, 2022
1 parent c1c4f6c commit 2ec5ddf
Show file tree
Hide file tree
Showing 21 changed files with 22,727 additions and 12 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ The minor version will be incremented upon a breaking change and the patch versi
* spl: Add `MetadataAccount` account deserialization. ([#2014](https://github.com/coral-xyz/anchor/pull/2014)).
* lang: Add parsing for consts from impl blocks for IDL PDA seeds generation ([#2128](https://github.com/coral-xyz/anchor/pull/2014))
* 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

### Fixes

Expand Down
3 changes: 3 additions & 0 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ impl WithPath<Config> {
path.join("src/lib.rs"),
version,
self.features.seeds,
self.features.relations,
false,
false,
)?;
Expand Down Expand Up @@ -286,6 +287,8 @@ pub struct Config {
pub struct FeaturesConfig {
#[serde(default)]
pub seeds: bool,
#[serde(default)]
pub relations: bool,
#[serde(default, rename = "skip-lint")]
pub skip_lint: bool,
}
Expand Down
1 change: 1 addition & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1511,6 +1511,7 @@ fn extract_idl(
&*file,
cargo.version(),
cfg.features.seeds,
cfg.features.relations,
no_docs,
!(cfg.features.skip_lint || skip_lint),
)
Expand Down
10 changes: 7 additions & 3 deletions lang/syn/src/idl/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub fn parse(
filename: impl AsRef<Path>,
version: String,
seeds_feature: bool,
relations_feature: bool,
no_docs: bool,
safety_checks: bool,
) -> Result<Option<Idl>> {
Expand Down Expand Up @@ -79,6 +80,7 @@ pub fn parse(
accounts_strct,
&accs,
seeds_feature,
relations_feature,
no_docs,
);
IdlInstruction {
Expand Down Expand Up @@ -128,7 +130,7 @@ pub fn parse(
.collect();
let accounts_strct = accs.get(&anchor_ident.to_string()).unwrap();
let accounts =
idl_accounts(&ctx, accounts_strct, &accs, seeds_feature, no_docs);
idl_accounts(&ctx, accounts_strct, &accs, seeds_feature, relations_feature, no_docs);
IdlInstruction {
name,
docs: None,
Expand Down Expand Up @@ -208,7 +210,7 @@ pub fn parse(
.collect::<Vec<_>>();
// todo: don't unwrap
let accounts_strct = accs.get(&ix.anchor_ident.to_string()).unwrap();
let accounts = idl_accounts(&ctx, accounts_strct, &accs, seeds_feature, no_docs);
let accounts = idl_accounts(&ctx, accounts_strct, &accs, seeds_feature, relations_feature, no_docs);
let ret_type_str = ix.returns.ty.to_token_stream().to_string();
let returns = match ret_type_str.as_str() {
"()" => None,
Expand Down Expand Up @@ -620,6 +622,7 @@ fn idl_accounts(
accounts: &AccountsStruct,
global_accs: &HashMap<String, AccountsStruct>,
seeds_feature: bool,
relations_feature: bool,
no_docs: bool,
) -> Vec<IdlAccountItem> {
accounts
Expand All @@ -630,7 +633,7 @@ fn idl_accounts(
let accs_strct = global_accs.get(&comp_f.symbol).unwrap_or_else(|| {
panic!("Could not resolve Accounts symbol {}", comp_f.symbol)
});
let accounts = idl_accounts(ctx, accs_strct, global_accs, seeds_feature, no_docs);
let accounts = idl_accounts(ctx, accs_strct, global_accs, seeds_feature, relations_feature, no_docs);
IdlAccountItem::IdlAccounts(IdlAccounts {
name: comp_f.ident.to_string().to_mixed_case(),
accounts,
Expand All @@ -645,6 +648,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, relations_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
23 changes: 23 additions & 0 deletions lang/syn/src/idl/relations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use crate::{Field};
use syn::{Expr};

pub fn parse(
acc: &Field,
relations_feature: bool,
) -> Vec<String> {
if !relations_feature {
return vec![];
}
acc.constraints
.has_one
.iter()
.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
}
})
.flatten()
.collect()
}
16 changes: 16 additions & 0 deletions tests/relations-derivation/Anchor.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[features]
relations = true
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": "pda-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
}
38 changes: 38 additions & 0 deletions tests/relations-derivation/tests/typescript.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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/pda_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
}
}

0 comments on commit 2ec5ddf

Please sign in to comment.