Skip to content

Commit 9bcea9b

Browse files
committed
Cache CONSTR_ID
1 parent 955cd7a commit 9bcea9b

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

pycardano/plutus.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66
import json
77
from dataclasses import dataclass, field, fields
88
from enum import Enum
9+
from hashlib import sha256
910
from typing import Any, Optional, Type, Union
1011

1112
import cbor2
1213
from cbor2 import CBORTag
1314
from nacl.encoding import RawEncoder
1415
from nacl.hash import blake2b
15-
from hashlib import sha256
1616

1717
from pycardano.exception import DeserializeException
1818
from pycardano.hash import DATUM_HASH_SIZE, SCRIPT_HASH_SIZE, DatumHash, ScriptHash
@@ -476,11 +476,16 @@ def CONSTR_ID(cls):
476476
The default implementation is an almost unique, deterministic constructor ID in the range 1 - 2^32 based
477477
on class attributes, types and class name.
478478
"""
479-
det_string = (
480-
cls.__name__ + "*" + "*".join([f"{f.name}~{f.type}" for f in fields(cls)])
481-
)
482-
det_hash = sha256(det_string.encode("utf8")).hexdigest()
483-
return int(det_hash, 16) % 2**32
479+
if not hasattr(cls, "_CONSTR_ID"):
480+
det_string = (
481+
cls.__name__
482+
+ "*"
483+
+ "*".join([f"{f.name}~{f.type}" for f in fields(cls)])
484+
)
485+
det_hash = sha256(det_string.encode("utf8")).hexdigest()
486+
setattr(cls, "_CONSTR_ID", int(det_hash, 16) % 2**32)
487+
488+
return cls._CONSTR_ID
484489

485490
def __post_init__(self):
486491
valid_types = (PlutusData, dict, IndefiniteList, int, bytes)

0 commit comments

Comments
 (0)