Skip to content

Commit

Permalink
Merge pull request #13 from kevinheavey/snake-case-idl
Browse files Browse the repository at this point in the history
Snake case idl
  • Loading branch information
kevinheavey authored Nov 17, 2021
2 parents d88f6c2 + 7c72ade commit 6c22d5e
Show file tree
Hide file tree
Showing 18 changed files with 253 additions and 247 deletions.
3 changes: 1 addition & 2 deletions src/anchorpy/coder/common.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Common utilities for encoding and decoding."""
from typing import Dict, Union
from hashlib import sha256
from inflection import underscore

from anchorpy.idl import (
Idl,
Expand All @@ -23,7 +22,7 @@ def sighash(namespace: str, ix_name: str) -> bytes:
"""Not technically sighash, since we don't include the arguments.
(Because Rust doesn't allow function overloading.)"""
formatted_str = f"{namespace}:{underscore(ix_name)}"
formatted_str = f"{namespace}:{ix_name}"
return sha256(formatted_str.encode()).digest()[:8]


Expand Down
11 changes: 7 additions & 4 deletions src/anchorpy/idl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from typing import List, Union, Optional, Dict, Any, Literal, Tuple, TypedDict

from apischema import deserialize, alias
from apischema.metadata import conversion
from inflection import underscore, camelize
from borsh_construct import CStruct, Vec, U8
import solana.publickey # noqa: WPS301

Expand All @@ -28,6 +30,7 @@
"IdlTypeVec", "IdlTypeOption", "IdlTypeDefined", "IdlTypeArray"
]
IdlType = Union[LiteralStrings, NonLiteralIdlTypes]
snake_case_conversion = conversion(underscore, camelize)


@dataclass
Expand All @@ -47,21 +50,21 @@ class IdlTypeDefined:

@dataclass
class IdlField:
name: str
name: str = field(metadata=snake_case_conversion)
type: IdlType


@dataclass
class IdlAccount:
name: str
name: str = field(metadata=snake_case_conversion)
is_mut: bool = field(metadata=alias("isMut"))
is_signer: bool = field(metadata=alias("isSigner"))


@dataclass
class IdlAccounts:
# Nested/recursive version of IdlAccount
name: str
name: str = field(metadata=snake_case_conversion)
accounts: List["IdlAccountItem"]


Expand All @@ -70,7 +73,7 @@ class IdlAccounts:

@dataclass
class IdlInstruction:
name: str
name: str = field(metadata=snake_case_conversion)
accounts: List[IdlAccountItem]
args: List[IdlField]

