kevinheavey / anchorpy Goto Github PK
View Code? Open in Web Editor NEWThe Python Anchor client.
Home Page: https://kevinheavey.github.io/anchorpy/
License: MIT License
The Python Anchor client.
Home Page: https://kevinheavey.github.io/anchorpy/
License: MIT License
Using the Jet Protocol IDL, copied here: https://gist.github.com/eyevz/fe7e9265b42c8fc7e4ff622498f6608a, I get the following error when trying to instantiate a program like Program(idl, jd.JET_V1_KEY, Provider.local())
.
ValueError: Unrecognized variant type: <class 'anchorpy.borsh_extension._DataclassStruct'>
I can successfully instantiate and inspect the IDL itself using idl = Idl.from_json(raw_idl)
.
Currently running python 3.9.11 on Debian. Not sure if this has ever been reported, but pasting my output here. Anchor, solana, and pip are installed. setuptools is also up to date. Any help would be appreciated.
pip install anchorpy
Collecting anchorpy
Using cached anchorpy-0.8.1-py3-none-any.whl (43 kB)
Collecting jsonrpcclient<5.0.0,>=4.0.1
Using cached jsonrpcclient-4.0.2.tar.gz (6.5 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [1 lines of output]
ERROR: Can not execute `setup.py` since setuptools is not available in the build environment.
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
(pyvenv39) #( 03/17/22@ 4:48PM )( lemons@basecamp ):~
anchor --version
anchor-cli 0.22.1
(pyvenv39) #( 03/17/22@ 4:48PM )( lemons@basecamp ):~
python --version
Python 3.9.11
(pyvenv39) #( 03/17/22@ 4:48PM )( lemons@basecamp ):~
pip --version
pip 22.0.4 from /home/lemons/.pyenv/versions/3.9.11/lib/python3.9/site-packages/pip (python 3.9)
I got an error : InvalidParamsMessage { message: "invalid transaction: Transaction failed to sanitize accounts offsets correctly" } when simulate and send transaction to mainnet and local net.
I have used the "anchorpy client-gen" command to generate a Python client, and I checked many times to make the accounts and args right.
Here is my code:
async def execute_whirlpool_swap():
MIN_SQRT_PRICE = 4295048016
MAX_SQRT_PRICE = 79226673515401279992447579055
WHIRLPOOL_PROGRAM_ID = Pubkey.from_string("whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc")
# swap SOL for USDC
args = {
"amount": int(1e9 * 0.01),
"other_amount_threshold": int(1e6 * 0.01),
"sqrt_price_limit": MIN_SQRT_PRICE,
"amount_specified_is_input": True,
"a_to_b": True
}
print("args", args)
pool = await whirlpool.Whirlpool.fetch(provider.connection, SOL_USDC_8_WHIRLPOOL_PUBKEY)
# -24350
print("pool.tick_current_index", pool.tick_current_index)
tick_arrays = tick_utils.TickUtil.get_tick_array_pdas(tick=pool.tick_current_index,
tick_spacing=pool.tick_spacing,
num_of_tick_arrays=3,
program_id=WHIRLPOOL_PROGRAM_ID,
whirlpool_address=SOL_USDC_8_WHIRLPOOL_PUBKEY,
a_to_b=True)
seeds = [bytes("oracle", 'utf8'), bytes(SOL_USDC_8_WHIRLPOOL_PUBKEY)]
oracle = Pubkey.find_program_address(seeds, WHIRLPOOL_PROGRAM_ID)
accounts = instructions.ExecuteWhirlpoolSwapAccounts(
whirlpool_program = WHIRLPOOL_PROGRAM_ID,
access_control = pda[0],
whirlpool = SOL_USDC_8_WHIRLPOOL_PUBKEY,
token_owner_account_a = get_associated_token_address(owner=dev.pubkey(), mint=WRAPPED_SOL_MINT),
token_vault_a = Pubkey.from_string("9RfZwn2Prux6QesG1Noo4HzMEBv3rPndJ2bN2Wwd6a7p"),
token_owner_account_b = get_associated_token_address(owner=dev.pubkey(), mint=USDC),
token_vault_b = Pubkey.from_string("BVNo8ftg2LkkssnWT4ZWdtoFaevnfD6ExYeramwM27pe"),
oracle = oracle[0],
# oracle = Pubkey.from_string("6vK8gSiRHSnZzAa5JsvBF2ej1LrxpRX21Y185CzP4PeA"),
# oracle = Pubkey.from_string("BVNo8ftg2LkkssnWT4ZWdtoFaevnfD6ExYeramwM27pe"), ####
tick_array0 = tick_arrays[0].public_key,
tick_array1 = tick_arrays[1].public_key,
tick_array2 = tick_arrays[2].public_key,
executor = dev.pubkey(),
)
ix = instructions.execute_whirlpool_swap(args, accounts)
recent_blockhash = await provider.connection.get_latest_blockhash(commitment="finalized")
tx = Transaction(recent_blockhash=recent_blockhash.value.blockhash).add(ix)
tx.sign(dev)
print("dev", dev.pubkey())
# NOTE: for simulate
print(await provider.simulate(tx))
"execute_whirlpool_swap" is to send a orca swap transaction.
"instructions.execute_whirlpool_swap" is my program function.
Type "ExecuteWhirlpoolSwapAccounts" is auto generated. Here is detail:
class ExecuteWhirlpoolSwapArgs(typing.TypedDict):
amount: int
other_amount_threshold: int
sqrt_price_limit: int
amount_specified_is_input: bool
a_to_b: bool
layout = borsh.CStruct(
"amount" / borsh.U64,
"other_amount_threshold" / borsh.U64,
"sqrt_price_limit" / borsh.U128,
"amount_specified_is_input" / borsh.Bool,
"a_to_b" / borsh.Bool,
)
class ExecuteWhirlpoolSwapAccounts(typing.TypedDict):
whirlpool_program: Pubkey
access_control: Pubkey
whirlpool: Pubkey
token_owner_account_a: Pubkey
token_vault_a: Pubkey
token_owner_account_b: Pubkey
token_vault_b: Pubkey
tick_array0: Pubkey
tick_array1: Pubkey
tick_array2: Pubkey
oracle: Pubkey
executor: Pubkey
def execute_whirlpool_swap(
args: ExecuteWhirlpoolSwapArgs,
accounts: ExecuteWhirlpoolSwapAccounts,
program_id: Pubkey = PROGRAM_ID,
remaining_accounts: typing.Optional[typing.List[AccountMeta]] = None,
) -> Instruction:
keys: list[AccountMeta] = [
AccountMeta(
pubkey=accounts["whirlpool_program"], is_signer=False, is_writable=False
),
AccountMeta(pubkey=TOKEN_PROGRAM_ID, is_signer=False, is_writable=False),
AccountMeta(
pubkey=accounts["access_control"], is_signer=False, is_writable=False
),
AccountMeta(pubkey=accounts["whirlpool"], is_signer=False, is_writable=True),
AccountMeta(
pubkey=accounts["token_owner_account_a"], is_signer=False, is_writable=True
),
AccountMeta(
pubkey=accounts["token_vault_a"], is_signer=False, is_writable=True
),
AccountMeta(
pubkey=accounts["token_owner_account_b"], is_signer=False, is_writable=True
),
AccountMeta(
pubkey=accounts["token_vault_b"], is_signer=False, is_writable=True
),
AccountMeta(pubkey=accounts["tick_array0"], is_signer=False, is_writable=True),
AccountMeta(pubkey=accounts["tick_array1"], is_signer=False, is_writable=True),
AccountMeta(pubkey=accounts["tick_array2"], is_signer=False, is_writable=True),
AccountMeta(pubkey=accounts["oracle"], is_signer=False, is_writable=False),
AccountMeta(pubkey=accounts["executor"], is_signer=True, is_writable=False),
]
print("token program id", TOKEN_PROGRAM_ID)
if remaining_accounts is not None:
keys += remaining_accounts
identifier = b"\x8cW\xc8\xe1 d\xae\xe1"
encoded_args = layout.build(
{
"amount": args["amount"],
"other_amount_threshold": args["other_amount_threshold"],
"sqrt_price_limit": args["sqrt_price_limit"],
"amount_specified_is_input": args["amount_specified_is_input"],
"a_to_b": args["a_to_b"],
}
)
data = identifier + encoded_args
return Instruction(program_id, data, keys)
Please help me find out why I got this error. I would appreciate very much. Thanks a lot!
In the dynamic client after loading the program accounts, I want to decode the data:
http_client = Client("https://api.devnet.solana.com")
pubkey = PublicKey("...")
accounts = []
for x in http_client.get_program_accounts_json_parsed(pubkey).value:
accounts.append(x.account)
But, the bytes cannot be decoded:
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 1-2: invalid continuation byte
What should I do?
Thanks a lot.
Using version ^0.18.0 for anchorpy
c-ext\backend_c.c(13): fatal error C1083: Cannot open include file: 'Windows.h': No such file or directory
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe' failed with exit code 2
at ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\poetry\installation\chef.py:147 in _prepare
143│
144│ error = ChefBuildError("\n\n".join(message_parts))
145│
146│ if error is not None:
→ 147│ raise error from None
148│
149│ return path
150│
151│ def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path:
Note: This error originates from the build backend, and is likely not a problem with poetry but with zstandard (0.18.0) not supporting PEP 517 builds. You can verify this by running 'pip wheel --use-pep517 "zstandard (==0.18.0)"'.
I'm on Windows 11.
Latest version of solana-py currently is 0.28.1 and comes with some important updates, any chance we can get a compatible version?
After creating a test script for my first anchorpy
client, generated from the target program (i.e. idl.json),
#!/bin/bash
# The program is is the eshxro staking one
# This requires the json generated by anchor on eshxro staking
# give whatever name to the client
anchorpy client-gen --program-id 2jmux3fWV5zHirkEZCoSMEgTgdYZqkE9Qx2oQnxoHRgA eshxro_staking_idl.json eshxrostaking_client
however, my test script wasn't able to import the target struct I am interested on, giving me an import error.
from solana.publickey import PublicKey
from eshxrostaking_client.accounts import StakePool
POOL_ID = "9zdpqAgENj4734TQvqjczMg2ekvvuGsxwJC6f7F1QWp4"
addr = PublicKey(POOL_ID)
from solana.rpc.api import Client
network = "https://api.devnet.solana.com"
client = Client(network)
acc = StakePool.fetch(client, addr)
if acc is None:
# the fetch method returns null when the account is uninitialized
raise ValueError("account not found")
obj = acc.to_json()
print(obj)
acc_from_json = StakePool.from_json(obj)
However, I have an ImportError on anchorpy
ImportError: cannot import name 'EnumForCodegen' from 'anchorpy.borsh_extension'
Find below the complete backtrace
Traceback (most recent call last):
File "/home/ruben/hxro-dot-com/backend/test.py", line 2, in <module>
from eshxrostaking_client.accounts import StakePool
File "/home/ruben/hxro-dot-com/backend/eshxrostaking_client/accounts/__init__.py", line 1, in <module>
from .stake_pool import StakePool, StakePoolJSON
File "/home/ruben/hxro-dot-com/backend/eshxrostaking_client/accounts/stake_pool.py", line 13, in <module>
from .. import types
File "/home/ruben/hxro-dot-com/backend/eshxrostaking_client/types/__init__.py", line 10, in <module>
from . import pool_type
File "/home/ruben/hxro-dot-com/backend/eshxrostaking_client/types/pool_type.py", line 4, in <module>
from anchorpy.borsh_extension import EnumForCodegen
ImportError: cannot import name 'EnumForCodegen' from 'anchorpy.borsh_extension' (/home/ruben/hxro-dot-com/backend/env/lib/python3.9/site-packages/anchorpy/borsh_extension.py)
My python environment
Package Version
--------------------- --------------
aiodns 3.0.0
aiohttp 3.8.3
aiosignal 1.2.0
anchorpy 0.8.3
anyio 3.6.2
apischema 0.16.6
appnope 0.1.3
APScheduler 3.9.1
argon2-cffi 21.3.0
argon2-cffi-bindings 21.2.0
asttokens 2.0.8
async-timeout 4.0.2
attrs 21.4.0
backcall 0.2.0
backoff 1.11.1
base58 2.1.1
based58 0.1.1
bidict 0.21.2
bleach 4.1.0
borsh-construct 0.1.1
cachetools 4.2.4
certifi 2021.10.8
cffi 1.15.1
chardet 4.0.0
charset-normalizer 2.0.12
click 7.1.2
construct 2.10.67
construct-typing 0.5.2
contourpy 1.0.5
cryptography 36.0.2
cycler 0.11.0
debugpy 1.6.3
decorator 5.1.1
defusedxml 0.7.1
dexteritysdk 0.1.1
dnspython 2.2.1
ed25519 1.5
entrypoints 0.4
executing 1.1.1
fastjsonschema 2.16.2
flake8 4.0.1
Flask 2.0.0
Flask-Cors 3.0.10
Flask-Sockets 0.2.1
fonttools 4.38.0
frozenlist 1.3.1
gevent 21.1.2
gevent-websocket 0.10.1
greenlet 1.1.0
gunicorn 20.1.0
h11 0.12.0
httpcore 0.13.7
httpx 0.18.2
idna 3.4
iniconfig 1.1.1
ipykernel 6.16.2
ipython 8.5.0
ipython-genutils 0.2.0
ipywidgets 7.7.2
iso8601 0.1.16
itsdangerous 2.1.2
jedi 0.18.1
Jinja2 3.1.2
jsonrpcclient 4.0.2
jsonrpcserver 5.0.9
jsonschema 3.2.0
jupyter 1.0.0
jupyter-client 7.3.1
jupyter-console 6.4.4
jupyter_core 4.11.2
jupyter-server 1.15.6
jupyterlab-pygments 0.1.2
jupyterlab-widgets 1.1.1
kiwisolver 1.4.4
loguru 0.6.0
MarkupSafe 2.0.1
matplotlib 3.6.1
matplotlib-inline 0.1.6
mccabe 0.6.1
migra 3.0.1621480950
mistune 0.8.4
more-itertools 8.14.0
multidict 6.0.2
nbclassic 0.4.5
nbclient 0.5.13
nbconvert 6.2.0
nbformat 5.7.0
nest-asyncio 1.5.6
notebook 6.5.1
notebook_shim 0.2.0
numpy 1.23.4
OSlash 0.6.3
packaging 21.3
pandas 1.5.1
pandocfilters 1.5.0
parimutuelsdk 0.0.50
parso 0.8.3
pexpect 4.8.0
pickleshare 0.7.5
Pillow 9.2.0
pip 22.2.2
pluggy 0.13.1
podite 0.1.2
prometheus-client 0.13.1
prompt-toolkit 3.0.31
psutil 5.9.3
psycopg2 2.9.1
ptyprocess 0.7.0
pure-eval 0.2.2
py 1.10.0
pycares 4.2.2
pycodestyle 2.8.0
pycparser 2.21
pyflakes 2.4.0
Pygments 2.13.0
pyheck 0.1.5
PyNaCl 1.5.0
pyparsing 3.0.7
pyrsistent 0.18.1
pytest 6.2.5
pytest-asyncio 0.17.2
pytest-xprocess 0.18.1
pythclient 0.1.2
python-dateutil 2.8.2
python-engineio 4.2.0
python-socketio 5.3.0
pytz 2022.1
pytz-deprecation-shim 0.1.0.post0
pyzmq 22.3.0
qtconsole 5.3.2
QtPy 2.2.1
requests 2.27.1
rfc3986 1.5.0
schemainspect 3.0.1616029793
Send2Trash 1.8.0
setuptools 65.3.0
simple-websocket 0.2.0
six 1.16.0
sniffio 1.3.0
solana 0.23.3
SQLAlchemy 1.4.22
sqlbag 0.1.1617247075
stack-data 0.5.1
sumtypes 0.1a6
terminado 0.13.3
testpath 0.5.0
toml 0.10.2
toolz 0.11.2
tornado 6.2
traitlets 5.5.0
types-cachetools 4.2.10
typing-extensions 3.10.0.2
tzdata 2022.5
tzlocal 4.2
urllib3 1.26.8
wcwidth 0.2.5
webencodings 0.5.1
websocket-client 1.2.3
websockets 10.4
Werkzeug 2.1.2
wheel 0.37.1
widgetsnbextension 3.6.1
wsproto 1.0.0
yarl 1.8.1
zope.event 4.5.0
zope.interface 5.4.0
zstandard 0.17.0
context: processing transaction logs into events for archival purposes with anchorpy
code:
import asyncio
import base64
import binascii
from solana.rpc.async_api import AsyncClient # type: ignore
from solders.signature import Signature # type: ignore
from anchorpy import Wallet, Program, Provider # type: ignore
DRIFT_PROGRAM_ID: str = "dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH"
PROGRAM_LOG: str = "Program log: "
PROGRAM_DATA: str = "Program data: "
PROGRAM_LOG_START_INDEX: int = len(PROGRAM_LOG)
PROGRAM_DATA_START_INDEX: int = len(PROGRAM_DATA)
async def parse_logs(program: Program, logs: list[str]) -> None:
for log in logs:
if log.startswith("Log truncated"):
break
handle_log(log, program)
def handle_log(
log: str, program: Program
):
if log.startswith(PROGRAM_LOG) or log.startswith(PROGRAM_DATA):
log_str = (
log[PROGRAM_LOG_START_INDEX:]
if log.startswith(PROGRAM_LOG)
else log[PROGRAM_DATA_START_INDEX:]
)
try:
decoded = base64.b64decode(log_str)
except binascii.Error:
return
# throws here
event = program.coder.events.parse(decoded)
print(event)
return
else:
return
async def main():
connection = AsyncClient("https://api.mainnet-beta.solana.com")
signature = Signature.from_string("gjVEiXqtWPCbfKtsypL3xvNk8ef2j6D1bo5pHjvL5Bms66TbDozjs7jqusfWj2GhPgDmTojPYgYXtr7AuTk5Y3c")
wallet = Wallet.dummy()
provider = Provider(connection, wallet)
program = await Program.at(DRIFT_PROGRAM_ID, provider)
logs = (await connection.get_transaction(signature, max_supported_transaction_version=0)).value.transaction.meta.log_messages
await parse_logs(program, logs)
if __name__ == "__main__":
asyncio.run(main())
error:
raise StreamError("stream read less than specified amount, expected %d, found %d" % (length, len(data)), path=path)
construct.core.StreamError: Error in path (parsing) -> discriminator
stream read less than specified amount, expected 8, found 6
Hey. Would love it if you can make a new release against the latest apischema version.
https://github.com/wyfo/apischema/releases/tag/v0.16.4 is preventing us to use the mainline version of anchorpy.
Thanks!
It seems like the event parser is getting confused by my logs. Here is a snippet demonstrating the problem: https://gist.github.com/eyevz/5ec6bab673f4b2d5886bac32da6f3ce4
Client fails to generate code in this particular case.
anchorpy client-gen --program-id=gdrpGjVffourzkdDRrQmySw4aTHr8a3xmQzzxSwFD1a idls/staratlas-distributor.json distributor
generating package...
generating program_id.py...
generating errors.py...
generating instructions...
Traceback (most recent call last):
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/bin/anchorpy", line 8, in <module>
sys.exit(app())
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/typer/main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/typer/main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/anchorpy/cli.py", line 136, in client_gen
gen_instructions(idl_obj, out)
File "/Users/macpro/PycharmProjects/staratlaspy/_venv/lib/python3.10/site-packages/anchorpy/clientgen/instructions.py", line 43, in gen_instructions
formatted = format_str(code, mode=FileMode())
File "src/black/__init__.py", line 1163, in format_str
File "src/black/__init__.py", line 1173, in _format_str_once
File "src/black/parsing.py", line 128, in lib2to3_parse
black.parsing.InvalidInput: Cannot parse: 20:8: from: PublicKey
source of idl json:
{
"version": "0.0.0",
"name": "merkle_distributor",
"instructions": [
{
"name": "newDistributor",
"accounts": [
{
"name": "base",
"isMut": false,
"isSigner": true
},
{
"name": "distributor",
"isMut": true,
"isSigner": false
},
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "bump",
"type": "u8"
},
{
"name": "root",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "temporal",
"type": "publicKey"
}
]
},
{
"name": "closeDistributor",
"accounts": [
{
"name": "base",
"isMut": false,
"isSigner": true
},
{
"name": "distributor",
"isMut": true,
"isSigner": false
},
{
"name": "distributorWallet",
"isMut": true,
"isSigner": false
},
{
"name": "receiver",
"isMut": false,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "bump",
"type": "u8"
},
{
"name": "walletBump",
"type": "u8"
}
]
},
{
"name": "claim",
"accounts": [
{
"name": "distributor",
"isMut": true,
"isSigner": false
},
{
"name": "claimStatus",
"isMut": true,
"isSigner": false
},
{
"name": "from",
"isMut": true,
"isSigner": false
},
{
"name": "to",
"isMut": true,
"isSigner": false
},
{
"name": "temporal",
"isMut": false,
"isSigner": true
},
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "bump",
"type": "u8"
},
{
"name": "index",
"type": "u64"
},
{
"name": "amount",
"type": "u64"
},
{
"name": "claimantSecret",
"type": "publicKey"
},
{
"name": "proof",
"type": {
"vec": {
"array": [
"u8",
32
]
}
}
}
]
},
{
"name": "claimCandy",
"accounts": [
{
"name": "distributor",
"isMut": true,
"isSigner": false
},
{
"name": "distributorWallet",
"isMut": true,
"isSigner": false
},
{
"name": "claimCount",
"isMut": true,
"isSigner": false
},
{
"name": "temporal",
"isMut": false,
"isSigner": true
},
{
"name": "payer",
"isMut": false,
"isSigner": true
},
{
"name": "candyMachineConfig",
"isMut": false,
"isSigner": false
},
{
"name": "candyMachine",
"isMut": true,
"isSigner": false
},
{
"name": "candyMachineWallet",
"isMut": true,
"isSigner": false
},
{
"name": "candyMachineMint",
"isMut": true,
"isSigner": false
},
{
"name": "candyMachineMetadata",
"isMut": true,
"isSigner": false
},
{
"name": "candyMachineMasterEdition",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenProgram",
"isMut": false,
"isSigner": false
},
{
"name": "tokenMetadataProgram",
"isMut": false,
"isSigner": false
},
{
"name": "candyMachineProgram",
"isMut": false,
"isSigner": false
},
{
"name": "rent",
"isMut": false,
"isSigner": false
},
{
"name": "clock",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "walletBump",
"type": "u8"
},
{
"name": "claimBump",
"type": "u8"
},
{
"name": "index",
"type": "u64"
},
{
"name": "amount",
"type": "u64"
},
{
"name": "claimantSecret",
"type": "publicKey"
},
{
"name": "proof",
"type": {
"vec": {
"array": [
"u8",
32
]
}
}
}
]
}
],
"accounts": [
{
"name": "MerkleDistributor",
"type": {
"kind": "struct",
"fields": [
{
"name": "base",
"type": "publicKey"
},
{
"name": "bump",
"type": "u8"
},
{
"name": "root",
"type": {
"array": [
"u8",
32
]
}
},
{
"name": "temporal",
"type": "publicKey"
}
]
}
},
{
"name": "ClaimStatus",
"type": {
"kind": "struct",
"fields": [
{
"name": "isClaimed",
"type": "bool"
},
{
"name": "claimant",
"type": "publicKey"
},
{
"name": "claimedAt",
"type": "i64"
},
{
"name": "amount",
"type": "u64"
}
]
}
},
{
"name": "ClaimCount",
"type": {
"kind": "struct",
"fields": [
{
"name": "count",
"type": "u64"
},
{
"name": "claimant",
"type": "publicKey"
}
]
}
},
{
"name": "CandyMachine",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": "publicKey"
},
{
"name": "wallet",
"type": "publicKey"
},
{
"name": "tokenMint",
"type": {
"option": "publicKey"
}
},
{
"name": "config",
"type": "publicKey"
},
{
"name": "data",
"type": {
"defined": "CandyMachineData"
}
},
{
"name": "itemsRedeemed",
"type": "u64"
},
{
"name": "bump",
"type": "u8"
}
]
}
}
],
"types": [
{
"name": "CandyMachineData",
"type": {
"kind": "struct",
"fields": [
{
"name": "uuid",
"type": "string"
},
{
"name": "price",
"type": "u64"
},
{
"name": "itemsAvailable",
"type": "u64"
},
{
"name": "goLiveDate",
"type": {
"option": "i64"
}
}
]
}
}
],
"events": [
{
"name": "ClaimedEvent",
"fields": [
{
"name": "index",
"type": "u64",
"index": false
},
{
"name": "claimant",
"type": "publicKey",
"index": false
},
{
"name": "amount",
"type": "u64",
"index": false
}
]
}
],
"errors": [
{
"code": 300,
"name": "InvalidProof",
"msg": "Invalid Merkle proof."
},
{
"code": 301,
"name": "DropAlreadyClaimed",
"msg": "Drop already claimed."
},
{
"code": 302,
"name": "Unauthorized",
"msg": "Account is not authorized to execute this instruction"
},
{
"code": 303,
"name": "OwnerMismatch",
"msg": "Token account owner did not match intended owner"
},
{
"code": 304,
"name": "TemporalMismatch",
"msg": "Temporal signer did not match distributor"
}
]
}
is there a reason you're not doing:
# Generate the program client from IDL.
async with Program(idl, program_id) as program:
# Execute the RPC.
await program.rpc["initialize"]()
instead of
# Generate the program client from IDL.
program = Program(idl, program_id)
# Execute the RPC.
await program.rpc["initialize"]()
# Close the underlying http client, otherwise we get warnings.
await program.close()
Also, perhaps workspaces can be given an async context manager too?
?
Hi, I want to instantiate a program account and then fetch it as documentation.
from my_client.accounts import PostAccount
connection = Client("https://api.devnet.solana.com")
addr = PublicKey("...")
acc = await PostAccount.fetch(connection, addr)
if acc is None:
raise ValueError("account not found")
obj = acc.to_json()
print(obj)
acc_from_json = PostAccount.from_json(obj)
This is like documentation. And the error:
TypeError Traceback (most recent call last)
f:\programming\intelligent_dex\core_calculations\tests.ipynb Cell 8 in <cell line: 4>()
[1](vscode-notebook-cell:/f%3A/programming/intelligent_dex/core_calculations/tests.ipynb#X11sZmlsZQ%3D%3D?line=0) # fetch an account
[2](vscode-notebook-cell:/f%3A/programming/intelligent_dex/core_calculations/tests.ipynb#X11sZmlsZQ%3D%3D?line=1) addr = PublicKey("FJLoTgfa5QErRQXsKJrx2ULipJQBRfxVd5zs1jzA18W3")
----> [4](vscode-notebook-cell:/f%3A/programming/intelligent_dex/core_calculations/tests.ipynb#X11sZmlsZQ%3D%3D?line=3) acc = await PostAccount.fetch(connection, addr)
[5](vscode-notebook-cell:/f%3A/programming/intelligent_dex/core_calculations/tests.ipynb#X11sZmlsZQ%3D%3D?line=4) if acc is None:
[6](vscode-notebook-cell:/f%3A/programming/intelligent_dex/core_calculations/tests.ipynb#X11sZmlsZQ%3D%3D?line=5) # the fetch method returns null when the account is uninitialized
[7](vscode-notebook-cell:/f%3A/programming/intelligent_dex/core_calculations/tests.ipynb#X11sZmlsZQ%3D%3D?line=6) raise ValueError("account not found")
File f:\programming\intelligent_dex\core_calculations\my_client\accounts\post_account.py:52, in PostAccount.fetch(cls, conn, address, commitment, program_id)
44 @classmethod
45 async def fetch(
46 cls,
(...)
50 program_id: PublicKey = PROGRAM_ID,
51 ) -> typing.Optional["PostAccount"]:
---> 52 resp = await conn.get_account_info(address, commitment=commitment)
53 info = resp.value
54 if info is None:
TypeError: object solders.rpc.responses.GetAccountInfoResp can't be used in 'await' expression
Please help.
Thanks
It can be installed in PCs, but cannot be installed in Mac.
The follow snippet fails while parsing the IDL for Jet Protocol staking program.
import asyncio
from solana.rpc.async_api import AsyncClient
from solana.publickey import PublicKey
from anchorpy import Program, Provider, Wallet
async def main():
client = AsyncClient("https://api.mainnet-beta.solana.com/")
provider = Provider(client, Wallet.local())
program_id = PublicKey("JPLockxtkngHkaQT5AuRYow3HyUv5qWzmhwsCPd653n")
program = await Program.at(
program_id, provider
) # ValidationError from this call
print(program.idl.name)
await program.close()
await main() # asyncio.run(main()) | await main()
For example the candy-guard idl:
"metadata": {
"address": "Guard1JwRhJkVH6XZhzoYxeBVQe872VH6QggF4BWmS9g",
"origin": "anchor",
"binaryVersion": "0.25.0",
"libVersion": "0.25.0"
}
Where origin
, binaryVersion
and libVersion
are not supported.
I am following the tutorial of how to invoke a program via anchorpy, I've built and deployed the sample anchor hello-world application.
When i try to load the IDL, I've got the following error:
idl = Idl.from_json(raw_idl) solders.SerdeJSONError: data did not match any variant of untagged enum IdlAccountItem at line 26 column 8
Also, when I remove the account from the program and try to parse the IDL again, it expects all fields from the metadata
dictionary to be top level.
Versions of all components are the most recent (at the time of writing this):
solana: 1.8.13
anchor: 0.30.0
anchorpy: 0.21
Hi there,
Thanks for taking the time to create anchorpy
and reading this. Any specific reason why pytest is included as a dependency and not in dev dependencies?
When trying to install anchorpy using pipenv an error is raised.
✘ Locking Failed!
[ResolutionFailure]: File "/Users/aleixlopez/PyCharmProjects/olyn-api/lib/python3.9/site-packages/pipenv/resolver.py", line 741, in _main
[ResolutionFailure]: resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev)
[ResolutionFailure]: File "/Users/aleixlopez/PyCharmProjects/olyn-api/lib/python3.9/site-packages/pipenv/resolver.py", line 702, in resolve_packages
[ResolutionFailure]: results, resolver = resolve(
[ResolutionFailure]: File "/Users/aleixlopez/PyCharmProjects/olyn-api/lib/python3.9/site-packages/pipenv/resolver.py", line 684, in resolve
[ResolutionFailure]: return resolve_deps(
[ResolutionFailure]: File "/Users/aleixlopez/PyCharmProjects/olyn-api/lib/python3.9/site-packages/pipenv/utils.py", line 1397, in resolve_deps
[ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
[ResolutionFailure]: File "/Users/aleixlopez/PyCharmProjects/olyn-api/lib/python3.9/site-packages/pipenv/utils.py", line 1110, in actually_resolve_deps
[ResolutionFailure]: resolver.resolve()
[ResolutionFailure]: File "/Users/aleixlopez/PyCharmProjects/olyn-api/lib/python3.9/site-packages/pipenv/utils.py", line 835, in resolve
[ResolutionFailure]: raise ResolutionFailure(message=str(e))
[pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.
First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again.
Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation.
Hint: try $ pipenv lock --pre if it is a pre-release dependency.
ERROR: Could not find a version that matches sumtypes<0.2,==0.1a6,>=0.1a6 (from -r /var/folders/46/y9z0rck93ns35hrd20x9q7tw0000gn/T/pipenv0fra6sqgrequirements/pipenv-7e6nvdvn-constraints.txt (line 23))
Skipped pre-versions: 0.1a1, 0.1a2, 0.1a2, 0.1a3, 0.1a3, 0.1a4, 0.1a4, 0.1a5, 0.1a5, 0.1a6, 0.1a6
There are incompatible versions in the resolved dependencies:
sumtypes==0.1a6 (from -r /var/folders/46/y9z0rck93ns35hrd20x9q7tw0000gn/T/pipenv0fra6sqgrequirements/pipenv-7e6nvdvn-constraints.txt (line 23))
sumtypes dependency in anchorpy is causing this issue.
how to use anchorpy to set token metadata,
such as name, symbol, url
Thank you
Switchboard uses defined types for all instruction parameters even if they are empty. This causes the client generation to fail when it encounters an empty type. Removing all empty types causes the generation to finish successfully.
IDL
https://gist.github.com/gallynaut/60ea292c0f001274ac30bc8de6d3b33d
Example of an IDL entry that causes issues
{
"name": "AggregatorLockParams",
"type": {
"kind": "struct",
"fields": []
}
},
Stack Trace
generating package...
generating program_id.py...
generating errors.py...
generating instructions...
generating types...
Traceback (most recent call last):
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/bin/anchorpy", line 8, in <module>
sys.exit(app())
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/typer/main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/typer/main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/anchorpy/cli.py", line 138, in client_gen
gen_types(idl_obj, out)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 65, in gen_types
gen_type_files(idl, types_dir)
File "/Users/gally/Library/Caches/pypoetry/virtualenvs/switchboardpy-N0s6MIM5-py3.9/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 103, in gen_type_files
formatted = format_str(code, mode=FileMode())
File "src/black/__init__.py", line 1154, in format_str
File "src/black/__init__.py", line 1164, in _format_str_once
File "src/black/parsing.py", line 128, in lib2to3_parse
black.parsing.InvalidInput: Cannot parse: 9:0: @dataclass
Line 13 in 5cb67a0
@kevinheavey
Not quite sure how this has happened, but you have bumped solana to 0.30.0
I am pretty it should still be at 0.29.0
Black seems to fail parsing an IDL file generated by Anchor 0.28.0. I am using anchorpy with the following versions:
anchorpy[cli]==0.17.2
solana==0.30.2
Running anchorpy client-gen ./sol_cerberus.json ./sol_cerberus
throws the following error:
generating package...
generating program_id.py...
generating errors.py...
generating instructions...
generating types...
Traceback (most recent call last):
File "/usr/local/bin/anchorpy", line 8, in <module>
sys.exit(app())
File "/usr/local/lib/python3.9/site-packages/typer/main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1688, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.9/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/typer/main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
File "/usr/local/lib/python3.9/site-packages/anchorpy/cli.py", line 136, in client_gen
gen_types(idl_obj, out)
File "/usr/local/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 67, in gen_types
gen_type_files(idl, types_dir)
File "/usr/local/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 100, in gen_type_files
formatted = format_str(code, mode=FileMode())
File "/usr/local/lib/python3.9/site-packages/black/__init__.py", line 1073, in format_str
dst_contents = _format_str_once(src_contents, mode=mode)
File "/usr/local/lib/python3.9/site-packages/black/__init__.py", line 1083, in _format_str_once
src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
File "/usr/local/lib/python3.9/site-packages/black/parsing.py", line 127, in lib2to3_parse
raise exc from None
black.parsing.InvalidInput: Cannot parse: 33:188: return {"authority": str(self.authority),"recovery": (None if self.recovery is None else str(self.recovery)),"name": self.name,"cached": self.cached,"fee": self.fee,"class_": self.class,"expires_at": self.expires_at}
{
"version": "0.1.7",
"name": "sol_cerberus",
"instructions": [
{
"name": "initializeApp",
"accounts": [
{
"name": "authority",
"isMut": true,
"isSigner": true
},
{
"name": "app",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "arg",
"type": {
"defined": "AppData"
},
"path": "app_data.id"
}
]
}
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "appData",
"type": {
"defined": "AppData"
}
}
]
},
{
"name": "updateApp",
"accounts": [
{
"name": "signer",
"isMut": false,
"isSigner": true
},
{
"name": "app",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "app.id"
}
]
}
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "appData",
"type": {
"defined": "UpdateAppData"
}
}
]
},
{
"name": "deleteApp",
"accounts": [
{
"name": "authority",
"isMut": true,
"isSigner": true
},
{
"name": "app",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "app.id"
}
]
}
},
{
"name": "collector",
"isMut": true,
"isSigner": false
}
],
"args": []
},
{
"name": "addRule",
"accounts": [
{
"name": "signer",
"isMut": true,
"isSigner": true
},
{
"name": "rule",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "arg",
"type": {
"defined": "RuleData"
},
"path": "rule_data.namespace"
},
{
"kind": "arg",
"type": {
"defined": "RuleData"
},
"path": "rule_data.role"
},
{
"kind": "arg",
"type": {
"defined": "RuleData"
},
"path": "rule_data.resource"
},
{
"kind": "arg",
"type": {
"defined": "RuleData"
},
"path": "rule_data.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "sol_cerberus_app.id"
}
]
}
},
{
"name": "solCerberusApp",
"isMut": false,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "sol_cerberus_app.id"
}
]
}
},
{
"name": "solCerberusRole",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusRule",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule.app_id"
}
]
}
},
{
"name": "solCerberusRule2",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule2.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule2.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule2.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule2.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule2.app_id"
}
]
}
},
{
"name": "solCerberusToken",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusMetadata",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusSeed",
"isMut": true,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "seed"
},
{
"kind": "account",
"type": "publicKey",
"path": "signer"
}
]
}
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "ruleData",
"type": {
"defined": "RuleData"
}
}
]
},
{
"name": "deleteRule",
"accounts": [
{
"name": "signer",
"isMut": true,
"isSigner": true
},
{
"name": "rule",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "rule.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "rule.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "rule.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "rule.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "sol_cerberus_app.id"
}
]
}
},
{
"name": "solCerberusApp",
"isMut": false,
"isSigner": false
},
{
"name": "solCerberusRole",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusRule",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule.app_id"
}
]
}
},
{
"name": "solCerberusRule2",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule2.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule2.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule2.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule2.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule2.app_id"
}
]
}
},
{
"name": "solCerberusToken",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusMetadata",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusSeed",
"isMut": true,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "seed"
},
{
"kind": "account",
"type": "publicKey",
"path": "signer"
}
]
}
},
{
"name": "collector",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "assignRole",
"accounts": [
{
"name": "signer",
"isMut": true,
"isSigner": true
},
{
"name": "role",
"isMut": true,
"isSigner": false
},
{
"name": "solCerberusApp",
"isMut": false,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "sol_cerberus_app.id"
}
]
}
},
{
"name": "solCerberusRole",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusRule",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule.app_id"
}
]
}
},
{
"name": "solCerberusToken",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusMetadata",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusSeed",
"isMut": true,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "seed"
},
{
"kind": "account",
"type": "publicKey",
"path": "signer"
}
]
}
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "assignRoleData",
"type": {
"defined": "AssignRoleData"
}
}
]
},
{
"name": "deleteAssignedRole",
"accounts": [
{
"name": "signer",
"isMut": true,
"isSigner": true
},
{
"name": "role",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "account",
"type": "string",
"account": "Role",
"path": "role.role"
},
{
"kind": "account",
"type": {
"option": "publicKey"
},
"account": "Role",
"path": "role.address"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "sol_cerberus_app.id"
}
]
}
},
{
"name": "solCerberusApp",
"isMut": false,
"isSigner": false
},
{
"name": "solCerberusRole",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusRule",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule.app_id"
}
]
}
},
{
"name": "solCerberusToken",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusMetadata",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusSeed",
"isMut": true,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "seed"
},
{
"kind": "account",
"type": "publicKey",
"path": "signer"
}
]
}
},
{
"name": "collector",
"isMut": true,
"isSigner": false
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": []
},
{
"name": "updateCache",
"docs": [
"* Updates either app.roles_updated_at or app.rules_updated_at fields, so clients\n * can keep track and cache roles & rules accordingly."
],
"accounts": [
{
"name": "authority",
"isMut": false,
"isSigner": true
},
{
"name": "app",
"isMut": true,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "app.id"
}
]
},
"relations": [
"authority"
]
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "cacheUpdated",
"type": "u8"
}
]
},
{
"name": "allowed",
"docs": [
"* Checks if the current user is authorized to run the instruction,\n * throwing \"Unauthorized\" error otherwise."
],
"accounts": [
{
"name": "signer",
"isMut": true,
"isSigner": true
},
{
"name": "solCerberusApp",
"isMut": false,
"isSigner": false,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "app"
},
{
"kind": "account",
"type": "publicKey",
"account": "App",
"path": "sol_cerberus_app.id"
}
]
}
},
{
"name": "solCerberusRule",
"isMut": false,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "account",
"type": "u8",
"account": "Rule",
"path": "sol_cerberus_rule.namespace"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.role"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.resource"
},
{
"kind": "account",
"type": "string",
"account": "Rule",
"path": "sol_cerberus_rule.permission"
},
{
"kind": "account",
"type": "publicKey",
"account": "Rule",
"path": "sol_cerberus_rule.app_id"
}
]
}
},
{
"name": "solCerberusRole",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusToken",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusMetadata",
"isMut": false,
"isSigner": false,
"isOptional": true
},
{
"name": "solCerberusSeed",
"isMut": true,
"isSigner": false,
"isOptional": true,
"pda": {
"seeds": [
{
"kind": "const",
"type": "string",
"value": "seed"
},
{
"kind": "account",
"type": "publicKey",
"path": "signer"
}
]
}
},
{
"name": "systemProgram",
"isMut": false,
"isSigner": false
}
],
"args": [
{
"name": "allowedRule",
"type": {
"defined": "AllowedRule"
}
}
]
}
],
"accounts": [
{
"name": "App",
"type": {
"kind": "struct",
"fields": [
{
"name": "id",
"type": "publicKey"
},
{
"name": "authority",
"type": "publicKey"
},
{
"name": "recovery",
"type": {
"option": "publicKey"
}
},
{
"name": "bump",
"type": "u8"
},
{
"name": "name",
"type": "string"
},
{
"name": "rolesUpdatedAt",
"type": "i64"
},
{
"name": "rulesUpdatedAt",
"type": "i64"
},
{
"name": "cached",
"type": "bool"
},
{
"name": "fee",
"type": {
"option": "u64"
}
},
{
"name": "class",
"type": "u8"
},
{
"name": "expiresAt",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "Seed",
"type": {
"kind": "struct",
"fields": [
{
"name": "initialized",
"type": "bool"
}
]
}
},
{
"name": "Role",
"type": {
"kind": "struct",
"fields": [
{
"name": "appId",
"type": "publicKey"
},
{
"name": "address",
"type": {
"option": "publicKey"
}
},
{
"name": "role",
"type": "string"
},
{
"name": "addressType",
"type": {
"defined": "AddressType"
}
},
{
"name": "expiresAt",
"type": {
"option": "i64"
}
},
{
"name": "bump",
"type": "u8"
}
]
}
},
{
"name": "Rule",
"type": {
"kind": "struct",
"fields": [
{
"name": "appId",
"type": "publicKey"
},
{
"name": "namespace",
"type": "u8"
},
{
"name": "role",
"type": "string"
},
{
"name": "resource",
"type": "string"
},
{
"name": "permission",
"type": "string"
},
{
"name": "expiresAt",
"type": {
"option": "i64"
}
},
{
"name": "bump",
"type": "u8"
}
]
}
}
],
"types": [
{
"name": "AllowedRule",
"type": {
"kind": "struct",
"fields": [
{
"name": "appId",
"type": "publicKey"
},
{
"name": "namespace",
"type": "u8"
},
{
"name": "resource",
"type": "string"
},
{
"name": "permission",
"type": "string"
}
]
}
},
{
"name": "AppData",
"type": {
"kind": "struct",
"fields": [
{
"name": "id",
"type": "publicKey"
},
{
"name": "recovery",
"type": {
"option": "publicKey"
}
},
{
"name": "name",
"type": "string"
},
{
"name": "cached",
"type": "bool"
}
]
}
},
{
"name": "UpdateAppData",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": "publicKey"
},
{
"name": "recovery",
"type": {
"option": "publicKey"
}
},
{
"name": "name",
"type": "string"
},
{
"name": "cached",
"type": "bool"
},
{
"name": "fee",
"type": {
"option": "u64"
}
},
{
"name": "class",
"type": "u8"
},
{
"name": "expiresAt",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "AssignRoleData",
"type": {
"kind": "struct",
"fields": [
{
"name": "address",
"type": {
"option": "publicKey"
}
},
{
"name": "role",
"type": "string"
},
{
"name": "addressType",
"type": {
"defined": "AddressType"
}
},
{
"name": "expiresAt",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "RuleData",
"type": {
"kind": "struct",
"fields": [
{
"name": "namespace",
"type": "u8"
},
{
"name": "role",
"type": "string"
},
{
"name": "resource",
"type": "string"
},
{
"name": "permission",
"type": "string"
},
{
"name": "expiresAt",
"type": {
"option": "i64"
}
}
]
}
},
{
"name": "Classes",
"docs": [
"Classes:",
"0 => Trial (Apps with default fees)",
"1 => Free (Apps with no fees)"
],
"type": {
"kind": "enum",
"variants": [
{
"name": "Trial"
},
{
"name": "Free"
}
]
}
},
{
"name": "CacheUpdated",
"docs": [
"CacheUpdated:",
"0 => Roles (When roles change)",
"1 => Rules (When rules change)"
],
"type": {
"kind": "enum",
"variants": [
{
"name": "Roles"
},
{
"name": "Rules"
}
]
}
},
{
"name": "AddressType",
"type": {
"kind": "enum",
"variants": [
{
"name": "Wallet"
},
{
"name": "Nft"
},
{
"name": "Collection"
}
]
}
},
{
"name": "Namespaces",
"docs": [
"Namespaces:",
"0 => Rule (Normal permissions)",
"1 => AssignRole (White list of roles that can be assigned by certain role)",
"2 => DeleteAssignRole (White list of roles that can be deleted by certain role)",
"3 => AddRuleNSRole (White list of namespaces and roles that can be created by certain role)",
"4 => AddRuleResourcePerm (White list of resources and permissions that can be created by certain role)",
"5 => DeleteRuleNSRole (White list of namespaces and roles that can be deleted by certain role)",
"6 => DeleteRuleResourcePerm (White list of resources and permissions that can be deleted by certain role)"
],
"type": {
"kind": "enum",
"variants": [
{
"name": "Rule"
},
{
"name": "AssignRole"
},
{
"name": "DeleteAssignRole"
},
{
"name": "AddRuleNSRole"
},
{
"name": "AddRuleResourcePerm"
},
{
"name": "DeleteRuleNSRole"
},
{
"name": "DeleteRuleResourcePerm"
}
]
}
}
],
"events": [
{
"name": "AppChanged",
"fields": [
{
"name": "time",
"type": "i64",
"index": false
},
{
"name": "appId",
"type": "publicKey",
"index": true
},
{
"name": "authority",
"type": "publicKey",
"index": false
}
]
},
{
"name": "RolesChanged",
"fields": [
{
"name": "time",
"type": "i64",
"index": false
},
{
"name": "appId",
"type": "publicKey",
"index": true
}
]
},
{
"name": "RulesChanged",
"fields": [
{
"name": "time",
"type": "i64",
"index": false
},
{
"name": "appId",
"type": "publicKey",
"index": true
}
]
}
],
"errors": [
{
"code": 6000,
"name": "UnauthorizedAuthorityUpdate",
"msg": "Only current Authority or Recovery accounts can update the App authority"
},
{
"code": 6001,
"name": "InvalidRule",
"msg": "Role, Resource or Permission must be betwen 1 and 16 alphanumeric characters long"
},
{
"code": 6002,
"name": "InvalidRole",
"msg": "Role must be between 1 and 16 alphanumeric characters long"
},
{
"code": 6003,
"name": "StringTooShort",
"msg": "The provided string is too short"
},
{
"code": 6004,
"name": "StringTooLong",
"msg": "The provided string is too long"
},
{
"code": 6005,
"name": "Unauthorized",
"msg": "The user does not have enough privileges to perform this action"
},
{
"code": 6006,
"name": "InvalidAppID",
"msg": "The Sol Cerberus APP ID does not match the one defined in the program"
},
{
"code": 6007,
"name": "InvalidAddressType",
"msg": "Invalid address type, mus be either 'Wallet', 'Nft', 'Collection' or a wildcard '*'"
},
{
"code": 6008,
"name": "InvalidNamespace",
"msg": "Invalid namespace, must be either an u8 number (0-255) or a wildcard '*'"
},
{
"code": 6009,
"name": "MissingSolCerberusAppId",
"msg": "SOL_CERBERUS_APP_ID is missing on lib.rs"
},
{
"code": 6010,
"name": "MissingSeedAccount",
"msg": "The Sol Cerberus Seed account is missing"
},
{
"code": 6011,
"name": "UnauthorizedProgramAuthority",
"msg": "Only program authority can perform this action"
},
{
"code": 6012,
"name": "InsufficientFunds",
"msg": "Insufficient funds for transaction"
}
],
"metadata": {
"address": "SCERbrcgSPwgkrJ7j4TABr17dhYzdgiwPZUSSfFPt8x"
}
}
From this IDL json: https://gist.github.com/cdb18/43cff60234a9e2a02949347f11c91240
Traceback (most recent call last):
File "/opt/homebrew/bin/anchorpy", line 8, in <module>
sys.exit(app())
File "/opt/homebrew/lib/python3.9/site-packages/typer/main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/typer/main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/cli.py", line 110, in client_gen
idl_obj = Idl.from_json(idl_dict)
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/idl.py", line 272, in from_json
return deserialize(cls, idl)
File "/opt/homebrew/lib/python3.9/site-packages/apischema/utils.py", line 400, in wrapper
return wrapped(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/apischema/deserialization/__init__.py", line 891, in deserialize
return deserialization_method(
File "apischema/deserialization/methods.pyx", line 494, in apischema.deserialization.methods.ObjectMethod.deserialize
File "apischema/deserialization/methods.pyx", line 495, in apischema.deserialization.methods.ObjectMethod.deserialize
File "apischema/deserialization/methods.pyx", line 1078, in apischema.deserialization.methods.ObjectMethod_deserialize
apischema.validation.errors.ValidationError: ValidationError: [{'loc': ['accounts', 0, 'docs'], 'err': 'unexpected property'}, {'loc': ['accounts', 1, 'docs'], 'err': 'unexpected property'}, {'loc': ['instructions', 6, 'accounts', 13, 'accounts'], 'err': 'missing property'}, {'loc': ['instructions', 6, 'accounts', 13, 'docs'], 'err': 'unexpected property'}, {'loc': ['instructions', 6, 'accounts', 13, 'docs'], 'err': 'unexpected property'}, {'loc': ['instructions', 6, 'accounts', 13, 'isMut'], 'err': 'unexpected property'}, {'loc': ['instructions', 6, 'accounts', 13, 'isSigner'], 'err': 'unexpected property'}, {'loc': ['types', 0, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 0, 'type', 'fields'], 'err': 'unexpected property'}, {'loc': ['types', 0, 'type', 'fields', 2, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 0, 'type', 'fields', 3, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 0, 'type', 'fields', 13, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 0, 'type', 'kind'], 'err': "not one of ['enum'] (oneOf)"}, {'loc': ['types', 0, 'type', 'variants'], 'err': 'missing property'}, {'loc': ['types', 1, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 1, 'type', 'fields'], 'err': 'unexpected property'}, {'loc': ['types', 1, 'type', 'fields', 1, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 1, 'type', 'kind'], 'err': "not one of ['enum'] (oneOf)"}, {'loc': ['types', 1, 'type', 'variants'], 'err': 'missing property'}, {'loc': ['types', 4, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 6, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 6, 'type', 'fields'], 'err': 'unexpected property'}, {'loc': ['types', 6, 'type', 'fields', 0, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 6, 'type', 'fields', 1, 'docs'], 'err': 'unexpected property'}, {'loc': ['types', 6, 'type', 'kind'], 'err': "not one of ['enum'] (oneOf)"}, {'loc': ['types', 6, 'type', 'variants'], 'err': 'missing property'}]
During a docker container build with anchor.py==0.8.0 in requirements.txt
we are encountering the following error -
ERROR: Could not find a version that satisfies the requirement pyheck== (from versions: 0.1.1, 0.1.2, 0.1.3, 0.1.4, 0.1.5)
ERROR: No matching distribution found for pyheck==
bash-5.1# pip install --use-deprecated=legacy-resolver pyheck==0.1.5
Collecting pyheck==0.1.5
Downloading pyheck-0.1.5.tar.gz (3.4 kB)
Installing build dependencies ... error
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 /usr/lib/python3.9/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-8jbs9l9k/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'maturin>=0.12,<0.13'
cwd: None
Complete output (57 lines):
Collecting maturin<0.13,>=0.12
Downloading maturin-0.12.11.tar.gz (141 kB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing wheel metadata: started
Preparing wheel metadata: finished with status 'done'
Collecting tomli>=1.1.0
Using cached tomli-2.0.1-py3-none-any.whl (12 kB)
Building wheels for collected packages: maturin
Building wheel for maturin (PEP 517): started
Building wheel for maturin (PEP 517): finished with status 'error'
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 /usr/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmp5xajsdl4
cwd: /tmp/pip-install-4hr6qk0z/maturin_3c608d77a7bc49019ad66524cd05095f
Complete output (36 lines):
running bdist_wheel
running build
installing to build/bdist.linux-x86_64/wheel
running install
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module>
main()
File "/usr/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
File "/usr/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py", line 204, in build_wheel
return _build_backend().build_wheel(wheel_directory, config_settings,
File "/tmp/pip-build-env-c2ng6n20/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 216, in build_wheel
return self._build_with_temp_dir(['bdist_wheel'], '.whl',
File "/tmp/pip-build-env-c2ng6n20/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 202, in _build_with_temp_dir
self.run_setup()
File "/tmp/pip-build-env-c2ng6n20/overlay/lib/python3.9/site-packages/setuptools/build_meta.py", line 145, in run_setup
exec(compile(code, __file__, 'exec'), locals())
File "setup.py", line 118, in <module>
setup(
File "/tmp/pip-build-env-c2ng6n20/overlay/lib/python3.9/site-packages/setuptools/__init__.py", line 153, in setup
return distutils.core.setup(**attrs)
File "/usr/lib/python3.9/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib/python3.9/distutils/dist.py", line 966, in run_commands
self.run_command(cmd)
File "/usr/lib/python3.9/distutils/dist.py", line 985, in run_command
cmd_obj.run()
File "/tmp/pip-build-env-c2ng6n20/overlay/lib/python3.9/site-packages/wheel/bdist_wheel.py", line 335, in run
self.run_command('install')
File "/usr/lib/python3.9/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/usr/lib/python3.9/distutils/dist.py", line 985, in run_command
cmd_obj.run()
File "setup.py", line 60, in run
raise RuntimeError(
RuntimeError: cargo not found in PATH. Please install rust (https://www.rust-lang.org/tools/install) and try again
Is there a known fix for this?
We have tried adding a rust dependency manually in a Docker build to work around it with little luck - things get stuck indefinitely in the following stage:
Collecting pyheck<0.2.0,>=0.1.4
Using cached pyheck-0.1.5.tar.gz (3.4 kB)
Installing build dependencies ... -
Any recommendations would be greatly appreciated!
Thank you for this library.
Can you give an example of how to listen for events emitted from a program?
I have a program id - 6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P that I'm trying to listen to the CreateEvent message.
This is the IDL:
https://raw.githubusercontent.com/Allen-Taylor/solana-scripts/main/message_8.txt
Do you have a working example on listening to events?
Thank you!
Below error occurs when running anchorpy client-gen
on an IDL where there are types
with the same name
due to this constraint. Quick fix solution was to manually make each type name unique, but would be great to handle this dynamically later.
generating package...
generating program_id.py...
generating errors.py...
generating instructions...
generating types...
Traceback (most recent call last):
File "/opt/homebrew/bin/anchorpy", line 8, in <module>
sys.exit(app())
File "/opt/homebrew/lib/python3.9/site-packages/typer/main.py", line 214, in __call__
return get_command(self)(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/opt/homebrew/lib/python3.9/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/typer/main.py", line 500, in wrapper
return callback(**use_params) # type: ignore
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/cli.py", line 138, in client_gen
gen_types(idl_obj, out)
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 65, in gen_types
gen_type_files(idl, types_dir)
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 101, in gen_type_files
types_code = gen_types_code(idl, types_dir)
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 123, in gen_types_code
else gen_enum(idl, ty.name, ty_type.variants)
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 467, in gen_enum
rec_unnamed = _make_unnamed_field_record(
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/clientgen/types.py", line 315, in _make_unnamed_field_record
encodable = _field_to_encodable(
File "/opt/homebrew/lib/python3.9/site-packages/anchorpy/clientgen/common.py", line 231, in _field_to_encodable
raise ValueError(f"Type not found {defined}")
ValueError: Type not found Swap
Hello, I have a program in normal Anchor JS which works completely fine but when I try to rewrite it in python I get the following error: ("Provided incorrect number of args to instruction=exchange2. Expected ['expected_taker_amount', 'expected_mint']", "Received (100000000, mintAddress here, {'accounts': etc..)
I'm sending the request this way: sendTransaction = await meProgram.rpc['exchange2'](itemPriceU64, PublicKey(mintAddress), transactionObject) which is pretty much the same as I do with JS, although with the python client I get the issue I mentioned above. How would I go about fixing this? Thanks in advance.
Python Version = 3.9.7 64-bit
AnchorPy Version = 0.6.0
Hi,
I was just wondering if it would be possible to trigger a release?
It would be super helpful as we are currently trying to complete our solana integration! 🎉
I am in dependency hell pending the websockets relaxation we resolved in;
I'm trying to generate the client for the metaplex metadata program IDL, but seems that hashmap type is missing the mapping.
https://raw.githubusercontent.com/metaplex-foundation/metaplex-program-library/master/token-metadata/js/idl/mpl_token_metadata.json
anchorpy client-gen mpl_token_metadata.json metaplex_client
Error:
solders.SerdeJSONError: unknown variant `hashMap`, expected one of `bool`, `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `f32`, `u64`, `i64`, `f64`, `u128`, `i128`, `bytes`, `string`, `publicKey`, `defined`, `option`, `vec`, `array` at line 4498 column 5
Hey,
I'm running into this error, not sure what's going wrong.
Quite new using anchorpy, let me know if I can provide with any extra info, trying to figure it out in my side too!.
(<class 'UnicodeDecodeError'>, UnicodeDecodeError('utf-8', b'\x02F\xca@\xb2E#\xa3Y>\xa7\xe8\xe8\xbe\xb3\xebu%\x9ak\x9a\xa3\x98\xb7\xe9\xec\x01NI\xa1\x19\xb3O\xfb%\x90n;d[\x8d\xb5\x83J\xf5\xac\x16B\xce\xa4\x10\xf9VY\xc6v\xb3\x1d5\x88\x04\xa4\xf42\x0e&\x0e\x98o"\xe2\xafz\xb1\x8e-3\xc7\x89#\xa6\xe4u\x17\x7f\xdb\xe38\x0f)\x8e\xae\x9c\xb2\xe7\x9a&Q\xc4\xcf\xe1\x9au\xf2\xbf6\xf1\x06\xa4]\xc4E\xe8X!\xe3\xea\xf2\x1b+jL\x9aJ\xb7\x17\x107\t\x02\x00\x02\x04j&\x7f\x8a\xa8|\n\x8a\x83\xe0\x90\xb1\xd5\xc1\xca\xb0!qYZL\xf6\xc5C:\x03\x1a\xb1\x88\xe2\xda\xd5]D\x88\x7fB\n6v\x81\xaa\xfe\x14V@^h\x99\xdf\xec\xef\xc6ZiY\xf1\x82x\xfe\x82\x9bF\x81\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xa54\x985w\xd8\xa7\x01\xf7\xc9\xef\xb1\xcd\xbc!\xc7\x97\xce\x02\'\xba\xb6\x02AX\xf8\x0b\x1bz\xec\xbb\x9e\x11\xc4\xf7!\xa0G\xcbY\x99C\xdb\xdd\x91|\x00\x7fGXCW\xc6@\x16xo&\xc0>u\xdf\x92!\x01\x03\x04\x00\x00\x01\x02\x7fz\x00\x00\x00localhost:5001/v1_1_0/assets/37570e1b-a121-4e3a-83f2-dd7525ac4d89/web3/solana/7H5XZos2ScDSYKCpvdKe9vpamP8wXYnDZoAJrwNzqZNG\x00', 2, 3, 'invalid continuation byte'), <traceback object at 0x7fe82699d940>)
[2022-08-18 19:24:02,209] ERROR in http: Traceback (most recent call last):
File "app/errors.py", line 52, in wrapper
return f(*args, **kwargs)
File "/app/utils/blueprints.py", line 73, in wrapper
return fn(*args, **kwargs)
File "/web3/routes.py", line 24, in tokenize_asset_on_chain_route
token = tokenize_asset_on_chain_service(asset_id, transaction_id, data)
File "/web3/services.py", line 138, in tokenize_asset_on_chain_service
response = send_solana_transaction_to_chain(transaction_model)
File "/web3/olyn_solana/service.py", line 65, in send_solana_transaction_to_chain
print(client.simulate_transaction(txn.serialize(), sig_verify=True))
File "/lib/python3.9/site-packages/solana/rpc/api.py", line 1421, in simulate_transaction
args = self._simulate_transaction_args(txn, sig_verify, commitment)
File "/lib/python3.9/site-packages/solana/rpc/core.py", line 433, in _simulate_transaction_args
wire_format = txn.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 2: invalid continuation byte
Regards,
Aleix
Mr. Kev,
gm, I really need to contact you to discuss the platform I'm working on's progress. is there any way I could get hold of you in discord or twitter?
Python version: 3.9
anchorpy version: 0.9.4
solana version: 0.25.1
Not support sub-node 'docs' in accounts nodes, that will throw valid can't pass exception,
remove all of 'docs' nodes, the Idl.from_json method worked fine
using raydium idl
anchorpy client-gen
fails with error: "unknown variant alias
, expected struct
or enum
"
when encountering this in the types
section:
{"name":"TickArryBitmap","type":{"kind":"alias","value":{"array":["u64",8]}}}
this error is raised:
/anchorpy/cli.py", line 109, in client_gen
idl_obj = Idl.from_json(idl.read_text())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
solders.SerdeJSONError: unknown variant `alias`, expected `struct` or `enum` at line 1 column 20942
using latest version of anchorpy
user error is not out of the realm of possibility ;)
I might be missing something, but the baked-in a static PROGRAM_ID
in ix builder helpers and Account
struct fetch methods seems to reduce the flexibility of the generated client. To be able to point this client to a program deployed on different clusters with potentially different addresses, I find myself having to comment out the program_id
check in account fetch methods, and wrap ix builders in something like:
def make_deposit_ix(accounts: DepositAccounts, program_id: PublicKey):
ix = generated.deposit(generated.DepositAccounts(...))
ix = TransactionInstruction(ix.keys, program_id, ix.data)
return ix
Instead, a possibility is for the fetch method to either:
Program
object instead of a straight AsyncClient
, and use the program_id
it packsprogram_id
argument defaulting to the static PROGRAM_ID
and ix builders could use the optional program_id
arg as well.
Let me know what you think. I can create a PR for these changes if interested.
Is there a reason not to use the none async client in solana.rpc?
Hey! Thanks for the great lib.
Could you please tell if there are any plans on updating solana to 0.34?
Hi,
When I try to install anchorpy 0.19.0 I get the following error:
ModuleNotFoundError: No module named 'pytest_asyncio'
[CMD]: poetry add pytest_asyncio
[CMD]: poetry run python -m main.py (script)
ModuleNotFoundError: No module named 'pytest_xprocess'
[CMD]: poetry add pytest_xprocess
[CMD]: poetry run python -m main.py (script)
ModuleNotFoundError: No module named 'pytest_xprocess'
It's possible that this is an issue on my end, but I don't know what would cause it in that case.
Hi, I am running the AsyncClient to fetch accounts,
addr = PublicKey("...")
async def main():
async with AsyncClient("https://api.devnet.solana.com") as client:
res = await client.is_connected()
print(res) # True
# Alternatively, close the client explicitly instead of using a context manager:
client = AsyncClient("https://api.devnet.solana.com")
res = await client.is_connected()
print(res) # True
await client.close()
acc = await PostAccount.fetch(AsyncClient, addr)
if acc is None:
# the fetch method returns null when the account is uninitialized
raise ValueError("account not found")
# convert to a JSON object
obj = acc.to_json()
print(obj)
# load from JSON
acc_from_json = PostAccount.from_json(obj)
asyncio.run(main())
The traceback:
True
True
Traceback (most recent call last):
File "F:\programming\intelligent_dex\core_calculations\order_matching.py", line 41, in <module>
asyncio.run(main())
File "C:\Anaconda3\envs\solana\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Anaconda3\envs\solana\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "F:\programming\intelligent_dex\core_calculations\order_matching.py", line 27, in main
acc = await PostAccount.fetch(AsyncClient, addr)
File "F:\programming\intelligent_dex\core_calculations\my_client\accounts\post_account.py", line 52, in fetch
resp = await conn.get_account_info(address, commitment=commitment)
TypeError: get_account_info() missing 1 required positional argument: 'pubkey'
Hi, cool project! I'm trying to figure out whether I can parse JSON from, eg, getTransaction
RPC call into a transaction and list of IDL-aware instructions with named args and accounts in the context.
Not to build instructions to send over RPC, but to parse historical transactions / logs events.
Everytime I try using the anchorpy client-gen idl.json client
command, I get this kind of error
apischema.validation.errors.ValidationError: ValidationError(messages=[], children={'instructions': ValidationError(messages=[], children={12: ValidationError(messages=[], children={'accounts': ValidationError(messages=[], children={2: ValidationError(messages=[], children={'isSigner': ValidationError(messages=['unexpected property'], children={}), 'accounts': ValidationError(messages=['missing property'], children={}), 'isMut': ValidationError(messages=['unexpected property'], children={}), 'isOptional': ValidationError(messages=['unexpected property', 'unexpected property'], children={})})})}), 16: ValidationError(messages=[], children={'accounts': ValidationError(messages=[], children={1: ValidationError(messages=[], children={'isSigner': ValidationError(messages=['unexpected property'], children={}), 'accounts': ValidationError(messages=['missing property'], children={}), 'isMut': ValidationError(messages=['unexpected property'], children={}), 'isOptional': ValidationError(messages=['unexpected property', 'unexpected property'], children={})})})}), 17: ValidationError(messages=[], children={'accounts': ValidationError(messages=[], children={1: ValidationError(messages=[], children={'isSigner': ValidationError(messages=['unexpected property'], children={}), 'accounts': ValidationError(messages=['missing property'], children={}), 'isMut': ValidationError(messages=['unexpected property'], children={}), 'isOptional': ValidationError(messages=['unexpected property', 'unexpected property'], children={})})})}), 18: ValidationError(messages=[], children={'accounts': ValidationError(messages=[], children={1: ValidationError(messages=[], children={'isSigner': ValidationError(messages=['unexpected property'], children={}), 'accounts': ValidationError(messages=['missing property'], children={}), 'isMut': ValidationError(messages=['unexpected property'], children={}), 'isOptional': ValidationError(messages=['unexpected property', 'unexpected property'], children={})})})})})})
And its the same for all idls I have tried. Not sure what the cause of this issue is
Hey!
typer = { version = "0.4.1", optional = true }
ipython = { version = "^8.0.1", optional = true }
genpy = {version = "^2021.1", optional = true }
black = {version = "^22.3.0", optional = true }
autoflake = { version = "^1.4", optional = true }
Is there a reason those are not listed as dev dependencies? With the current approach, they make dependency resolution in tools using anchorpy
harder.
pip install
is creating the following wheel on both iTerm
(amd64) and iTerm Rosetta
(i386).
Created wheel for pyheck: filename=pyheck-0.1.4-cp39-abi3-macosx_10_7_x86_64.whl size=297671 sha256=48da256ebeaaae2a04fad1369aaaea3832f7642cce8dce96ee570dc2b03861b1
In both cases, when importing anchorpy
, it imports pyheck
, which throws throws:
ImportError: dlopen(/Users/will/.pyenv/versions/test/lib/python3.9/site-packages/pyheck/pyheck.abi3.so, 0x0002): tried: '/Users/will/.pyenv/versions/test/lib/python3.9/site-packages/pyheck/pyheck.abi3.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/local/lib/pyheck.abi3.so' (no such file), '/usr/lib/pyheck.abi3.so' (no such file), '/Users/will/.pyenv/versions/3.9.1/envs/test/lib/python3.9/site-packages/pyheck/pyheck.abi3.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/local/lib/pyheck.abi3.so' (no such file), '/usr/lib/pyheck.abi3.so' (no such file)
Thanks!
With the current set of dependencies when running make test
I get the error:
tests/test_swap.py:32: in <module>
from pyserum.open_orders_account import make_create_account_instruction
.venv/lib/python3.10/site-packages/pyserum/open_orders_account.py:9: in <module>
from solana.rpc.types import Commitment, MemcmpOpts, RPCResponse
ImportError: cannot import name 'RPCResponse' from 'solana.rpc.types'
which is actually correct because pyserum-0.5.0a0
is not updated to the latest version of solanapy and hence the error
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.