solana-chainkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chainkit/__init__.py +16 -0
- chainkit/addresses.py +43 -0
- chainkit/amounts.py +66 -0
- chainkit/constants.py +58 -0
- chainkit/instructions.py +73 -0
- chainkit/parse.py +84 -0
- chainkit/py.typed +0 -0
- chainkit/pyth.py +92 -0
- chainkit/rpc.py +139 -0
- chainkit/transactions.py +146 -0
- solana_chainkit-0.1.0.dist-info/METADATA +217 -0
- solana_chainkit-0.1.0.dist-info/RECORD +15 -0
- solana_chainkit-0.1.0.dist-info/WHEEL +4 -0
- solana_chainkit-0.1.0.dist-info/licenses/LICENSE +202 -0
- solana_chainkit-0.1.0.dist-info/licenses/NOTICE +4 -0
chainkit/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""chainkit: production-grade building blocks for USDC payments on Solana, in Python.
|
|
2
|
+
|
|
3
|
+
Modules (import what you need; nothing here touches the network on import):
|
|
4
|
+
|
|
5
|
+
chainkit.constants program ids, clusters, Circle's exact USDC mints
|
|
6
|
+
chainkit.amounts exact USDC amounts as integer atomic units, never floats
|
|
7
|
+
chainkit.addresses strict address parsing, associated token account derivation
|
|
8
|
+
chainkit.instructions range-checked transferChecked, createIdempotent, compute budget, memo
|
|
9
|
+
chainkit.transactions build a USDC transfer; decode any message into facts before signing
|
|
10
|
+
chainkit.parse detect payments from balance deltas (works for any wallet or exchange)
|
|
11
|
+
chainkit.rpc JSON-RPC client with ordered failover and transient-error signalling
|
|
12
|
+
chainkit.pyth verified SOL/USD (or any Pyth feed) read directly from Solana
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
__version__ = '0.1.0'
|
|
16
|
+
__all__ = ['__version__']
|
chainkit/addresses.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Address parsing and associated token account (ATA) derivation."""
|
|
2
|
+
from solders.pubkey import Pubkey
|
|
3
|
+
|
|
4
|
+
from .constants import ATA_PROGRAM, TOKEN_PROGRAM
|
|
5
|
+
|
|
6
|
+
_TOKEN_PROGRAM = Pubkey.from_string(TOKEN_PROGRAM)
|
|
7
|
+
_ATA_PROGRAM = Pubkey.from_string(ATA_PROGRAM)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AddressError(ValueError):
|
|
11
|
+
"""The value is not a valid Solana address."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_pubkey(value: object) -> Pubkey:
|
|
15
|
+
"""Parse a base58 Solana address strictly: surrounding spaces are trimmed, everything else must round-trip."""
|
|
16
|
+
if not isinstance(value, str):
|
|
17
|
+
raise AddressError('That is not a valid Solana address.')
|
|
18
|
+
text = value.strip()
|
|
19
|
+
if not 32 <= len(text) <= 44:
|
|
20
|
+
raise AddressError('That is not a valid Solana address.')
|
|
21
|
+
try:
|
|
22
|
+
key = Pubkey.from_string(text)
|
|
23
|
+
except ValueError:
|
|
24
|
+
raise AddressError('That is not a valid Solana address.') from None
|
|
25
|
+
if str(key) != text: # pragma: no cover - defensive: base58 decoding is canonical in solders today
|
|
26
|
+
raise AddressError('That is not a valid Solana address.')
|
|
27
|
+
return key
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _key(value: str | Pubkey) -> Pubkey:
|
|
31
|
+
return value if isinstance(value, Pubkey) else parse_pubkey(value)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def derive_ata(owner: str | Pubkey, mint: str | Pubkey) -> Pubkey:
|
|
35
|
+
"""The associated token account of `owner` for `mint` under the classic SPL Token program."""
|
|
36
|
+
ata, _bump = Pubkey.find_program_address([bytes(_key(owner)), bytes(_TOKEN_PROGRAM), bytes(_key(mint))],
|
|
37
|
+
_ATA_PROGRAM)
|
|
38
|
+
return ata
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_on_curve(address: str | Pubkey) -> bool:
|
|
42
|
+
"""True for addresses that can sign (wallets); False for program-derived addresses such as token accounts."""
|
|
43
|
+
return _key(address).is_on_curve()
|
chainkit/amounts.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""USDC amounts as integer atomic units (6 decimals). Never floats.
|
|
2
|
+
|
|
3
|
+
`to_atomic('150.25') == 150_250_000`. Integers in atomic units are the only safe representation for ledger and
|
|
4
|
+
on-chain amounts; decimal strings are for people.
|
|
5
|
+
"""
|
|
6
|
+
import re
|
|
7
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
8
|
+
|
|
9
|
+
from .constants import ATOMIC_PER_USDC, U64_MAX, USDC_DECIMALS
|
|
10
|
+
|
|
11
|
+
# ASCII digits only: \d would also match other scripts (for example Arabic-Indic digits), which Decimal accepts.
|
|
12
|
+
_PLAIN = re.compile(r'[0-9]+(\.[0-9]+)?')
|
|
13
|
+
_GROUPED = re.compile(r'[0-9]{1,3}(,[0-9]{3})+(\.[0-9]+)?')
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AmountError(ValueError):
|
|
17
|
+
"""The value is not a valid positive USDC amount."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def to_atomic(value: str | Decimal) -> int:
|
|
21
|
+
"""Parse a positive USDC amount into atomic units.
|
|
22
|
+
|
|
23
|
+
Accepts a decimal string ('150.25', '1,250.50') or a Decimal. Rejects floats (binary rounding), plain
|
|
24
|
+
integers (ambiguous: dollars or atomic units?), scientific notation, malformed thousands separators, zero,
|
|
25
|
+
negatives, more than 6 decimal places and anything above the u64 limit of an SPL token amount.
|
|
26
|
+
"""
|
|
27
|
+
raw: object = value # callers may pass anything at runtime; validate it all
|
|
28
|
+
if isinstance(raw, (bool, float)):
|
|
29
|
+
raise AmountError('Floats are not accepted for money; pass a string or Decimal.')
|
|
30
|
+
if isinstance(raw, int):
|
|
31
|
+
raise AmountError('Pass USDC as a decimal string; integers are ambiguous here.')
|
|
32
|
+
if isinstance(raw, Decimal):
|
|
33
|
+
amount = raw
|
|
34
|
+
elif isinstance(raw, str):
|
|
35
|
+
text = raw.strip()
|
|
36
|
+
if not (_PLAIN.fullmatch(text) or _GROUPED.fullmatch(text)):
|
|
37
|
+
raise AmountError('Enter a valid amount, for example 150.25.')
|
|
38
|
+
amount = Decimal(text.replace(',', ''))
|
|
39
|
+
else:
|
|
40
|
+
raise AmountError('Pass USDC as a decimal string or Decimal.')
|
|
41
|
+
if not amount.is_finite() or amount <= 0:
|
|
42
|
+
raise AmountError('Amount must be greater than zero.')
|
|
43
|
+
exponent = amount.as_tuple().exponent
|
|
44
|
+
if isinstance(exponent, int) and -exponent > USDC_DECIMALS:
|
|
45
|
+
raise AmountError('USDC supports at most 6 decimal places.')
|
|
46
|
+
atomic = int(amount.scaleb(USDC_DECIMALS))
|
|
47
|
+
if atomic > U64_MAX:
|
|
48
|
+
raise AmountError('Amount is too large.')
|
|
49
|
+
return atomic
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def from_atomic(atomic: int) -> Decimal:
|
|
53
|
+
"""Atomic units to an exact Decimal with 6 places: 150250000 -> Decimal('150.250000')."""
|
|
54
|
+
raw: object = atomic
|
|
55
|
+
if isinstance(raw, bool) or not isinstance(raw, int):
|
|
56
|
+
raise TypeError('atomic must be an int')
|
|
57
|
+
value: Decimal = Decimal(raw) / ATOMIC_PER_USDC
|
|
58
|
+
return value.quantize(Decimal('0.000001'))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def format_usdc(atomic: int, places: int = 2) -> str:
|
|
62
|
+
"""Human display, rounded half up to `places` with thousands separators. Display only, never for posting."""
|
|
63
|
+
if not 0 <= places <= USDC_DECIMALS:
|
|
64
|
+
raise ValueError('places must be between 0 and 6')
|
|
65
|
+
value = from_atomic(atomic).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
|
66
|
+
return f'{value:,.{places}f}'
|
chainkit/constants.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Program ids, clusters and the exact USDC mints.
|
|
2
|
+
|
|
3
|
+
Payments code should compare mints by exact address, never by name or symbol: anyone can create a token called
|
|
4
|
+
"USDC". The addresses below are Circle's official USDC mints.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' # nosec B105 (public program id) classic SPL Token
|
|
8
|
+
TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' # nosec B105 (public program id)
|
|
9
|
+
ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'
|
|
10
|
+
SYSTEM_PROGRAM = '11111111111111111111111111111111'
|
|
11
|
+
COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111'
|
|
12
|
+
MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'
|
|
13
|
+
|
|
14
|
+
USDC_DECIMALS = 6
|
|
15
|
+
ATOMIC_PER_USDC = 10 ** USDC_DECIMALS
|
|
16
|
+
MAX_TRANSACTION_BYTES = 1232 # Solana packet limit for a serialized transaction
|
|
17
|
+
TOKEN_ACCOUNT_SIZE = 165 # bytes in an SPL token account (rent is charged on this size)
|
|
18
|
+
U64_MAX = 2 ** 64 - 1
|
|
19
|
+
|
|
20
|
+
# Genesis hashes identify a cluster with certainty (a URL does not). Genesis hashes and mints are verified
|
|
21
|
+
# against public RPC by tests/test_live.py (2026-11-25: mint account owned by the token program, 6 decimals).
|
|
22
|
+
CLUSTERS: dict[str, dict[str, str]] = {
|
|
23
|
+
'mainnet-beta': {
|
|
24
|
+
'genesis_hash': '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d',
|
|
25
|
+
'usdc_mint': 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', # Circle USDC (checked by live tests)
|
|
26
|
+
},
|
|
27
|
+
'devnet': {
|
|
28
|
+
'genesis_hash': 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG',
|
|
29
|
+
'usdc_mint': '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', # Circle Devnet USDC
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
# The only programs a USDC transfer built by chainkit ever touches.
|
|
34
|
+
ALLOWED_PROGRAMS = frozenset({TOKEN_PROGRAM, ATA_PROGRAM, COMPUTE_BUDGET_PROGRAM, MEMO_PROGRAM, SYSTEM_PROGRAM})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def usdc_mint(cluster: str) -> str:
|
|
38
|
+
"""Circle's USDC mint for `cluster` ('mainnet-beta' or 'devnet')."""
|
|
39
|
+
try:
|
|
40
|
+
return CLUSTERS[cluster]['usdc_mint']
|
|
41
|
+
except KeyError:
|
|
42
|
+
raise ValueError(f'Unknown cluster {cluster!r}') from None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def genesis_hash(cluster: str) -> str:
|
|
46
|
+
"""Genesis hash of `cluster`; compare with `SolanaRpc.genesis_hash()` before signing anything."""
|
|
47
|
+
try:
|
|
48
|
+
return CLUSTERS[cluster]['genesis_hash']
|
|
49
|
+
except KeyError:
|
|
50
|
+
raise ValueError(f'Unknown cluster {cluster!r}') from None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cluster_for_genesis(genesis: str) -> str | None:
|
|
54
|
+
"""The cluster name for a genesis hash, or None if it is not a known cluster."""
|
|
55
|
+
for name, values in CLUSTERS.items():
|
|
56
|
+
if values['genesis_hash'] == genesis:
|
|
57
|
+
return name
|
|
58
|
+
return None
|
chainkit/instructions.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The small, fixed set of instructions a USDC transfer needs, encoded by hand and range-checked.
|
|
2
|
+
|
|
3
|
+
transferChecked (not transfer) is used so the token program itself verifies the mint and decimals.
|
|
4
|
+
"""
|
|
5
|
+
import struct
|
|
6
|
+
|
|
7
|
+
from solders.instruction import AccountMeta, Instruction
|
|
8
|
+
from solders.pubkey import Pubkey
|
|
9
|
+
|
|
10
|
+
from .constants import ATA_PROGRAM, COMPUTE_BUDGET_PROGRAM, MEMO_PROGRAM, SYSTEM_PROGRAM, TOKEN_PROGRAM, U64_MAX
|
|
11
|
+
|
|
12
|
+
TRANSFER_CHECKED = 12
|
|
13
|
+
ATA_CREATE_IDEMPOTENT = 1
|
|
14
|
+
CU_LIMIT = 2
|
|
15
|
+
CU_PRICE = 3
|
|
16
|
+
MAX_COMPUTE_UNITS = 1_400_000
|
|
17
|
+
MAX_MEMO_BYTES = 120
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _pk(value: str | Pubkey) -> Pubkey:
|
|
21
|
+
return value if isinstance(value, Pubkey) else Pubkey.from_string(str(value))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _check_int(name: str, value: int, low: int, high: int) -> None:
|
|
25
|
+
if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
|
|
26
|
+
raise ValueError(f'{name} must be an integer from {low} to {high}')
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def transfer_checked(source_token_account: str | Pubkey, mint: str | Pubkey,
|
|
30
|
+
destination_token_account: str | Pubkey, owner: str | Pubkey, amount: int,
|
|
31
|
+
decimals: int) -> Instruction:
|
|
32
|
+
"""SPL Token transferChecked: move `amount` atomic units; fails on-chain if mint or decimals do not match."""
|
|
33
|
+
_check_int('amount', amount, 1, U64_MAX)
|
|
34
|
+
_check_int('decimals', decimals, 0, 255)
|
|
35
|
+
data = bytes([TRANSFER_CHECKED]) + struct.pack('<Q', amount) + bytes([decimals])
|
|
36
|
+
return Instruction(_pk(TOKEN_PROGRAM), data, [
|
|
37
|
+
AccountMeta(_pk(source_token_account), is_signer=False, is_writable=True),
|
|
38
|
+
AccountMeta(_pk(mint), is_signer=False, is_writable=False),
|
|
39
|
+
AccountMeta(_pk(destination_token_account), is_signer=False, is_writable=True),
|
|
40
|
+
AccountMeta(_pk(owner), is_signer=True, is_writable=False),
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def create_ata_idempotent(payer: str | Pubkey, ata: str | Pubkey, owner: str | Pubkey,
|
|
45
|
+
mint: str | Pubkey) -> Instruction:
|
|
46
|
+
"""Create `owner`'s token account for `mint` if missing; a no-op if it already exists. `payer` funds the rent."""
|
|
47
|
+
return Instruction(_pk(ATA_PROGRAM), bytes([ATA_CREATE_IDEMPOTENT]), [
|
|
48
|
+
AccountMeta(_pk(payer), is_signer=True, is_writable=True),
|
|
49
|
+
AccountMeta(_pk(ata), is_signer=False, is_writable=True),
|
|
50
|
+
AccountMeta(_pk(owner), is_signer=False, is_writable=False),
|
|
51
|
+
AccountMeta(_pk(mint), is_signer=False, is_writable=False),
|
|
52
|
+
AccountMeta(_pk(SYSTEM_PROGRAM), is_signer=False, is_writable=False),
|
|
53
|
+
AccountMeta(_pk(TOKEN_PROGRAM), is_signer=False, is_writable=False),
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def set_compute_unit_limit(units: int) -> Instruction:
|
|
58
|
+
_check_int('units', units, 1, MAX_COMPUTE_UNITS)
|
|
59
|
+
return Instruction(_pk(COMPUTE_BUDGET_PROGRAM), bytes([CU_LIMIT]) + struct.pack('<I', units), [])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def set_compute_unit_price(micro_lamports: int) -> Instruction:
|
|
63
|
+
"""Priority fee in micro-lamports per compute unit."""
|
|
64
|
+
_check_int('micro_lamports', micro_lamports, 0, U64_MAX)
|
|
65
|
+
return Instruction(_pk(COMPUTE_BUDGET_PROGRAM), bytes([CU_PRICE]) + struct.pack('<Q', micro_lamports), [])
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def memo(text: str) -> Instruction:
|
|
69
|
+
"""A memo (UTF-8, 1 to 120 bytes). Kept short on purpose: memos are public and cost transaction space."""
|
|
70
|
+
payload = text.encode('utf-8')
|
|
71
|
+
if not 1 <= len(payload) <= MAX_MEMO_BYTES:
|
|
72
|
+
raise ValueError(f'memo must be 1 to {MAX_MEMO_BYTES} bytes')
|
|
73
|
+
return Instruction(_pk(MEMO_PROGRAM), payload, [])
|
chainkit/parse.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Read USDC movements out of `jsonParsed` transactions (as returned by getTransaction).
|
|
2
|
+
|
|
3
|
+
Balance deltas (pre/post token balances) are used instead of instruction parsing, so a payment is seen no matter
|
|
4
|
+
which program moved it: a wallet, an exchange withdrawal, an aggregator or a smart contract. Every balance row is
|
|
5
|
+
checked against the exact mint and the classic token program, so look-alike tokens are never counted.
|
|
6
|
+
"""
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .constants import TOKEN_PROGRAM
|
|
10
|
+
|
|
11
|
+
Json = dict[str, Any]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _key_of(entry: object) -> str:
|
|
15
|
+
return str(entry['pubkey']) if isinstance(entry, dict) else str(entry)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _index_of(tx: Json, account: str) -> int | None:
|
|
19
|
+
keys = tx['transaction']['message']['accountKeys']
|
|
20
|
+
for i, key in enumerate(keys):
|
|
21
|
+
if _key_of(key) == account:
|
|
22
|
+
return i
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _usdc_rows(rows: list[Json] | None, mint: str) -> dict[int, Json]:
|
|
27
|
+
return {row['accountIndex']: row for row in rows or []
|
|
28
|
+
if row.get('mint') == mint and row.get('programId', TOKEN_PROGRAM) == TOKEN_PROGRAM}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _amount(row: Json | None) -> int:
|
|
32
|
+
return int(row['uiTokenAmount']['amount']) if row else 0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _succeeded(tx: Json) -> bool:
|
|
36
|
+
meta = tx.get('meta') or {}
|
|
37
|
+
return bool(meta) and meta.get('err') is None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def usdc_delta(tx: Json, token_account: str, mint: str) -> int:
|
|
41
|
+
"""Net change, in atomic units, of `token_account` for `mint`. 0 for failed transactions, for accounts not in
|
|
42
|
+
the transaction, and for rows of another mint or token program. Negative when USDC left the account, including
|
|
43
|
+
when the account was closed."""
|
|
44
|
+
if not _succeeded(tx):
|
|
45
|
+
return 0
|
|
46
|
+
index = _index_of(tx, token_account)
|
|
47
|
+
if index is None:
|
|
48
|
+
return 0
|
|
49
|
+
meta = tx['meta']
|
|
50
|
+
pre = _usdc_rows(meta.get('preTokenBalances'), mint).get(index)
|
|
51
|
+
post = _usdc_rows(meta.get('postTokenBalances'), mint).get(index)
|
|
52
|
+
return _amount(post) - _amount(pre)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def owner_delta(tx: Json, owner: str, mint: str) -> int:
|
|
56
|
+
"""Net change across every `mint` token account owned by `owner` (not only its associated account)."""
|
|
57
|
+
if not _succeeded(tx):
|
|
58
|
+
return 0
|
|
59
|
+
meta = tx['meta']
|
|
60
|
+
pre = _usdc_rows(meta.get('preTokenBalances'), mint)
|
|
61
|
+
post = _usdc_rows(meta.get('postTokenBalances'), mint)
|
|
62
|
+
total = 0
|
|
63
|
+
for index in set(pre) | set(post):
|
|
64
|
+
row_owner = (post.get(index) or pre.get(index) or {}).get('owner')
|
|
65
|
+
if row_owner == owner:
|
|
66
|
+
total += _amount(post.get(index)) - _amount(pre.get(index))
|
|
67
|
+
return total
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def senders(tx: Json, mint: str) -> list[str]:
|
|
71
|
+
"""Owners whose `mint` balance decreased in a successful transaction (the apparent source wallets), sorted."""
|
|
72
|
+
if not _succeeded(tx):
|
|
73
|
+
return []
|
|
74
|
+
meta = tx['meta']
|
|
75
|
+
pre = _usdc_rows(meta.get('preTokenBalances'), mint)
|
|
76
|
+
post = _usdc_rows(meta.get('postTokenBalances'), mint)
|
|
77
|
+
result = {row['owner'] for index, row in pre.items()
|
|
78
|
+
if row.get('owner') and _amount(post.get(index)) < _amount(row)}
|
|
79
|
+
return sorted(result)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def fee_lamports(tx: Json) -> int:
|
|
83
|
+
"""Network fee paid by the fee payer, in lamports."""
|
|
84
|
+
return int((tx.get('meta') or {}).get('fee') or 0)
|
chainkit/py.typed
ADDED
|
File without changes
|
chainkit/pyth.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Pyth price feeds read directly from Solana (no API key, no Django).
|
|
2
|
+
|
|
3
|
+
Pyth's push oracle keeps a sponsored `PriceUpdateV2` account per feed, written by the Pyth Solana Receiver program.
|
|
4
|
+
We read the SOL/USD account with getAccountInfo and trust it only if:
|
|
5
|
+
* the account is owned by the Pyth Solana Receiver program,
|
|
6
|
+
* the update is fully verified (all Wormhole guardian signatures checked on-chain),
|
|
7
|
+
* the embedded feed id is SOL/USD,
|
|
8
|
+
* it is recent and its confidence interval is tight.
|
|
9
|
+
|
|
10
|
+
PriceUpdateV2 layout (Anchor/Borsh):
|
|
11
|
+
8 discriminator
|
|
12
|
+
32 write_authority
|
|
13
|
+
1 verification_level variant (0 = Partial, followed by u8 num_signatures; 1 = Full)
|
|
14
|
+
PriceFeedMessage: 32 feed_id, i64 price, u64 conf, i32 exponent, i64 publish_time, i64 prev_publish_time,
|
|
15
|
+
i64 ema_price, u64 ema_conf
|
|
16
|
+
8 posted_slot
|
|
17
|
+
"""
|
|
18
|
+
import base64
|
|
19
|
+
import struct
|
|
20
|
+
import time
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from decimal import Decimal
|
|
23
|
+
from typing import Any, Protocol
|
|
24
|
+
|
|
25
|
+
PYTH_RECEIVER_PROGRAM = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ'
|
|
26
|
+
SOL_USD_FEED_ID = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d'
|
|
27
|
+
# Sponsored SOL/USD price feed account (shard 0), the same address on mainnet and devnet.
|
|
28
|
+
SOL_USD_PRICE_ACCOUNT = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE'
|
|
29
|
+
_HEADER = 8 + 32
|
|
30
|
+
_PRICE = struct.Struct('<qQiq') # price, conf, exponent, publish_time
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SupportsCall(Protocol):
|
|
34
|
+
"""Anything with a JSON-RPC `call(method, params)`, such as `chainkit.rpc.SolanaRpc`."""
|
|
35
|
+
|
|
36
|
+
def call(self, method: str, params: list[Any] | None = None) -> Any: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PythError(ValueError):
|
|
40
|
+
"""The account is not a trustworthy, current Pyth price."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class PythPrice:
|
|
45
|
+
feed_id: str
|
|
46
|
+
price: Decimal
|
|
47
|
+
conf: Decimal
|
|
48
|
+
publish_time: int
|
|
49
|
+
fully_verified: bool
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_price_update(data: bytes) -> PythPrice:
|
|
53
|
+
if len(data) < _HEADER + 2 + 32 + _PRICE.size:
|
|
54
|
+
raise PythError('Account data is too short for a Pyth PriceUpdateV2.')
|
|
55
|
+
offset = _HEADER
|
|
56
|
+
level = data[offset]
|
|
57
|
+
if level == 0:
|
|
58
|
+
offset += 2 # Partial { num_signatures: u8 }
|
|
59
|
+
elif level == 1:
|
|
60
|
+
offset += 1 # Full
|
|
61
|
+
else:
|
|
62
|
+
raise PythError(f'Unknown verification level {level}.')
|
|
63
|
+
feed_id = data[offset:offset + 32].hex()
|
|
64
|
+
offset += 32
|
|
65
|
+
raw_price, raw_conf, exponent, publish_time = _PRICE.unpack_from(data, offset)
|
|
66
|
+
scale = Decimal(10) ** exponent
|
|
67
|
+
return PythPrice(feed_id=feed_id, price=Decimal(raw_price) * scale, conf=Decimal(raw_conf) * scale,
|
|
68
|
+
publish_time=publish_time, fully_verified=level == 1)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def read_price(rpc: SupportsCall, account: str = SOL_USD_PRICE_ACCOUNT, feed_id: str = SOL_USD_FEED_ID, *,
|
|
72
|
+
max_age_seconds: int = 300, max_conf_ratio: Decimal = Decimal('0.02'), now: float | None = None
|
|
73
|
+
) -> PythPrice:
|
|
74
|
+
"""Fetch and validate a Pyth price account through a `chainkit.rpc.SolanaRpc`."""
|
|
75
|
+
value = rpc.call('getAccountInfo', [account, {'encoding': 'base64', 'commitment': 'confirmed'}])['value']
|
|
76
|
+
if value is None:
|
|
77
|
+
raise PythError(f'Pyth price account {account} does not exist on this cluster.')
|
|
78
|
+
if value.get('owner') != PYTH_RECEIVER_PROGRAM:
|
|
79
|
+
raise PythError('Price account is not owned by the Pyth Solana Receiver program.')
|
|
80
|
+
price = parse_price_update(base64.b64decode(value['data'][0]))
|
|
81
|
+
if not price.fully_verified:
|
|
82
|
+
raise PythError('Pyth price update is only partially verified.')
|
|
83
|
+
if price.feed_id != feed_id:
|
|
84
|
+
raise PythError('Price account holds a different Pyth feed.')
|
|
85
|
+
if price.price <= 0:
|
|
86
|
+
raise PythError('Pyth price is not positive.')
|
|
87
|
+
age = (now if now is not None else time.time()) - price.publish_time
|
|
88
|
+
if age > max_age_seconds:
|
|
89
|
+
raise PythError(f'Pyth price is {int(age)} s old (limit {max_age_seconds} s).')
|
|
90
|
+
if price.conf / price.price > max_conf_ratio:
|
|
91
|
+
raise PythError('Pyth confidence interval is too wide to price fees.')
|
|
92
|
+
return price
|
chainkit/rpc.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Minimal Solana JSON-RPC client with ordered failover across several endpoints.
|
|
2
|
+
|
|
3
|
+
Endpoints are tried in order. Network errors, HTTP 429 and 5xx, and invalid JSON move on to the next endpoint
|
|
4
|
+
(`RpcError.transient` is True when every endpoint failed that way, so a retry later is safe). A JSON-RPC error
|
|
5
|
+
answer is final and raised immediately (`transient` False): another node would give the same answer.
|
|
6
|
+
|
|
7
|
+
`verify_client()` returns a client pinned to the last configured endpoint, so a critical fact (for example that a
|
|
8
|
+
deposit is finalized) can be confirmed by a second, independent provider.
|
|
9
|
+
"""
|
|
10
|
+
import itertools
|
|
11
|
+
from typing import Any, cast
|
|
12
|
+
|
|
13
|
+
import requests
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
|
|
17
|
+
_ids = itertools.count(1)
|
|
18
|
+
Json = dict[str, Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RpcError(RuntimeError):
|
|
22
|
+
def __init__(self, message: str, code: int | None = None, transient: bool = False):
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.code = code
|
|
25
|
+
self.transient = transient
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SolanaRpc:
|
|
29
|
+
def __init__(self, urls: list[str], timeout: float = 20.0, session: requests.Session | None = None):
|
|
30
|
+
if not urls:
|
|
31
|
+
raise ValueError('At least one RPC URL is required.')
|
|
32
|
+
self.urls = list(urls)
|
|
33
|
+
self.timeout = timeout
|
|
34
|
+
self.session = session or requests.Session()
|
|
35
|
+
self.session.headers.setdefault('User-Agent', f'chainkit/{__version__}')
|
|
36
|
+
|
|
37
|
+
def verify_client(self) -> 'SolanaRpc':
|
|
38
|
+
return SolanaRpc([self.urls[-1]], self.timeout, self.session)
|
|
39
|
+
|
|
40
|
+
def call(self, method: str, params: list[Any] | None = None) -> Any:
|
|
41
|
+
last_error: RpcError | None = None
|
|
42
|
+
for url in self.urls:
|
|
43
|
+
try:
|
|
44
|
+
response = self.session.post(url, json={'jsonrpc': '2.0', 'id': next(_ids), 'method': method,
|
|
45
|
+
'params': params or []}, timeout=self.timeout)
|
|
46
|
+
except requests.RequestException as exc:
|
|
47
|
+
last_error = RpcError(f'{method}: {exc.__class__.__name__}', transient=True)
|
|
48
|
+
continue
|
|
49
|
+
if response.status_code == 429 or response.status_code >= 500:
|
|
50
|
+
last_error = RpcError(f'{method}: HTTP {response.status_code}', transient=True)
|
|
51
|
+
continue
|
|
52
|
+
try:
|
|
53
|
+
body = response.json()
|
|
54
|
+
except ValueError:
|
|
55
|
+
last_error = RpcError(f'{method}: invalid JSON', transient=True)
|
|
56
|
+
continue
|
|
57
|
+
if not isinstance(body, dict):
|
|
58
|
+
last_error = RpcError(f'{method}: unexpected response', transient=True)
|
|
59
|
+
continue
|
|
60
|
+
if 'error' in body:
|
|
61
|
+
error = body['error'] if isinstance(body['error'], dict) else {'message': str(body['error'])}
|
|
62
|
+
code = error.get('code')
|
|
63
|
+
raise RpcError(f"{method}: {error.get('message')}", code=code if isinstance(code, int) else None)
|
|
64
|
+
return body.get('result')
|
|
65
|
+
raise last_error or RpcError(f'{method}: no RPC endpoint answered', transient=True)
|
|
66
|
+
|
|
67
|
+
# Typed helpers -------------------------------------------------------------------------
|
|
68
|
+
def genesis_hash(self) -> str:
|
|
69
|
+
return str(self.call('getGenesisHash'))
|
|
70
|
+
|
|
71
|
+
def latest_blockhash(self, commitment: str = 'confirmed') -> tuple[str, int]:
|
|
72
|
+
"""(blockhash, lastValidBlockHeight). A transaction using this blockhash can never land after that height."""
|
|
73
|
+
value = self.call('getLatestBlockhash', [{'commitment': commitment}])['value']
|
|
74
|
+
return value['blockhash'], int(value['lastValidBlockHeight'])
|
|
75
|
+
|
|
76
|
+
def block_height(self, commitment: str = 'confirmed') -> int:
|
|
77
|
+
return int(self.call('getBlockHeight', [{'commitment': commitment}]))
|
|
78
|
+
|
|
79
|
+
def send_transaction(self, tx_base64: str) -> str:
|
|
80
|
+
"""Submit with preflight simulation and no node-side retries (the caller owns retry decisions)."""
|
|
81
|
+
options = {'encoding': 'base64', 'skipPreflight': False, 'preflightCommitment': 'confirmed', 'maxRetries': 0}
|
|
82
|
+
return str(self.call('sendTransaction', [tx_base64, options]))
|
|
83
|
+
|
|
84
|
+
def signature_statuses(self, signatures: list[str]) -> list[Json | None]:
|
|
85
|
+
value = self.call('getSignatureStatuses', [signatures, {'searchTransactionHistory': True}])['value']
|
|
86
|
+
return cast(list[Json | None], value)
|
|
87
|
+
|
|
88
|
+
def transaction(self, signature: str, commitment: str = 'finalized') -> Json | None:
|
|
89
|
+
options = {'encoding': 'jsonParsed', 'commitment': commitment, 'maxSupportedTransactionVersion': 0}
|
|
90
|
+
return cast(Json | None, self.call('getTransaction', [signature, options]))
|
|
91
|
+
|
|
92
|
+
def signatures_for_address(self, address: str, until: str | None = None, limit: int = 100,
|
|
93
|
+
commitment: str = 'finalized', before: str | None = None) -> list[Json]:
|
|
94
|
+
options: dict[str, Any] = {'limit': limit, 'commitment': commitment}
|
|
95
|
+
if until:
|
|
96
|
+
options['until'] = until
|
|
97
|
+
if before:
|
|
98
|
+
options['before'] = before
|
|
99
|
+
return cast(list[Json], self.call('getSignaturesForAddress', [address, options]))
|
|
100
|
+
|
|
101
|
+
def all_signatures_since(self, address: str, until: str | None, commitment: str = 'finalized',
|
|
102
|
+
max_pages: int = 50) -> list[Json]:
|
|
103
|
+
"""Every signature newer than `until` (newest first), following pages so none are skipped.
|
|
104
|
+
Raises RpcError if more than `max_pages` pages exist, rather than silently returning a partial list."""
|
|
105
|
+
result: list[Json] = []
|
|
106
|
+
before = None
|
|
107
|
+
for _ in range(max_pages):
|
|
108
|
+
page = self.signatures_for_address(address, until=until, limit=1000, commitment=commitment,
|
|
109
|
+
before=before)
|
|
110
|
+
result.extend(page)
|
|
111
|
+
if len(page) < 1000:
|
|
112
|
+
return result
|
|
113
|
+
before = page[-1]['signature']
|
|
114
|
+
raise RpcError(f'getSignaturesForAddress: more than {max_pages} pages for {address}', transient=True)
|
|
115
|
+
|
|
116
|
+
def account_info(self, address: str, commitment: str = 'confirmed', encoding: str = 'jsonParsed') -> Json | None:
|
|
117
|
+
value = self.call('getAccountInfo', [address, {'encoding': encoding, 'commitment': commitment}])['value']
|
|
118
|
+
return cast(Json | None, value)
|
|
119
|
+
|
|
120
|
+
def token_balance(self, token_account: str, commitment: str = 'finalized') -> int:
|
|
121
|
+
"""Balance in atomic units; 0 if the token account does not exist yet."""
|
|
122
|
+
try:
|
|
123
|
+
value = self.call('getTokenAccountBalance', [token_account, {'commitment': commitment}])['value']
|
|
124
|
+
except RpcError as exc:
|
|
125
|
+
if exc.code == -32602: # invalid param: the account does not exist (yet)
|
|
126
|
+
return 0
|
|
127
|
+
raise
|
|
128
|
+
return int(value['amount'])
|
|
129
|
+
|
|
130
|
+
def sol_balance(self, address: str, commitment: str = 'finalized') -> int:
|
|
131
|
+
return int(self.call('getBalance', [address, {'commitment': commitment}])['value'])
|
|
132
|
+
|
|
133
|
+
def minimum_balance_for_rent_exemption(self, size: int) -> int:
|
|
134
|
+
"""Lamports an account of `size` bytes must hold (165 bytes for a token account)."""
|
|
135
|
+
return int(self.call('getMinimumBalanceForRentExemption', [size]))
|
|
136
|
+
|
|
137
|
+
def request_airdrop(self, address: str, lamports: int) -> str:
|
|
138
|
+
"""Devnet/testnet only."""
|
|
139
|
+
return str(self.call('requestAirdrop', [address, lamports]))
|
chainkit/transactions.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Build and inspect USDC transfer transactions.
|
|
2
|
+
|
|
3
|
+
`build_transfer_message` creates a transfer from a plain plan using only allowlisted instructions.
|
|
4
|
+
`describe_message` decodes any legacy message back into plain facts, and lists everything it does not recognise in
|
|
5
|
+
`unknown`, so a signer can refuse to sign anything it cannot fully explain:
|
|
6
|
+
|
|
7
|
+
facts = describe_message(message)
|
|
8
|
+
if not facts.is_clean or facts.transfers != [expected]:
|
|
9
|
+
raise RefuseToSign(...)
|
|
10
|
+
"""
|
|
11
|
+
import struct
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from solders.hash import Hash
|
|
16
|
+
from solders.message import Message
|
|
17
|
+
from solders.pubkey import Pubkey
|
|
18
|
+
|
|
19
|
+
from . import instructions as ix
|
|
20
|
+
from .addresses import derive_ata, parse_pubkey
|
|
21
|
+
from .constants import (
|
|
22
|
+
ALLOWED_PROGRAMS,
|
|
23
|
+
ATA_PROGRAM,
|
|
24
|
+
COMPUTE_BUDGET_PROGRAM,
|
|
25
|
+
MAX_TRANSACTION_BYTES,
|
|
26
|
+
MEMO_PROGRAM,
|
|
27
|
+
TOKEN_PROGRAM,
|
|
28
|
+
U64_MAX,
|
|
29
|
+
USDC_DECIMALS,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
DEFAULT_CU_LIMIT = 60_000
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class TransferPlan:
|
|
37
|
+
"""What to send. Give exactly one destination: an owner wallet (its token account is derived and created if
|
|
38
|
+
needed, paid by `fee_payer`) or an existing token account."""
|
|
39
|
+
fee_payer: str
|
|
40
|
+
source_owner: str
|
|
41
|
+
mint: str
|
|
42
|
+
amount: int # atomic units
|
|
43
|
+
destination_owner: str | None = None
|
|
44
|
+
destination_token_account: str | None = None
|
|
45
|
+
memo: str = ''
|
|
46
|
+
cu_price_micro_lamports: int = 0
|
|
47
|
+
cu_limit: int = DEFAULT_CU_LIMIT
|
|
48
|
+
decimals: int = USDC_DECIMALS
|
|
49
|
+
|
|
50
|
+
def destination_account(self) -> str:
|
|
51
|
+
if self.destination_token_account:
|
|
52
|
+
return str(parse_pubkey(self.destination_token_account))
|
|
53
|
+
if not self.destination_owner:
|
|
54
|
+
raise ValueError('Give exactly one of destination_owner or destination_token_account.')
|
|
55
|
+
return str(derive_ata(self.destination_owner, self.mint))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_transfer_message(plan: TransferPlan, recent_blockhash: str) -> Message:
|
|
59
|
+
"""A legacy message: compute limit, optional priority fee, optional idempotent account creation,
|
|
60
|
+
transferChecked, optional memo. Raises ValueError for an invalid plan or an oversized transaction."""
|
|
61
|
+
if bool(plan.destination_owner) == bool(plan.destination_token_account):
|
|
62
|
+
raise ValueError('Give exactly one of destination_owner or destination_token_account.')
|
|
63
|
+
if isinstance(plan.amount, bool) or not isinstance(plan.amount, int) or not 1 <= plan.amount <= U64_MAX:
|
|
64
|
+
raise ValueError('amount must be a positive integer number of atomic units')
|
|
65
|
+
for name in ('fee_payer', 'source_owner', 'mint'):
|
|
66
|
+
parse_pubkey(getattr(plan, name))
|
|
67
|
+
source_ata = derive_ata(plan.source_owner, plan.mint)
|
|
68
|
+
destination = plan.destination_account()
|
|
69
|
+
if destination == str(source_ata):
|
|
70
|
+
raise ValueError('Source and destination are the same token account.')
|
|
71
|
+
instructions = [ix.set_compute_unit_limit(plan.cu_limit)]
|
|
72
|
+
if plan.cu_price_micro_lamports:
|
|
73
|
+
instructions.append(ix.set_compute_unit_price(plan.cu_price_micro_lamports))
|
|
74
|
+
if plan.destination_owner:
|
|
75
|
+
instructions.append(ix.create_ata_idempotent(plan.fee_payer, destination, plan.destination_owner, plan.mint))
|
|
76
|
+
instructions.append(ix.transfer_checked(source_ata, plan.mint, destination, plan.source_owner, plan.amount,
|
|
77
|
+
plan.decimals))
|
|
78
|
+
if plan.memo:
|
|
79
|
+
instructions.append(ix.memo(plan.memo))
|
|
80
|
+
message = Message.new_with_blockhash(instructions, Pubkey.from_string(plan.fee_payer),
|
|
81
|
+
Hash.from_string(recent_blockhash))
|
|
82
|
+
if transaction_size(message) > MAX_TRANSACTION_BYTES:
|
|
83
|
+
raise ValueError('Transaction would exceed the Solana size limit.')
|
|
84
|
+
return message
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def transaction_size(message: Message) -> int:
|
|
88
|
+
"""Serialized size of the signed transaction: signature count, signatures, then the message."""
|
|
89
|
+
signatures = message.header.num_required_signatures
|
|
90
|
+
return len(bytes(message)) + 1 + 64 * signatures
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class MessageFacts:
|
|
95
|
+
fee_payer: str
|
|
96
|
+
signers: list[str]
|
|
97
|
+
programs: list[str]
|
|
98
|
+
transfers: list[dict[str, Any]] = field(default_factory=list) # source, mint, destination, owner, amount, decimals
|
|
99
|
+
ata_creations: list[dict[str, str]] = field(default_factory=list) # payer, ata, owner, mint
|
|
100
|
+
memos: list[str] = field(default_factory=list)
|
|
101
|
+
compute_unit_limit: int | None = None
|
|
102
|
+
compute_unit_price: int | None = None
|
|
103
|
+
unknown: list[str] = field(default_factory=list) # anything not recognised; must be empty to sign
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def is_clean(self) -> bool:
|
|
107
|
+
return not self.unknown
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def describe_message(message: Message) -> MessageFacts:
|
|
111
|
+
"""Decode a legacy message into facts. Never raises on unexpected content: it reports it in `unknown`."""
|
|
112
|
+
keys = [str(k) for k in message.account_keys]
|
|
113
|
+
signer_count = message.header.num_required_signatures
|
|
114
|
+
facts = MessageFacts(fee_payer=keys[0], signers=keys[:signer_count], programs=[])
|
|
115
|
+
for compiled in message.instructions:
|
|
116
|
+
program = keys[compiled.program_id_index]
|
|
117
|
+
accounts = [keys[i] for i in compiled.accounts]
|
|
118
|
+
data = bytes(compiled.data)
|
|
119
|
+
facts.programs.append(program)
|
|
120
|
+
if program not in ALLOWED_PROGRAMS:
|
|
121
|
+
facts.unknown.append(f'program {program}')
|
|
122
|
+
elif program == TOKEN_PROGRAM:
|
|
123
|
+
if data[:1] == bytes([ix.TRANSFER_CHECKED]) and len(data) == 10 and len(accounts) == 4:
|
|
124
|
+
amount = struct.unpack('<Q', data[1:9])[0]
|
|
125
|
+
facts.transfers.append({'source': accounts[0], 'mint': accounts[1], 'destination': accounts[2],
|
|
126
|
+
'owner': accounts[3], 'amount': amount, 'decimals': data[9]})
|
|
127
|
+
else:
|
|
128
|
+
facts.unknown.append('token instruction other than transferChecked')
|
|
129
|
+
elif program == ATA_PROGRAM:
|
|
130
|
+
if data == bytes([ix.ATA_CREATE_IDEMPOTENT]) and len(accounts) == 6:
|
|
131
|
+
facts.ata_creations.append({'payer': accounts[0], 'ata': accounts[1], 'owner': accounts[2],
|
|
132
|
+
'mint': accounts[3]})
|
|
133
|
+
else:
|
|
134
|
+
facts.unknown.append('associated token account instruction other than createIdempotent')
|
|
135
|
+
elif program == COMPUTE_BUDGET_PROGRAM:
|
|
136
|
+
if data[:1] == bytes([ix.CU_LIMIT]) and len(data) == 5:
|
|
137
|
+
facts.compute_unit_limit = struct.unpack('<I', data[1:5])[0]
|
|
138
|
+
elif data[:1] == bytes([ix.CU_PRICE]) and len(data) == 9:
|
|
139
|
+
facts.compute_unit_price = struct.unpack('<Q', data[1:9])[0]
|
|
140
|
+
else:
|
|
141
|
+
facts.unknown.append('compute budget instruction other than limit or price')
|
|
142
|
+
elif program == MEMO_PROGRAM:
|
|
143
|
+
facts.memos.append(data.decode('utf-8', errors='replace'))
|
|
144
|
+
else: # the system program is allowed only as an account of createIdempotent, never invoked directly
|
|
145
|
+
facts.unknown.append(f'direct call to {program}')
|
|
146
|
+
return facts
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: solana-chainkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Production-grade building blocks for USDC payments on Solana: exact amounts, safe transfers, deposit detection, RPC failover and verified Pyth prices.
|
|
5
|
+
Project-URL: Homepage, https://github.com/pmzomo/chainkit
|
|
6
|
+
Project-URL: Source, https://github.com/pmzomo/chainkit
|
|
7
|
+
Project-URL: Issues, https://github.com/pmzomo/chainkit/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/pmzomo/chainkit/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Peter Nzomo <pmzomo@gmail.com>
|
|
10
|
+
Maintainer-email: Peter Nzomo <pmzomo@gmail.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
License-File: NOTICE
|
|
14
|
+
Keywords: fintech,payments,pyth,solana,spl-token,stablecoin,usdc
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.10
|
|
28
|
+
Requires-Dist: requests<3,>=2.31
|
|
29
|
+
Requires-Dist: solders<1,>=0.21
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: build; extra == 'dev'
|
|
32
|
+
Requires-Dist: hypothesis>=6.100; extra == 'dev'
|
|
33
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
34
|
+
Requires-Dist: pytest-cov>=5; extra == 'dev'
|
|
35
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
36
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
37
|
+
Requires-Dist: twine; extra == 'dev'
|
|
38
|
+
Requires-Dist: types-requests; extra == 'dev'
|
|
39
|
+
Description-Content-Type: text/markdown
|
|
40
|
+
|
|
41
|
+
# chainkit
|
|
42
|
+
|
|
43
|
+
[](https://github.com/pmzomo/chainkit/actions/workflows/ci.yml)
|
|
44
|
+
[](https://pypi.org/project/solana-chainkit/)
|
|
45
|
+
[](https://pypi.org/project/solana-chainkit/)
|
|
46
|
+
[](https://github.com/pmzomo/chainkit/blob/main/LICENSE)
|
|
47
|
+
|
|
48
|
+
**Production-grade building blocks for USDC payments on Solana, in Python.**
|
|
49
|
+
|
|
50
|
+
chainkit packages the parts of a Solana payments backend that are easy to get subtly wrong: exact money amounts,
|
|
51
|
+
safe USDC transfers, recognising real USDC (and only real USDC), detecting deposits from any wallet or exchange,
|
|
52
|
+
surviving RPC outages, and reading a verified price straight from the Pyth oracle on Solana. It is small, typed,
|
|
53
|
+
fully tested, and has two runtime dependencies (`solders`, `requests`).
|
|
54
|
+
|
|
55
|
+
It was extracted from [GT Pay](https://pay.gtbai.co), a USDC wallet and payroll platform for the global workforce
|
|
56
|
+
built by Global TalentBridge AI, where it runs the payment path and the separate signing service.
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install solana-chainkit
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import chainkit
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Why it exists
|
|
67
|
+
|
|
68
|
+
Most Solana payment tooling is TypeScript. Python runs a large share of fintech back offices, payroll systems and data
|
|
69
|
+
teams, and they need the same guarantees:
|
|
70
|
+
|
|
71
|
+
| Mistake teams make | What chainkit does |
|
|
72
|
+
|---|---|
|
|
73
|
+
| Storing money as floats (`0.1 + 0.2`) | Amounts are integer atomic units; floats and ambiguous integers are refused |
|
|
74
|
+
| Trusting a token called "USDC" | Compares Circle's exact mint addresses and the classic token program on every balance row |
|
|
75
|
+
| Typos in hard-coded addresses | Weekly live tests check the mints, genesis hashes and Pyth account against real Solana |
|
|
76
|
+
| Signing whatever transaction a library built | `describe_message` decodes a message into plain facts and lists anything unrecognised, so you can refuse to sign it |
|
|
77
|
+
| Missing deposits sent by exchanges or contracts | Detects payments from balance deltas, which works no matter which program moved the funds |
|
|
78
|
+
| One RPC provider down means payments stop | Ordered failover across providers, with errors marked transient or final |
|
|
79
|
+
| Trusting a price API you do not control | Reads Pyth's price account on Solana and checks owner, verification level, feed id, age and confidence |
|
|
80
|
+
| Re-signing a dropped transaction too early (double pay) | Exposes `lastValidBlockHeight` so you only re-sign after the old one can no longer land |
|
|
81
|
+
|
|
82
|
+
## Quick start
|
|
83
|
+
|
|
84
|
+
### Exact amounts
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from chainkit.amounts import to_atomic, format_usdc
|
|
88
|
+
|
|
89
|
+
to_atomic('150.25') # 150250000
|
|
90
|
+
to_atomic('1,250.50') # 1250500000
|
|
91
|
+
format_usdc(150250000) # '150.25'
|
|
92
|
+
to_atomic(0.1) # AmountError: floats are not accepted for money
|
|
93
|
+
to_atomic('1e3') # AmountError: scientific notation is not an amount
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Detect a USDC deposit (from any wallet or exchange)
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from chainkit.constants import usdc_mint
|
|
100
|
+
from chainkit.addresses import derive_ata
|
|
101
|
+
from chainkit.parse import usdc_delta, senders
|
|
102
|
+
from chainkit.rpc import SolanaRpc
|
|
103
|
+
|
|
104
|
+
rpc = SolanaRpc(['https://api.devnet.solana.com']) # add a second provider for failover
|
|
105
|
+
mint = usdc_mint('devnet')
|
|
106
|
+
token_account = str(derive_ata('YourWalletAddress...', mint))
|
|
107
|
+
|
|
108
|
+
for item in rpc.signatures_for_address(token_account, limit=20):
|
|
109
|
+
tx = rpc.transaction(item['signature']) # finalized by default
|
|
110
|
+
received = usdc_delta(tx, token_account, mint) # atomic units; 0 for failed tx or look-alike tokens
|
|
111
|
+
if received > 0:
|
|
112
|
+
print(item['signature'], received, 'from', senders(tx, mint))
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Build a transfer, then check it before signing
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
import base64
|
|
119
|
+
|
|
120
|
+
from solders.transaction import Transaction
|
|
121
|
+
from chainkit.transactions import TransferPlan, build_transfer_message, describe_message
|
|
122
|
+
|
|
123
|
+
plan = TransferPlan(fee_payer=str(payer.pubkey()), source_owner=str(owner.pubkey()), mint=mint,
|
|
124
|
+
amount=5_000_000, destination_owner='RecipientWallet...', memo='invoice 1042')
|
|
125
|
+
blockhash, last_valid_height = rpc.latest_blockhash()
|
|
126
|
+
message = build_transfer_message(plan, blockhash)
|
|
127
|
+
|
|
128
|
+
facts = describe_message(message) # what will this transaction actually do?
|
|
129
|
+
assert facts.is_clean # nothing unrecognised
|
|
130
|
+
assert facts.transfers[0]['amount'] == 5_000_000
|
|
131
|
+
|
|
132
|
+
tx = Transaction([payer, owner], message, message.recent_blockhash)
|
|
133
|
+
signature = rpc.send_transaction(base64.b64encode(bytes(tx)).decode())
|
|
134
|
+
# Only build and sign a replacement once block height > last_valid_height and the signature was never seen.
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
If the recipient has no USDC account yet, the plan adds an idempotent account creation paid by `fee_payer`. The
|
|
138
|
+
one-time rent for that account is `rpc.minimum_balance_for_rent_exemption(165)` lamports. Query it: rent is not a
|
|
139
|
+
constant (it fell from 2,039,280 to 1,488,440 lamports by November 2026).
|
|
140
|
+
|
|
141
|
+
### Verified SOL/USD price from Pyth, read on-chain
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from chainkit import pyth
|
|
145
|
+
from chainkit.rpc import SolanaRpc
|
|
146
|
+
|
|
147
|
+
price = pyth.read_price(SolanaRpc(['https://api.mainnet-beta.solana.com']))
|
|
148
|
+
print(price.price, '+/-', price.conf) # Decimal('72.70629150') +/- Decimal('0.02...')
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
`read_price` refuses the account unless it is owned by the Pyth Solana Receiver program, fully verified by Wormhole
|
|
152
|
+
guardians, the SOL/USD feed, at most 5 minutes old and within a 2% confidence band. Any Pyth feed works by passing its
|
|
153
|
+
price account and feed id.
|
|
154
|
+
|
|
155
|
+
More in [`examples/`](https://github.com/pmzomo/chainkit/tree/main/examples):
|
|
156
|
+
|
|
157
|
+
| Example | Network |
|
|
158
|
+
|---|---|
|
|
159
|
+
| `inspect_transfer.py`: build a transfer, inspect it, refuse unless it matches the intent, sign | Offline |
|
|
160
|
+
| `detect_deposits.py`: list recent USDC deposits to a wallet from any sender | Devnet or mainnet |
|
|
161
|
+
| `account_setup_cost.py`: live rent plus Pyth price = USD cost of creating a recipient's USDC account | Mainnet |
|
|
162
|
+
|
|
163
|
+
## Modules
|
|
164
|
+
|
|
165
|
+
| Module | Purpose |
|
|
166
|
+
|---|---|
|
|
167
|
+
| `chainkit.constants` | Program ids, cluster genesis hashes, Circle's USDC mints, `cluster_for_genesis` |
|
|
168
|
+
| `chainkit.amounts` | `to_atomic`, `from_atomic`, `format_usdc` |
|
|
169
|
+
| `chainkit.addresses` | Strict `parse_pubkey`, `derive_ata`, `is_on_curve` |
|
|
170
|
+
| `chainkit.instructions` | Range-checked `transfer_checked`, `create_ata_idempotent`, compute budget, `memo` |
|
|
171
|
+
| `chainkit.transactions` | `TransferPlan`, `build_transfer_message`, `describe_message` (`MessageFacts`), `transaction_size` |
|
|
172
|
+
| `chainkit.parse` | `usdc_delta`, `owner_delta`, `senders`, `fee_lamports` |
|
|
173
|
+
| `chainkit.rpc` | `SolanaRpc` with failover; `RpcError(code, transient)`; typed helpers incl. paging and rent |
|
|
174
|
+
| `chainkit.pyth` | `read_price`, `parse_price_update`, SOL/USD constants |
|
|
175
|
+
|
|
176
|
+
## Safety model
|
|
177
|
+
|
|
178
|
+
- **Exact assets only.** USDC is identified by mint address and token program, never by name. Token-2022 rows with a
|
|
179
|
+
USDC-looking mint are ignored.
|
|
180
|
+
- **Allowlisted instructions.** Built transfers use only compute budget, idempotent token-account creation,
|
|
181
|
+
`transferChecked` and memo. `describe_message` reports anything else in `unknown`.
|
|
182
|
+
- **Fail loudly.** Invalid amounts, addresses, out-of-range integers and oversized transactions raise immediately;
|
|
183
|
+
paging that would be incomplete raises instead of returning a partial list.
|
|
184
|
+
- **Know your cluster.** Compare `rpc.genesis_hash()` with `constants.genesis_hash(cluster)` before signing, so a
|
|
185
|
+
mainnet key never signs against the wrong network (and the reverse).
|
|
186
|
+
- **No keys inside.** chainkit never stores, generates or transmits private keys. You sign with your own signer
|
|
187
|
+
(solders `Keypair`, a KMS, an HSM).
|
|
188
|
+
|
|
189
|
+
## Scope
|
|
190
|
+
|
|
191
|
+
chainkit builds and reads **legacy** messages and the **classic SPL Token** program, which is what USDC uses. It is a
|
|
192
|
+
library, not a wallet or a custody service. Deposit detection reads `jsonParsed` transactions; pair it with your own
|
|
193
|
+
storage of the last processed signature.
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
199
|
+
pip install -e ".[dev]"
|
|
200
|
+
pytest --cov # unit tests, no network
|
|
201
|
+
CHAINKIT_LIVE=1 pytest -m live # optional: checks against public Solana RPC and Pyth
|
|
202
|
+
ruff check . && mypy
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## Documentation
|
|
206
|
+
|
|
207
|
+
The full system specification, with diagrams of every flow, is in
|
|
208
|
+
[docs/SPECIFICATION.md](https://github.com/pmzomo/chainkit/blob/main/docs/SPECIFICATION.md).
|
|
209
|
+
|
|
210
|
+
## Status
|
|
211
|
+
|
|
212
|
+
Version 0.1.0, beta. The API may still change before 1.0; changes are listed in [CHANGELOG.md](https://github.com/pmzomo/chainkit/blob/main/CHANGELOG.md).
|
|
213
|
+
Security issues: see [SECURITY.md](https://github.com/pmzomo/chainkit/blob/main/SECURITY.md).
|
|
214
|
+
|
|
215
|
+
## License
|
|
216
|
+
|
|
217
|
+
Apache License 2.0. Copyright 2026 Global TalentBridge AI LLC. See [LICENSE](https://github.com/pmzomo/chainkit/blob/main/LICENSE) and [NOTICE](https://github.com/pmzomo/chainkit/blob/main/NOTICE).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
chainkit/__init__.py,sha256=L4fBKv4dUfCuIyyaWTKy-zcr3QWjoLH0woUXYXR3kKk,939
|
|
2
|
+
chainkit/addresses.py,sha256=4enRjRkvIDvgaVjB508oEnec9BU9zI6ZMFFYrCsuNn4,1723
|
|
3
|
+
chainkit/amounts.py,sha256=v_OyqafcukwmqM0IAr5AoWCj1Q-Mv7OIWRW6MUEIqfQ,2984
|
|
4
|
+
chainkit/constants.py,sha256=TloJ8RkV33ZJP9jUkqYe_R9XgHO64CRSfBU7r4Gq6QA,2607
|
|
5
|
+
chainkit/instructions.py,sha256=5pap7Gfu67I4mInH435UaNwenZD4UsLv9PV1Qr0WSZE,3430
|
|
6
|
+
chainkit/parse.py,sha256=e7dgA0gPoFlBc4pemyGV0BMlXLKU5f5jSKngdSc0h54,3195
|
|
7
|
+
chainkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
chainkit/pyth.py,sha256=nqywr5v8r3LvUYxoQzIlQLFw8SvGZDWwfvCVbFAzrg4,4008
|
|
9
|
+
chainkit/rpc.py,sha256=jouRPTprlEQtpah7JXMTcp3ux18Ntbf5IH4i3gTW298,7245
|
|
10
|
+
chainkit/transactions.py,sha256=A_eNZ3BgxoIZdMkkAVFsfhwaaL5vmSC02znDcgO6yco,6988
|
|
11
|
+
solana_chainkit-0.1.0.dist-info/METADATA,sha256=KEwyBrF2H9YHF3iuiyxeloCf_eQ_HDDP77lKJQWwso8,10745
|
|
12
|
+
solana_chainkit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
solana_chainkit-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
14
|
+
solana_chainkit-0.1.0.dist-info/licenses/NOTICE,sha256=QUK6XYz1SfX4izHfEJoUbx6nnOqWgzD5GWOqMlUqpOk,159
|
|
15
|
+
solana_chainkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|