Expand Down
6 changes: 3 additions & 3 deletions tests/test_basic_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ async def initialized_account(program: Program) -> Keypair:
1234,
ctx=Context(
accounts={
"myAccount": my_account.public_key,
"my_account": my_account.public_key,
"user": program.provider.wallet.public_key,
"systemProgram": SYS_PROGRAM_ID,
"system_program": SYS_PROGRAM_ID,
},
signers=[my_account],
),
Expand All @@ -58,7 +58,7 @@ async def test_update_previously_created_account(
"""Test updating a previously created account."""
await program.rpc["update"](
4321,
ctx=Context(accounts={"myAccount": initialized_account.public_key}),
ctx=Context(accounts={"my_account": initialized_account.public_key}),
)
account = await program.account["MyAccount"].fetch(initialized_account.public_key)
assert account.data == 4321
2 changes: 1 addition & 1 deletion tests/test_basic_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ async def created_counter(program: Program, provider: Provider) -> Keypair:
accounts={
"counter": counter.public_key,
"user": provider.wallet.public_key,
"systemProgram": SYS_PROGRAM_ID,
"system_program": SYS_PROGRAM_ID,
},
signers=[counter],
),
Expand Down
6 changes: 3 additions & 3 deletions tests/test_basic_3.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,17 @@ async def test_cpi(workspace: Dict[str, Program], provider: Provider) -> None:
accounts={
"puppet": new_puppet_account.public_key,
"user": provider.wallet.public_key,
"systemProgram": SYS_PROGRAM_ID,
"system_program": SYS_PROGRAM_ID,
},
signers=[new_puppet_account],
),
)
await puppet_master.rpc["pullStrings"](
await puppet_master.rpc["pull_strings"](
111,
ctx=Context(
accounts={
"puppet": new_puppet_account.public_key,
"puppetProgram": puppet.program_id,
"puppet_program": puppet.program_id,
},
),
)
Expand Down
12 changes: 6 additions & 6 deletions tests/test_cashiers_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,18 @@ async def create_check(program: Program, initial_state: InitialState) -> Created
accounts = {
"check": check.public_key,
"vault": vault.public_key,
"checkSigner": check_signer,
"check_signer": check_signer,
"from": initial_state.god,
"to": initial_state.receiver,
"owner": program.provider.wallet.public_key,
"tokenProgram": TOKEN_PROGRAM_ID,
"token_program": TOKEN_PROGRAM_ID,
"rent": SYSVAR_RENT_PUBKEY,
}
instructions = [
await program.account["Check"].create_instruction(check, 300),
*token_account_instrs,
]
await program.rpc["createCheck"](
await program.rpc["create_check"](
100,
"Hello world",
nonce,
Expand Down Expand Up @@ -120,15 +120,15 @@ async def test_cash_check(
initial_state: InitialState,
create_check: CreatedCheck,
) -> None:
await program.rpc["cashCheck"](
await program.rpc["cash_check"](
ctx=Context(
accounts={
"check": create_check.check.public_key,
"vault": create_check.vault.public_key,
"checkSigner": create_check.signer,
"check_signer": create_check.signer,
"to": initial_state.receiver,
"owner": provider.wallet.public_key,
"tokenProgram": TOKEN_PROGRAM_ID,
"token_program": TOKEN_PROGRAM_ID,
},
)
)
Expand Down
12 changes: 6 additions & 6 deletions tests/test_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ async def provider(program: Program) -> Provider:
@fixture(scope="module")
async def created_chatroom(program: Program) -> Keypair:
chatroom = Keypair()
await program.rpc["createChatRoom"](
await program.rpc["create_chat_room"](
"Test Chat",
ctx=Context(
accounts={
"chatRoom": chatroom.public_key,
"chat_room": chatroom.public_key,
"rent": SYSVAR_RENT_PUBKEY,
},
instructions=[
Expand All @@ -56,14 +56,14 @@ async def created_user(
) -> Tuple[PublicKey, PublicKey]:
authority = program.provider.wallet.public_key
user, bump = PublicKey.find_program_address([bytes(authority)], program.program_id)
await program.rpc["createUser"](
await program.rpc["create_user"](
"My User",
bump,
ctx=Context(
accounts={
"user": user,
"authority": authority,
"systemProgram": SYS_PROGRAM_ID,
"system_program": SYS_PROGRAM_ID,
}
),
)
Expand All @@ -84,13 +84,13 @@ async def sent_messages(
]
for i, msg in enumerate(messages):
print(f"sending message {i}")
await program.rpc["sendMessage"](
await program.rpc["send_message"](
msg,
ctx=Context(
accounts={
"user": user,
"authority": authority,
"chatRoom": created_chatroom.public_key,
"chat_room": created_chatroom.public_key,
},
),
)
Expand Down
14 changes: 7 additions & 7 deletions tests/test_composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ async def initialized_accounts(program: Program) -> Tuple[Keypair, Keypair]:
await program.rpc["initialize"](
ctx=Context(
accounts={
"dummyA": dummy_a.public_key,
"dummyB": dummy_b.public_key,
"dummy_a": dummy_a.public_key,
"dummy_b": dummy_b.public_key,
"rent": SYSVAR_RENT_PUBKEY,
},
signers=[dummy_a, dummy_b],
Expand All @@ -50,15 +50,15 @@ async def composite_updated_accounts(
program: Program,
initialized_accounts: Tuple[Keypair, Keypair],
) -> Tuple[Keypair, Keypair]:
"""Run compositeUpdate and return the keypairs used."""
"""Run composite_update and return the keypairs used."""
dummy_a, dummy_b = initialized_accounts
ctx = Context(
accounts={
"foo": {"dummyA": dummy_a.public_key},
"bar": {"dummyB": dummy_b.public_key},
"foo": {"dummy_a": dummy_a.public_key},
"bar": {"dummy_b": dummy_b.public_key},
},
)
await program.rpc["compositeUpdate"](1234, 4321, ctx=ctx)
await program.rpc["composite_update"](1234, 4321, ctx=ctx)
return initialized_accounts


Expand All @@ -67,7 +67,7 @@ async def test_composite_update(
program: Program,
composite_updated_accounts: Tuple[Keypair, Keypair],
) -> None:
"""Test that the call to compositeUpdate worked."""
"""Test that the call to composite_update worked."""
dummy_a, dummy_b = composite_updated_accounts
dummy_a_account = await program.account["DummyA"].fetch(dummy_a.public_key)
dummy_b_account = await program.account["DummyB"].fetch(dummy_b.public_key)
Expand Down
14 changes: 7 additions & 7 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async def test_hello_err(program: Program) -> None:
async def test_hello_no_msg_err(program: Program) -> None:
"""Test error from helloNoMsg func."""
with raises(ProgramError) as excinfo:
await program.rpc["helloNoMsg"]()
await program.rpc["hello_no_msg"]()
assert excinfo.value.msg == "HelloNoMsg"
assert excinfo.value.code == 300 + 123

Expand All @@ -45,7 +45,7 @@ async def test_hello_no_msg_err(program: Program) -> None:
async def test_hello_next_err(program: Program) -> None:
"""Test error from helloNext func."""
with raises(ProgramError) as excinfo:
await program.rpc["helloNext"]()
await program.rpc["hello_next"]()
assert excinfo.value.msg == "HelloNext"
assert excinfo.value.code == 300 + 124

Expand All @@ -54,8 +54,8 @@ async def test_hello_next_err(program: Program) -> None:
async def test_mut_err(program: Program) -> None:
"""Test mmut error."""
with raises(ProgramError) as excinfo:
await program.rpc["mutError"](
ctx=Context(accounts={"myAccount": SYSVAR_RENT_PUBKEY})
await program.rpc["mut_error"](
ctx=Context(accounts={"my_account": SYSVAR_RENT_PUBKEY})
)
assert excinfo.value.msg == "A mut constraint was violated"
assert excinfo.value.code == 140
Expand All @@ -66,10 +66,10 @@ async def test_has_one_err(program: Program) -> None:
"""Test hasOneError."""
account = Keypair()
with raises(ProgramError) as excinfo:
await program.rpc["hasOneError"](
await program.rpc["has_one_error"](
ctx=Context(
accounts={
"myAccount": account.public_key,
"my_account": account.public_key,
"owner": SYSVAR_RENT_PUBKEY,
"rent": SYSVAR_RENT_PUBKEY,
},
Expand Down Expand Up @@ -97,7 +97,7 @@ async def test_signer_err(program: Program) -> None:
),
],
program_id=program.program_id,
data=program.coder.instruction.encode("signerError", {}),
data=program.coder.instruction.encode("signer_error", {}),
),
)
with raises(RPCException) as excinfo:
Expand Down
Loading

0 comments on commit 6c22d5e

Please sign in to comment.