diff --git a/openapi.yaml b/openapi.yaml index 7a25e3e67..56368ef11 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -10413,6 +10413,92 @@ components: - action - operation - criteria + RateLimitingCriterion: + x-audience: development + type: object + title: RateLimitingCriterion + description: A criterion that limits the number or value of operations within a time window. When the limit is exceeded, subsequent operations matching this criterion will be rejected until the window resets. + properties: + type: + type: string + description: The type of criterion to use. This should be `rateLimiting`. + example: rateLimiting + enum: + - rateLimiting + window: + type: string + description: The time window for the rate limit. Operations are counted within this rolling window. + example: 4d2h45m + maxCount: + type: integer + description: The maximum number of operations allowed within the window. When the count is exceeded, subsequent operations will be rejected. Mutually exclusive with `maxValueCents`. + example: 10 + maxValueCents: + type: integer + description: The maximum cumulative USD value in cents of operations allowed within the window. When the value is exceeded, subsequent operations will be rejected. Mutually exclusive with `maxCount`. + example: 100000 + required: + - type + - window + SendEndUserEvmAssetCriteria: + x-audience: development + type: array + description: A schema for specifying criteria for the sendEndUserEvmAsset operation. + items: + oneOf: + - $ref: '#/components/schemas/EthValueCriterion' + - $ref: '#/components/schemas/EvmAddressCriterion' + - $ref: '#/components/schemas/EvmNetworkCriterion' + - $ref: '#/components/schemas/EvmDataCriterion' + - $ref: '#/components/schemas/NetUSDChangeCriterion' + - $ref: '#/components/schemas/RateLimitingCriterion' + example: + - type: ethValue + ethValue: '1000000' + operator: '>=' + - type: evmAddress + addresses: + - '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' + operator: in + - type: evmNetwork + networks: + - base + - ethereum + operator: in + - type: evmData + abi: erc20 + conditions: + - function: transfer + params: + - name: value + operator: <= + value: '10000' + - type: netUSDChange + changeCents: 10000 + operator: <= + SendEndUserEvmAssetRule: + x-audience: development + title: SendEndUserEvmAssetRule + properties: + action: + type: string + description: Whether matching the rule will cause the request to be rejected or accepted. + example: accept + enum: + - reject + - accept + operation: + type: string + description: The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. + example: sendEndUserEvmAsset + enum: + - sendEndUserEvmAsset + criteria: + $ref: '#/components/schemas/SendEndUserEvmAssetCriteria' + required: + - action + - operation + - criteria SignEndUserEvmMessageCriteria: x-audience: public type: array @@ -10652,6 +10738,81 @@ components: - action - operation - criteria + SendEndUserSolAssetCriteria: + x-audience: development + type: array + description: A schema for specifying criteria for the sendEndUserSolAsset operation. + items: + oneOf: + - $ref: '#/components/schemas/SolAddressCriterion' + - $ref: '#/components/schemas/SolValueCriterion' + - $ref: '#/components/schemas/SplAddressCriterion' + - $ref: '#/components/schemas/SplValueCriterion' + - $ref: '#/components/schemas/MintAddressCriterion' + - $ref: '#/components/schemas/SolDataCriterion' + - $ref: '#/components/schemas/ProgramIdCriterion' + - $ref: '#/components/schemas/SolNetworkCriterion' + - $ref: '#/components/schemas/RateLimitingCriterion' + example: + - type: solAddress + addresses: + - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + operator: in + - type: solValue + solValue: '1000000000000000000' + operator: <= + - type: splAddress + addresses: + - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + operator: in + - type: splValue + splValue: '1000000000000000000' + operator: <= + - type: mintAddress + addresses: + - HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT + operator: in + - type: solData + idls: + - SystemProgram + conditions: + - instruction: transfer_checked + params: + - name: lamports + operator: <= + value: '1000000' + - type: programId + programIds: + - TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA + operator: in + - type: solNetwork + networks: + - solana-devnet + - solana + operator: in + SendEndUserSolAssetRule: + x-audience: development + title: SendEndUserSolAssetRule + properties: + action: + type: string + description: Whether matching the rule will cause the request to be rejected or accepted. + example: accept + enum: + - reject + - accept + operation: + type: string + description: The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. + example: sendEndUserSolAsset + enum: + - sendEndUserSolAsset + criteria: + $ref: '#/components/schemas/SendEndUserSolAssetCriteria' + required: + - action + - operation + - criteria SignEndUserSolMessageCriteria: x-audience: public type: array @@ -10706,6 +10867,8 @@ components: - $ref: '#/components/schemas/SignEndUserSolTransactionRule' - $ref: '#/components/schemas/SendEndUserSolTransactionRule' - $ref: '#/components/schemas/SignEndUserSolMessageRule' + - $ref: '#/components/schemas/SendEndUserEvmAssetRule' + - $ref: '#/components/schemas/SendEndUserSolAssetRule' example: action: accept operation: signEvmTransaction diff --git a/python/cdp/openapi_client/__init__.py b/python/cdp/openapi_client/__init__.py index b3594b5f3..50ba5ef4d 100644 --- a/python/cdp/openapi_client/__init__.py +++ b/python/cdp/openapi_client/__init__.py @@ -174,13 +174,18 @@ from cdp.openapi_client.models.prepare_user_operation_rule import PrepareUserOperationRule from cdp.openapi_client.models.program_id_criterion import ProgramIdCriterion from cdp.openapi_client.models.query_result_cache_configuration import QueryResultCacheConfiguration +from cdp.openapi_client.models.rate_limiting_criterion import RateLimitingCriterion from cdp.openapi_client.models.request_evm_faucet200_response import RequestEvmFaucet200Response from cdp.openapi_client.models.request_evm_faucet_request import RequestEvmFaucetRequest from cdp.openapi_client.models.request_solana_faucet200_response import RequestSolanaFaucet200Response from cdp.openapi_client.models.request_solana_faucet_request import RequestSolanaFaucetRequest from cdp.openapi_client.models.revoke_spend_permission_request import RevokeSpendPermissionRequest from cdp.openapi_client.models.rule import Rule +from cdp.openapi_client.models.send_end_user_evm_asset_criteria_inner import SendEndUserEvmAssetCriteriaInner +from cdp.openapi_client.models.send_end_user_evm_asset_rule import SendEndUserEvmAssetRule from cdp.openapi_client.models.send_end_user_evm_transaction_rule import SendEndUserEvmTransactionRule +from cdp.openapi_client.models.send_end_user_sol_asset_criteria_inner import SendEndUserSolAssetCriteriaInner +from cdp.openapi_client.models.send_end_user_sol_asset_rule import SendEndUserSolAssetRule from cdp.openapi_client.models.send_end_user_sol_transaction_rule import SendEndUserSolTransactionRule from cdp.openapi_client.models.send_evm_transaction200_response import SendEvmTransaction200Response from cdp.openapi_client.models.send_evm_transaction_criteria_inner import SendEvmTransactionCriteriaInner diff --git a/python/cdp/openapi_client/models/__init__.py b/python/cdp/openapi_client/models/__init__.py index 9fa7f21f4..2b824c881 100644 --- a/python/cdp/openapi_client/models/__init__.py +++ b/python/cdp/openapi_client/models/__init__.py @@ -143,13 +143,18 @@ from cdp.openapi_client.models.prepare_user_operation_rule import PrepareUserOperationRule from cdp.openapi_client.models.program_id_criterion import ProgramIdCriterion from cdp.openapi_client.models.query_result_cache_configuration import QueryResultCacheConfiguration +from cdp.openapi_client.models.rate_limiting_criterion import RateLimitingCriterion from cdp.openapi_client.models.request_evm_faucet200_response import RequestEvmFaucet200Response from cdp.openapi_client.models.request_evm_faucet_request import RequestEvmFaucetRequest from cdp.openapi_client.models.request_solana_faucet200_response import RequestSolanaFaucet200Response from cdp.openapi_client.models.request_solana_faucet_request import RequestSolanaFaucetRequest from cdp.openapi_client.models.revoke_spend_permission_request import RevokeSpendPermissionRequest from cdp.openapi_client.models.rule import Rule +from cdp.openapi_client.models.send_end_user_evm_asset_criteria_inner import SendEndUserEvmAssetCriteriaInner +from cdp.openapi_client.models.send_end_user_evm_asset_rule import SendEndUserEvmAssetRule from cdp.openapi_client.models.send_end_user_evm_transaction_rule import SendEndUserEvmTransactionRule +from cdp.openapi_client.models.send_end_user_sol_asset_criteria_inner import SendEndUserSolAssetCriteriaInner +from cdp.openapi_client.models.send_end_user_sol_asset_rule import SendEndUserSolAssetRule from cdp.openapi_client.models.send_end_user_sol_transaction_rule import SendEndUserSolTransactionRule from cdp.openapi_client.models.send_evm_transaction200_response import SendEvmTransaction200Response from cdp.openapi_client.models.send_evm_transaction_criteria_inner import SendEvmTransactionCriteriaInner diff --git a/python/cdp/openapi_client/models/rate_limiting_criterion.py b/python/cdp/openapi_client/models/rate_limiting_criterion.py new file mode 100644 index 000000000..5081f6894 --- /dev/null +++ b/python/cdp/openapi_client/models/rate_limiting_criterion.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class RateLimitingCriterion(BaseModel): + """ + A criterion that limits the number or value of operations within a time window. When the limit is exceeded, subsequent operations matching this criterion will be rejected until the window resets. + """ # noqa: E501 + type: StrictStr = Field(description="The type of criterion to use. This should be `rateLimiting`.") + window: StrictStr = Field(description="The time window for the rate limit. Operations are counted within this rolling window.") + max_count: Optional[StrictInt] = Field(default=None, description="The maximum number of operations allowed within the window. When the count is exceeded, subsequent operations will be rejected. Mutually exclusive with `maxValueCents`.", alias="maxCount") + max_value_cents: Optional[StrictInt] = Field(default=None, description="The maximum cumulative USD value in cents of operations allowed within the window. When the value is exceeded, subsequent operations will be rejected. Mutually exclusive with `maxCount`.", alias="maxValueCents") + __properties: ClassVar[List[str]] = ["type", "window", "maxCount", "maxValueCents"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['rateLimiting']): + raise ValueError("must be one of enum values ('rateLimiting')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of RateLimitingCriterion from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of RateLimitingCriterion from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "window": obj.get("window"), + "maxCount": obj.get("maxCount"), + "maxValueCents": obj.get("maxValueCents") + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/rule.py b/python/cdp/openapi_client/models/rule.py index 83408a6cb..754e2f53c 100644 --- a/python/cdp/openapi_client/models/rule.py +++ b/python/cdp/openapi_client/models/rule.py @@ -19,7 +19,9 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from cdp.openapi_client.models.prepare_user_operation_rule import PrepareUserOperationRule +from cdp.openapi_client.models.send_end_user_evm_asset_rule import SendEndUserEvmAssetRule from cdp.openapi_client.models.send_end_user_evm_transaction_rule import SendEndUserEvmTransactionRule +from cdp.openapi_client.models.send_end_user_sol_asset_rule import SendEndUserSolAssetRule from cdp.openapi_client.models.send_end_user_sol_transaction_rule import SendEndUserSolTransactionRule from cdp.openapi_client.models.send_evm_transaction_rule import SendEvmTransactionRule from cdp.openapi_client.models.send_sol_transaction_rule import SendSolTransactionRule @@ -39,7 +41,7 @@ from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self -RULE_ONE_OF_SCHEMAS = ["PrepareUserOperationRule", "SendEndUserEvmTransactionRule", "SendEndUserSolTransactionRule", "SendEvmTransactionRule", "SendSolTransactionRule", "SendUserOperationRule", "SignEndUserEvmMessageRule", "SignEndUserEvmTransactionRule", "SignEndUserEvmTypedDataRule", "SignEndUserSolMessageRule", "SignEndUserSolTransactionRule", "SignEvmHashRule", "SignEvmMessageRule", "SignEvmTransactionRule", "SignEvmTypedDataRule", "SignSolMessageRule", "SignSolTransactionRule"] +RULE_ONE_OF_SCHEMAS = ["PrepareUserOperationRule", "SendEndUserEvmAssetRule", "SendEndUserEvmTransactionRule", "SendEndUserSolAssetRule", "SendEndUserSolTransactionRule", "SendEvmTransactionRule", "SendSolTransactionRule", "SendUserOperationRule", "SignEndUserEvmMessageRule", "SignEndUserEvmTransactionRule", "SignEndUserEvmTypedDataRule", "SignEndUserSolMessageRule", "SignEndUserSolTransactionRule", "SignEvmHashRule", "SignEvmMessageRule", "SignEvmTransactionRule", "SignEvmTypedDataRule", "SignSolMessageRule", "SignSolTransactionRule"] class Rule(BaseModel): """ @@ -79,8 +81,12 @@ class Rule(BaseModel): oneof_schema_16_validator: Optional[SendEndUserSolTransactionRule] = None # data type: SignEndUserSolMessageRule oneof_schema_17_validator: Optional[SignEndUserSolMessageRule] = None - actual_instance: Optional[Union[PrepareUserOperationRule, SendEndUserEvmTransactionRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule]] = None - one_of_schemas: Set[str] = { "PrepareUserOperationRule", "SendEndUserEvmTransactionRule", "SendEndUserSolTransactionRule", "SendEvmTransactionRule", "SendSolTransactionRule", "SendUserOperationRule", "SignEndUserEvmMessageRule", "SignEndUserEvmTransactionRule", "SignEndUserEvmTypedDataRule", "SignEndUserSolMessageRule", "SignEndUserSolTransactionRule", "SignEvmHashRule", "SignEvmMessageRule", "SignEvmTransactionRule", "SignEvmTypedDataRule", "SignSolMessageRule", "SignSolTransactionRule" } + # data type: SendEndUserEvmAssetRule + oneof_schema_18_validator: Optional[SendEndUserEvmAssetRule] = None + # data type: SendEndUserSolAssetRule + oneof_schema_19_validator: Optional[SendEndUserSolAssetRule] = None + actual_instance: Optional[Union[PrepareUserOperationRule, SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule]] = None + one_of_schemas: Set[str] = { "PrepareUserOperationRule", "SendEndUserEvmAssetRule", "SendEndUserEvmTransactionRule", "SendEndUserSolAssetRule", "SendEndUserSolTransactionRule", "SendEvmTransactionRule", "SendSolTransactionRule", "SendUserOperationRule", "SignEndUserEvmMessageRule", "SignEndUserEvmTransactionRule", "SignEndUserEvmTypedDataRule", "SignEndUserSolMessageRule", "SignEndUserSolTransactionRule", "SignEvmHashRule", "SignEvmMessageRule", "SignEvmTransactionRule", "SignEvmTypedDataRule", "SignSolMessageRule", "SignSolTransactionRule" } model_config = ConfigDict( validate_assignment=True, @@ -188,12 +194,22 @@ def actual_instance_must_validate_oneof(cls, v): error_messages.append(f"Error! Input type `{type(v)}` is not `SignEndUserSolMessageRule`") else: match += 1 + # validate data type: SendEndUserEvmAssetRule + if not isinstance(v, SendEndUserEvmAssetRule): + error_messages.append(f"Error! Input type `{type(v)}` is not `SendEndUserEvmAssetRule`") + else: + match += 1 + # validate data type: SendEndUserSolAssetRule + if not isinstance(v, SendEndUserSolAssetRule): + error_messages.append(f"Error! Input type `{type(v)}` is not `SendEndUserSolAssetRule`") + else: + match += 1 if match > 1: # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmTransactionRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) + raise ValueError("Multiple matches found when setting `actual_instance` in Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError("No match found when setting `actual_instance` in Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmTransactionRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) + raise ValueError("No match found when setting `actual_instance` in Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) else: return v @@ -310,13 +326,25 @@ def from_json(cls, json_str: str) -> Self: match += 1 except (ValidationError, ValueError) as e: error_messages.append(str(e)) + # deserialize data into SendEndUserEvmAssetRule + try: + instance.actual_instance = SendEndUserEvmAssetRule.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SendEndUserSolAssetRule + try: + instance.actual_instance = SendEndUserSolAssetRule.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) if match > 1: # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmTransactionRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) + raise ValueError("Multiple matches found when deserializing the JSON string into Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError("No match found when deserializing the JSON string into Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmTransactionRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) + raise ValueError("No match found when deserializing the JSON string into Rule with oneOf schemas: PrepareUserOperationRule, SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule. Details: " + ", ".join(error_messages)) else: return instance @@ -330,7 +358,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> Optional[Union[Dict[str, Any], PrepareUserOperationRule, SendEndUserEvmTransactionRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule]]: + def to_dict(self) -> Optional[Union[Dict[str, Any], PrepareUserOperationRule, SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolTransactionRule, SendUserOperationRule, SignEndUserEvmMessageRule, SignEndUserEvmTransactionRule, SignEndUserEvmTypedDataRule, SignEndUserSolMessageRule, SignEndUserSolTransactionRule, SignEvmHashRule, SignEvmMessageRule, SignEvmTransactionRule, SignEvmTypedDataRule, SignSolMessageRule, SignSolTransactionRule]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None diff --git a/python/cdp/openapi_client/models/send_end_user_evm_asset_criteria_inner.py b/python/cdp/openapi_client/models/send_end_user_evm_asset_criteria_inner.py new file mode 100644 index 000000000..f88acccf8 --- /dev/null +++ b/python/cdp/openapi_client/models/send_end_user_evm_asset_criteria_inner.py @@ -0,0 +1,194 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.eth_value_criterion import EthValueCriterion +from cdp.openapi_client.models.evm_address_criterion import EvmAddressCriterion +from cdp.openapi_client.models.evm_data_criterion import EvmDataCriterion +from cdp.openapi_client.models.evm_network_criterion import EvmNetworkCriterion +from cdp.openapi_client.models.net_usd_change_criterion import NetUSDChangeCriterion +from cdp.openapi_client.models.rate_limiting_criterion import RateLimitingCriterion +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +SENDENDUSEREVMASSETCRITERIAINNER_ONE_OF_SCHEMAS = ["EthValueCriterion", "EvmAddressCriterion", "EvmDataCriterion", "EvmNetworkCriterion", "NetUSDChangeCriterion", "RateLimitingCriterion"] + +class SendEndUserEvmAssetCriteriaInner(BaseModel): + """ + SendEndUserEvmAssetCriteriaInner + """ + # data type: EthValueCriterion + oneof_schema_1_validator: Optional[EthValueCriterion] = None + # data type: EvmAddressCriterion + oneof_schema_2_validator: Optional[EvmAddressCriterion] = None + # data type: EvmNetworkCriterion + oneof_schema_3_validator: Optional[EvmNetworkCriterion] = None + # data type: EvmDataCriterion + oneof_schema_4_validator: Optional[EvmDataCriterion] = None + # data type: NetUSDChangeCriterion + oneof_schema_5_validator: Optional[NetUSDChangeCriterion] = None + # data type: RateLimitingCriterion + oneof_schema_6_validator: Optional[RateLimitingCriterion] = None + actual_instance: Optional[Union[EthValueCriterion, EvmAddressCriterion, EvmDataCriterion, EvmNetworkCriterion, NetUSDChangeCriterion, RateLimitingCriterion]] = None + one_of_schemas: Set[str] = { "EthValueCriterion", "EvmAddressCriterion", "EvmDataCriterion", "EvmNetworkCriterion", "NetUSDChangeCriterion", "RateLimitingCriterion" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = SendEndUserEvmAssetCriteriaInner.model_construct() + error_messages = [] + match = 0 + # validate data type: EthValueCriterion + if not isinstance(v, EthValueCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `EthValueCriterion`") + else: + match += 1 + # validate data type: EvmAddressCriterion + if not isinstance(v, EvmAddressCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `EvmAddressCriterion`") + else: + match += 1 + # validate data type: EvmNetworkCriterion + if not isinstance(v, EvmNetworkCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `EvmNetworkCriterion`") + else: + match += 1 + # validate data type: EvmDataCriterion + if not isinstance(v, EvmDataCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `EvmDataCriterion`") + else: + match += 1 + # validate data type: NetUSDChangeCriterion + if not isinstance(v, NetUSDChangeCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `NetUSDChangeCriterion`") + else: + match += 1 + # validate data type: RateLimitingCriterion + if not isinstance(v, RateLimitingCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `RateLimitingCriterion`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in SendEndUserEvmAssetCriteriaInner with oneOf schemas: EthValueCriterion, EvmAddressCriterion, EvmDataCriterion, EvmNetworkCriterion, NetUSDChangeCriterion, RateLimitingCriterion. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in SendEndUserEvmAssetCriteriaInner with oneOf schemas: EthValueCriterion, EvmAddressCriterion, EvmDataCriterion, EvmNetworkCriterion, NetUSDChangeCriterion, RateLimitingCriterion. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into EthValueCriterion + try: + instance.actual_instance = EthValueCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into EvmAddressCriterion + try: + instance.actual_instance = EvmAddressCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into EvmNetworkCriterion + try: + instance.actual_instance = EvmNetworkCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into EvmDataCriterion + try: + instance.actual_instance = EvmDataCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into NetUSDChangeCriterion + try: + instance.actual_instance = NetUSDChangeCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into RateLimitingCriterion + try: + instance.actual_instance = RateLimitingCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into SendEndUserEvmAssetCriteriaInner with oneOf schemas: EthValueCriterion, EvmAddressCriterion, EvmDataCriterion, EvmNetworkCriterion, NetUSDChangeCriterion, RateLimitingCriterion. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into SendEndUserEvmAssetCriteriaInner with oneOf schemas: EthValueCriterion, EvmAddressCriterion, EvmDataCriterion, EvmNetworkCriterion, NetUSDChangeCriterion, RateLimitingCriterion. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], EthValueCriterion, EvmAddressCriterion, EvmDataCriterion, EvmNetworkCriterion, NetUSDChangeCriterion, RateLimitingCriterion]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/send_end_user_evm_asset_rule.py b/python/cdp/openapi_client/models/send_end_user_evm_asset_rule.py new file mode 100644 index 000000000..eeca0af80 --- /dev/null +++ b/python/cdp/openapi_client/models/send_end_user_evm_asset_rule.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from cdp.openapi_client.models.send_end_user_evm_asset_criteria_inner import SendEndUserEvmAssetCriteriaInner +from typing import Optional, Set +from typing_extensions import Self + +class SendEndUserEvmAssetRule(BaseModel): + """ + SendEndUserEvmAssetRule + """ # noqa: E501 + action: StrictStr = Field(description="Whether matching the rule will cause the request to be rejected or accepted.") + operation: StrictStr = Field(description="The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.") + criteria: List[SendEndUserEvmAssetCriteriaInner] = Field(description="A schema for specifying criteria for the sendEndUserEvmAsset operation.") + __properties: ClassVar[List[str]] = ["action", "operation", "criteria"] + + @field_validator('action') + def action_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['reject', 'accept']): + raise ValueError("must be one of enum values ('reject', 'accept')") + return value + + @field_validator('operation') + def operation_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['sendEndUserEvmAsset']): + raise ValueError("must be one of enum values ('sendEndUserEvmAsset')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SendEndUserEvmAssetRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in criteria (list) + _items = [] + if self.criteria: + for _item_criteria in self.criteria: + if _item_criteria: + _items.append(_item_criteria.to_dict()) + _dict['criteria'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SendEndUserEvmAssetRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "action": obj.get("action"), + "operation": obj.get("operation"), + "criteria": [SendEndUserEvmAssetCriteriaInner.from_dict(_item) for _item in obj["criteria"]] if obj.get("criteria") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/models/send_end_user_sol_asset_criteria_inner.py b/python/cdp/openapi_client/models/send_end_user_sol_asset_criteria_inner.py new file mode 100644 index 000000000..bcb4b6d05 --- /dev/null +++ b/python/cdp/openapi_client/models/send_end_user_sol_asset_criteria_inner.py @@ -0,0 +1,236 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.openapi_client.models.mint_address_criterion import MintAddressCriterion +from cdp.openapi_client.models.program_id_criterion import ProgramIdCriterion +from cdp.openapi_client.models.rate_limiting_criterion import RateLimitingCriterion +from cdp.openapi_client.models.sol_address_criterion import SolAddressCriterion +from cdp.openapi_client.models.sol_data_criterion import SolDataCriterion +from cdp.openapi_client.models.sol_network_criterion import SolNetworkCriterion +from cdp.openapi_client.models.sol_value_criterion import SolValueCriterion +from cdp.openapi_client.models.spl_address_criterion import SplAddressCriterion +from cdp.openapi_client.models.spl_value_criterion import SplValueCriterion +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +SENDENDUSERSOLASSETCRITERIAINNER_ONE_OF_SCHEMAS = ["MintAddressCriterion", "ProgramIdCriterion", "RateLimitingCriterion", "SolAddressCriterion", "SolDataCriterion", "SolNetworkCriterion", "SolValueCriterion", "SplAddressCriterion", "SplValueCriterion"] + +class SendEndUserSolAssetCriteriaInner(BaseModel): + """ + SendEndUserSolAssetCriteriaInner + """ + # data type: SolAddressCriterion + oneof_schema_1_validator: Optional[SolAddressCriterion] = None + # data type: SolValueCriterion + oneof_schema_2_validator: Optional[SolValueCriterion] = None + # data type: SplAddressCriterion + oneof_schema_3_validator: Optional[SplAddressCriterion] = None + # data type: SplValueCriterion + oneof_schema_4_validator: Optional[SplValueCriterion] = None + # data type: MintAddressCriterion + oneof_schema_5_validator: Optional[MintAddressCriterion] = None + # data type: SolDataCriterion + oneof_schema_6_validator: Optional[SolDataCriterion] = None + # data type: ProgramIdCriterion + oneof_schema_7_validator: Optional[ProgramIdCriterion] = None + # data type: SolNetworkCriterion + oneof_schema_8_validator: Optional[SolNetworkCriterion] = None + # data type: RateLimitingCriterion + oneof_schema_9_validator: Optional[RateLimitingCriterion] = None + actual_instance: Optional[Union[MintAddressCriterion, ProgramIdCriterion, RateLimitingCriterion, SolAddressCriterion, SolDataCriterion, SolNetworkCriterion, SolValueCriterion, SplAddressCriterion, SplValueCriterion]] = None + one_of_schemas: Set[str] = { "MintAddressCriterion", "ProgramIdCriterion", "RateLimitingCriterion", "SolAddressCriterion", "SolDataCriterion", "SolNetworkCriterion", "SolValueCriterion", "SplAddressCriterion", "SplValueCriterion" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = SendEndUserSolAssetCriteriaInner.model_construct() + error_messages = [] + match = 0 + # validate data type: SolAddressCriterion + if not isinstance(v, SolAddressCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `SolAddressCriterion`") + else: + match += 1 + # validate data type: SolValueCriterion + if not isinstance(v, SolValueCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `SolValueCriterion`") + else: + match += 1 + # validate data type: SplAddressCriterion + if not isinstance(v, SplAddressCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `SplAddressCriterion`") + else: + match += 1 + # validate data type: SplValueCriterion + if not isinstance(v, SplValueCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `SplValueCriterion`") + else: + match += 1 + # validate data type: MintAddressCriterion + if not isinstance(v, MintAddressCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `MintAddressCriterion`") + else: + match += 1 + # validate data type: SolDataCriterion + if not isinstance(v, SolDataCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `SolDataCriterion`") + else: + match += 1 + # validate data type: ProgramIdCriterion + if not isinstance(v, ProgramIdCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `ProgramIdCriterion`") + else: + match += 1 + # validate data type: SolNetworkCriterion + if not isinstance(v, SolNetworkCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `SolNetworkCriterion`") + else: + match += 1 + # validate data type: RateLimitingCriterion + if not isinstance(v, RateLimitingCriterion): + error_messages.append(f"Error! Input type `{type(v)}` is not `RateLimitingCriterion`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in SendEndUserSolAssetCriteriaInner with oneOf schemas: MintAddressCriterion, ProgramIdCriterion, RateLimitingCriterion, SolAddressCriterion, SolDataCriterion, SolNetworkCriterion, SolValueCriterion, SplAddressCriterion, SplValueCriterion. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in SendEndUserSolAssetCriteriaInner with oneOf schemas: MintAddressCriterion, ProgramIdCriterion, RateLimitingCriterion, SolAddressCriterion, SolDataCriterion, SolNetworkCriterion, SolValueCriterion, SplAddressCriterion, SplValueCriterion. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into SolAddressCriterion + try: + instance.actual_instance = SolAddressCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SolValueCriterion + try: + instance.actual_instance = SolValueCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SplAddressCriterion + try: + instance.actual_instance = SplAddressCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SplValueCriterion + try: + instance.actual_instance = SplValueCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into MintAddressCriterion + try: + instance.actual_instance = MintAddressCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SolDataCriterion + try: + instance.actual_instance = SolDataCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into ProgramIdCriterion + try: + instance.actual_instance = ProgramIdCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into SolNetworkCriterion + try: + instance.actual_instance = SolNetworkCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into RateLimitingCriterion + try: + instance.actual_instance = RateLimitingCriterion.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into SendEndUserSolAssetCriteriaInner with oneOf schemas: MintAddressCriterion, ProgramIdCriterion, RateLimitingCriterion, SolAddressCriterion, SolDataCriterion, SolNetworkCriterion, SolValueCriterion, SplAddressCriterion, SplValueCriterion. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into SendEndUserSolAssetCriteriaInner with oneOf schemas: MintAddressCriterion, ProgramIdCriterion, RateLimitingCriterion, SolAddressCriterion, SolDataCriterion, SolNetworkCriterion, SolValueCriterion, SplAddressCriterion, SplValueCriterion. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], MintAddressCriterion, ProgramIdCriterion, RateLimitingCriterion, SolAddressCriterion, SolDataCriterion, SolNetworkCriterion, SolValueCriterion, SplAddressCriterion, SplValueCriterion]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/cdp/openapi_client/models/send_end_user_sol_asset_rule.py b/python/cdp/openapi_client/models/send_end_user_sol_asset_rule.py new file mode 100644 index 000000000..649fd478d --- /dev/null +++ b/python/cdp/openapi_client/models/send_end_user_sol_asset_rule.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from cdp.openapi_client.models.send_end_user_sol_asset_criteria_inner import SendEndUserSolAssetCriteriaInner +from typing import Optional, Set +from typing_extensions import Self + +class SendEndUserSolAssetRule(BaseModel): + """ + SendEndUserSolAssetRule + """ # noqa: E501 + action: StrictStr = Field(description="Whether matching the rule will cause the request to be rejected or accepted.") + operation: StrictStr = Field(description="The operation to which the rule applies. Every element of the `criteria` array must match the specified operation.") + criteria: List[SendEndUserSolAssetCriteriaInner] = Field(description="A schema for specifying criteria for the sendEndUserSolAsset operation.") + __properties: ClassVar[List[str]] = ["action", "operation", "criteria"] + + @field_validator('action') + def action_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['reject', 'accept']): + raise ValueError("must be one of enum values ('reject', 'accept')") + return value + + @field_validator('operation') + def operation_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['sendEndUserSolAsset']): + raise ValueError("must be one of enum values ('sendEndUserSolAsset')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SendEndUserSolAssetRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in criteria (list) + _items = [] + if self.criteria: + for _item_criteria in self.criteria: + if _item_criteria: + _items.append(_item_criteria.to_dict()) + _dict['criteria'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SendEndUserSolAssetRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "action": obj.get("action"), + "operation": obj.get("operation"), + "criteria": [SendEndUserSolAssetCriteriaInner.from_dict(_item) for _item in obj["criteria"]] if obj.get("criteria") is not None else None + }) + return _obj + + diff --git a/python/cdp/openapi_client/test/test_rate_limiting_criterion.py b/python/cdp/openapi_client/test/test_rate_limiting_criterion.py new file mode 100644 index 000000000..096224654 --- /dev/null +++ b/python/cdp/openapi_client/test/test_rate_limiting_criterion.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.rate_limiting_criterion import RateLimitingCriterion + +class TestRateLimitingCriterion(unittest.TestCase): + """RateLimitingCriterion unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> RateLimitingCriterion: + """Test RateLimitingCriterion + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `RateLimitingCriterion` + """ + model = RateLimitingCriterion() + if include_optional: + return RateLimitingCriterion( + type = 'rateLimiting', + window = '4d2h45m', + max_count = 10, + max_value_cents = 100000 + ) + else: + return RateLimitingCriterion( + type = 'rateLimiting', + window = '4d2h45m', + ) + """ + + def testRateLimitingCriterion(self): + """Test RateLimitingCriterion""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_rule.py b/python/cdp/openapi_client/test/test_rule.py index 246ff364e..96e620bbd 100644 --- a/python/cdp/openapi_client/test/test_rule.py +++ b/python/cdp/openapi_client/test/test_rule.py @@ -37,14 +37,14 @@ def make_instance(self, include_optional) -> Rule: if include_optional: return Rule( action = 'accept', - operation = 'signEndUserSolMessage', - criteria = [{type=solMessage, match=^hello ([a-z]+)$}] + operation = 'sendEndUserSolAsset', + criteria = [{type=solAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solValue, solValue=1000000000000000000, operator=<=}, {type=splAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=splValue, splValue=1000000000000000000, operator=<=}, {type=mintAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solData, idls=[SystemProgram], conditions=[{instruction=transfer_checked, params=[{name=lamports, operator=<=, value=1000000}]}]}, {type=programId, programIds=[TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA], operator=in}, {type=solNetwork, networks=[solana-devnet, solana], operator=in}] ) else: return Rule( action = 'accept', - operation = 'signEndUserSolMessage', - criteria = [{type=solMessage, match=^hello ([a-z]+)$}], + operation = 'sendEndUserSolAsset', + criteria = [{type=solAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solValue, solValue=1000000000000000000, operator=<=}, {type=splAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=splValue, splValue=1000000000000000000, operator=<=}, {type=mintAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solData, idls=[SystemProgram], conditions=[{instruction=transfer_checked, params=[{name=lamports, operator=<=, value=1000000}]}]}, {type=programId, programIds=[TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA], operator=in}, {type=solNetwork, networks=[solana-devnet, solana], operator=in}], ) """ diff --git a/python/cdp/openapi_client/test/test_send_end_user_evm_asset_criteria_inner.py b/python/cdp/openapi_client/test/test_send_end_user_evm_asset_criteria_inner.py new file mode 100644 index 000000000..9ce8ef82a --- /dev/null +++ b/python/cdp/openapi_client/test/test_send_end_user_evm_asset_criteria_inner.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.send_end_user_evm_asset_criteria_inner import SendEndUserEvmAssetCriteriaInner + +class TestSendEndUserEvmAssetCriteriaInner(unittest.TestCase): + """SendEndUserEvmAssetCriteriaInner unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SendEndUserEvmAssetCriteriaInner: + """Test SendEndUserEvmAssetCriteriaInner + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SendEndUserEvmAssetCriteriaInner` + """ + model = SendEndUserEvmAssetCriteriaInner() + if include_optional: + return SendEndUserEvmAssetCriteriaInner( + type = 'ethValue', + eth_value = '1000000000000000000', + operator = '<=', + addresses = [0x742d35Cc6634C0532925a3b844Bc454e4438f44e, 0x1234567890123456789012345678901234567890], + networks = [base, ethereum], + abi = erc20, + conditions = [{function=approve}, {function=transfer, params=[{name=value, operator=<=, value=10000}, {name=to, operator=in, values=[0x742d35Cc6634C0532925a3b844Bc454e4438f44e]}]}], + change_cents = 10000, + window = '4d2h45m', + max_count = 10, + max_value_cents = 100000 + ) + else: + return SendEndUserEvmAssetCriteriaInner( + type = 'ethValue', + eth_value = '1000000000000000000', + operator = '<=', + addresses = [0x742d35Cc6634C0532925a3b844Bc454e4438f44e, 0x1234567890123456789012345678901234567890], + networks = [base, ethereum], + abi = erc20, + conditions = [{function=approve}, {function=transfer, params=[{name=value, operator=<=, value=10000}, {name=to, operator=in, values=[0x742d35Cc6634C0532925a3b844Bc454e4438f44e]}]}], + change_cents = 10000, + window = '4d2h45m', + ) + """ + + def testSendEndUserEvmAssetCriteriaInner(self): + """Test SendEndUserEvmAssetCriteriaInner""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_send_end_user_evm_asset_rule.py b/python/cdp/openapi_client/test/test_send_end_user_evm_asset_rule.py new file mode 100644 index 000000000..5023a9f85 --- /dev/null +++ b/python/cdp/openapi_client/test/test_send_end_user_evm_asset_rule.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.send_end_user_evm_asset_rule import SendEndUserEvmAssetRule + +class TestSendEndUserEvmAssetRule(unittest.TestCase): + """SendEndUserEvmAssetRule unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SendEndUserEvmAssetRule: + """Test SendEndUserEvmAssetRule + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SendEndUserEvmAssetRule` + """ + model = SendEndUserEvmAssetRule() + if include_optional: + return SendEndUserEvmAssetRule( + action = 'accept', + operation = 'sendEndUserEvmAsset', + criteria = [{type=ethValue, ethValue=1000000, operator=>=}, {type=evmAddress, addresses=[0x742d35Cc6634C0532925a3b844Bc454e4438f44e], operator=in}, {type=evmNetwork, networks=[base, ethereum], operator=in}, {type=evmData, abi=erc20, conditions=[{function=transfer, params=[{name=value, operator=<=, value=10000}]}]}, {type=netUSDChange, changeCents=10000, operator=<=}] + ) + else: + return SendEndUserEvmAssetRule( + action = 'accept', + operation = 'sendEndUserEvmAsset', + criteria = [{type=ethValue, ethValue=1000000, operator=>=}, {type=evmAddress, addresses=[0x742d35Cc6634C0532925a3b844Bc454e4438f44e], operator=in}, {type=evmNetwork, networks=[base, ethereum], operator=in}, {type=evmData, abi=erc20, conditions=[{function=transfer, params=[{name=value, operator=<=, value=10000}]}]}, {type=netUSDChange, changeCents=10000, operator=<=}], + ) + """ + + def testSendEndUserEvmAssetRule(self): + """Test SendEndUserEvmAssetRule""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_send_end_user_sol_asset_criteria_inner.py b/python/cdp/openapi_client/test/test_send_end_user_sol_asset_criteria_inner.py new file mode 100644 index 000000000..f63044379 --- /dev/null +++ b/python/cdp/openapi_client/test/test_send_end_user_sol_asset_criteria_inner.py @@ -0,0 +1,73 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.send_end_user_sol_asset_criteria_inner import SendEndUserSolAssetCriteriaInner + +class TestSendEndUserSolAssetCriteriaInner(unittest.TestCase): + """SendEndUserSolAssetCriteriaInner unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SendEndUserSolAssetCriteriaInner: + """Test SendEndUserSolAssetCriteriaInner + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SendEndUserSolAssetCriteriaInner` + """ + model = SendEndUserSolAssetCriteriaInner() + if include_optional: + return SendEndUserSolAssetCriteriaInner( + type = 'solAddress', + addresses = [HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], + operator = 'in', + sol_value = '1000000000000000000', + spl_value = '1000000000000000000', + idls = [SystemProgram, TokenProgram, {address=TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA, instructions=[{name=transfer_checked, discriminator=[119, 250, 202, 24, 253, 135, 244, 121], args=[{name=amount, type=u64}, {name=decimals, type=u8}]}]}], + conditions = [{instruction=transfer_checked, params=[{name=lamports, operator=<=, value=1000000}, {name=space, operator===, value=64}]}], + program_ids = [TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA, 11111111111111111111111111111112], + networks = [solana-devnet, solana], + window = '4d2h45m', + max_count = 10, + max_value_cents = 100000 + ) + else: + return SendEndUserSolAssetCriteriaInner( + type = 'solAddress', + addresses = [HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], + operator = 'in', + sol_value = '1000000000000000000', + spl_value = '1000000000000000000', + idls = [SystemProgram, TokenProgram, {address=TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA, instructions=[{name=transfer_checked, discriminator=[119, 250, 202, 24, 253, 135, 244, 121], args=[{name=amount, type=u64}, {name=decimals, type=u8}]}]}], + conditions = [{instruction=transfer_checked, params=[{name=lamports, operator=<=, value=1000000}, {name=space, operator===, value=64}]}], + program_ids = [TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA, 11111111111111111111111111111112], + networks = [solana-devnet, solana], + window = '4d2h45m', + ) + """ + + def testSendEndUserSolAssetCriteriaInner(self): + """Test SendEndUserSolAssetCriteriaInner""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/openapi_client/test/test_send_end_user_sol_asset_rule.py b/python/cdp/openapi_client/test/test_send_end_user_sol_asset_rule.py new file mode 100644 index 000000000..2e25d7b01 --- /dev/null +++ b/python/cdp/openapi_client/test/test_send_end_user_sol_asset_rule.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Coinbase Developer Platform APIs + + The Coinbase Developer Platform APIs - leading the world's transition onchain. + + The version of the OpenAPI document: 2.0.0 + Contact: cdp@coinbase.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from cdp.openapi_client.models.send_end_user_sol_asset_rule import SendEndUserSolAssetRule + +class TestSendEndUserSolAssetRule(unittest.TestCase): + """SendEndUserSolAssetRule unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SendEndUserSolAssetRule: + """Test SendEndUserSolAssetRule + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SendEndUserSolAssetRule` + """ + model = SendEndUserSolAssetRule() + if include_optional: + return SendEndUserSolAssetRule( + action = 'accept', + operation = 'sendEndUserSolAsset', + criteria = [{type=solAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solValue, solValue=1000000000000000000, operator=<=}, {type=splAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=splValue, splValue=1000000000000000000, operator=<=}, {type=mintAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solData, idls=[SystemProgram], conditions=[{instruction=transfer_checked, params=[{name=lamports, operator=<=, value=1000000}]}]}, {type=programId, programIds=[TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA], operator=in}, {type=solNetwork, networks=[solana-devnet, solana], operator=in}] + ) + else: + return SendEndUserSolAssetRule( + action = 'accept', + operation = 'sendEndUserSolAsset', + criteria = [{type=solAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solValue, solValue=1000000000000000000, operator=<=}, {type=splAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=splValue, splValue=1000000000000000000, operator=<=}, {type=mintAddress, addresses=[HpabPRRCFbBKSuJr5PdkVvQc85FyxyTWkFM2obBRSvHT], operator=in}, {type=solData, idls=[SystemProgram], conditions=[{instruction=transfer_checked, params=[{name=lamports, operator=<=, value=1000000}]}]}, {type=programId, programIds=[TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA], operator=in}, {type=solNetwork, networks=[solana-devnet, solana], operator=in}], + ) + """ + + def testSendEndUserSolAssetRule(self): + """Test SendEndUserSolAssetRule""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/python/cdp/policies/request_transformer.py b/python/cdp/policies/request_transformer.py index 1f45f7bc8..404634718 100644 --- a/python/cdp/policies/request_transformer.py +++ b/python/cdp/policies/request_transformer.py @@ -20,10 +20,25 @@ from cdp.openapi_client.models.net_usd_change_criterion import NetUSDChangeCriterion from cdp.openapi_client.models.prepare_user_operation_rule import PrepareUserOperationRule from cdp.openapi_client.models.program_id_criterion import ProgramIdCriterion +from cdp.openapi_client.models.rate_limiting_criterion import ( + RateLimitingCriterion as OpenAPIRateLimitingCriterion, +) from cdp.openapi_client.models.rule import Rule +from cdp.openapi_client.models.send_end_user_evm_asset_criteria_inner import ( + SendEndUserEvmAssetCriteriaInner, +) +from cdp.openapi_client.models.send_end_user_evm_asset_rule import ( + SendEndUserEvmAssetRule, +) from cdp.openapi_client.models.send_end_user_evm_transaction_rule import ( SendEndUserEvmTransactionRule, ) +from cdp.openapi_client.models.send_end_user_sol_asset_criteria_inner import ( + SendEndUserSolAssetCriteriaInner, +) +from cdp.openapi_client.models.send_end_user_sol_asset_rule import ( + SendEndUserSolAssetRule, +) from cdp.openapi_client.models.send_end_user_sol_transaction_rule import ( SendEndUserSolTransactionRule, ) @@ -595,6 +610,181 @@ "sendSolTransaction" ] openapi_criterion_mapping["signEndUserSolMessage"] = openapi_criterion_mapping["signSolMessage"] +openapi_criterion_mapping["sendEndUserEvmAsset"] = { + "ethValue": lambda c: SendEndUserEvmAssetCriteriaInner( + actual_instance=EthValueCriterion( + eth_value=c.ethValue, + operator=c.operator, + type="ethValue", + ) + ), + "evmAddress": lambda c: SendEndUserEvmAssetCriteriaInner( + actual_instance=EvmAddressCriterion( + addresses=c.addresses, + operator=c.operator, + type="evmAddress", + ) + ), + "evmNetwork": lambda c: SendEndUserEvmAssetCriteriaInner( + actual_instance=EvmNetworkCriterion( + networks=c.networks, + operator=c.operator, + type="evmNetwork", + ) + ), + "netUSDChange": lambda c: SendEndUserEvmAssetCriteriaInner( + actual_instance=NetUSDChangeCriterion( + change_cents=c.changeCents, + operator=c.operator, + type="netUSDChange", + ) + ), + "evmData": lambda c: SendEndUserEvmAssetCriteriaInner( + actual_instance=EvmDataCriterion( + type="evmData", + abi=EvmDataCriterionAbi( + actual_instance=(KnownAbiType(c.abi) if isinstance(c.abi, str) else c.abi) + ), + conditions=[ + OpenAPIEvmDataCondition( + function=cond.function, + params=[ + EvmDataConditionParamsInner( + actual_instance=( + EvmDataParameterConditionList( + name=param.name, + operator=param.operator, + values=param.values, + ) + if hasattr(param, "values") + else EvmDataParameterCondition( + name=param.name, + operator=param.operator, + value=param.value, + ) + ) + ) + for param in cond.params + ] + if cond.params + else None, + ) + for cond in c.conditions + ], + ) + ), + "rateLimiting": lambda c: SendEndUserEvmAssetCriteriaInner( + actual_instance=OpenAPIRateLimitingCriterion( + type="rateLimiting", + window=c.window, + max_count=c.maxCount, + max_value_cents=c.maxValueCents, + ) + ), +} +openapi_criterion_mapping["sendEndUserSolAsset"] = { + "solAddress": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=SolAddressCriterion( + addresses=c.addresses, + operator=c.operator, + type="solAddress", + ) + ), + "solValue": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=SolValueCriterion( + sol_value=c.solValue, + operator=c.operator, + type="solValue", + ) + ), + "solNetwork": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=SolNetworkCriterion( + networks=c.networks, + operator=c.operator, + type="solNetwork", + ) + ), + "splAddress": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=SplAddressCriterion( + addresses=c.addresses, + operator=c.operator, + type="splAddress", + ) + ), + "splValue": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=SplValueCriterion( + spl_value=c.splValue, + operator=c.operator, + type="splValue", + ) + ), + "mintAddress": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=MintAddressCriterion( + addresses=c.addresses, + operator=c.operator, + type="mintAddress", + ) + ), + "programId": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=ProgramIdCriterion( + program_ids=c.programIds, + operator=c.operator, + type="programId", + ) + ), + "solData": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=SolDataCriterion( + type="solData", + idls=[ + SolDataCriterionIdlsInner( + actual_instance=( + KnownIdlType(idl) + if isinstance(idl, str) + else Idl( + address=idl.address, + instructions=idl.instructions, + ) + ) + ) + for idl in c.idls + ], + conditions=[ + SolDataCondition( + instruction=cond.instruction, + params=[ + SolDataConditionParamsInner( + actual_instance=( + SolDataParameterConditionList( + name=param.name, + operator=param.operator, + values=param.values, + ) + if hasattr(param, "values") + else SolDataParameterCondition( + name=param.name, + operator=param.operator, + value=param.value, + ) + ) + ) + for param in cond.params + ] + if cond.params + else None, + ) + for cond in c.conditions + ], + ) + ), + "rateLimiting": lambda c: SendEndUserSolAssetCriteriaInner( + actual_instance=OpenAPIRateLimitingCriterion( + type="rateLimiting", + window=c.window, + max_count=c.maxCount, + max_value_cents=c.maxValueCents, + ) + ), +} # OpenAPI rule constructor mapping openapi_rule_mapping = { @@ -615,6 +805,8 @@ "signEndUserSolTransaction": SignEndUserSolTransactionRule, "sendEndUserSolTransaction": SendEndUserSolTransactionRule, "signEndUserSolMessage": SignEndUserSolMessageRule, + "sendEndUserEvmAsset": SendEndUserEvmAssetRule, + "sendEndUserSolAsset": SendEndUserSolAssetRule, } diff --git a/python/cdp/policies/response_transformer.py b/python/cdp/policies/response_transformer.py index 051fb86b4..74dda6601 100644 --- a/python/cdp/policies/response_transformer.py +++ b/python/cdp/policies/response_transformer.py @@ -15,8 +15,11 @@ NetUSDChangeCriterion as NetUSDChangeCriterionModel, PrepareUserOperationRule as PrepareUserOperationRuleModel, ProgramIdCriterion as ProgramIdCriterionModel, + RateLimitingCriterion as RateLimitingCriterionModel, Rule as RuleType, + SendEndUserEvmAssetRule as SendEndUserEvmAssetRuleModel, SendEndUserEvmTransactionRule as SendEndUserEvmTransactionRuleModel, + SendEndUserSolAssetRule as SendEndUserSolAssetRuleModel, SendEndUserSolTransactionRule as SendEndUserSolTransactionRuleModel, SendEvmTransactionRule as SendEvmTransactionRuleModel, SendSolanaTransactionRule as SendSolanaTransactionRuleModel, @@ -361,6 +364,22 @@ "sendSolTransaction" ] response_criterion_mapping["signEndUserSolMessage"] = response_criterion_mapping["signSolMessage"] +response_criterion_mapping["sendEndUserEvmAsset"] = { + **response_criterion_mapping["sendEvmTransaction"], + "rateLimiting": lambda c: RateLimitingCriterionModel( + window=c.window, + maxCount=c.max_count, + maxValueCents=c.max_value_cents, + ), +} +response_criterion_mapping["sendEndUserSolAsset"] = { + **response_criterion_mapping["sendSolTransaction"], + "rateLimiting": lambda c: RateLimitingCriterionModel( + window=c.window, + maxCount=c.max_count, + maxValueCents=c.max_value_cents, + ), +} # Response rule class mapping response_rule_mapping = { @@ -381,6 +400,8 @@ "signEndUserSolTransaction": SignEndUserSolTransactionRuleModel, "sendEndUserSolTransaction": SendEndUserSolTransactionRuleModel, "signEndUserSolMessage": SignEndUserSolMessageRuleModel, + "sendEndUserEvmAsset": SendEndUserEvmAssetRuleModel, + "sendEndUserSolAsset": SendEndUserSolAssetRuleModel, } diff --git a/python/cdp/policies/types.py b/python/cdp/policies/types.py index 661cfa667..403543c8f 100644 --- a/python/cdp/policies/types.py +++ b/python/cdp/policies/types.py @@ -788,6 +788,27 @@ class SignEndUserEvmTransactionRule(BaseModel): ) +class RateLimitingCriterion(BaseModel): + """A criterion that limits the number or value of operations within a time window.""" + + type: Literal["rateLimiting"] = Field( + "rateLimiting", + description="The type of criterion. Must be 'rateLimiting'.", + ) + window: str = Field( + ..., + description="The time window for the rate limit (e.g. '4d2h45m').", + ) + maxCount: int | None = Field( + None, + description="Maximum number of operations allowed within the window. Mutually exclusive with maxValueCents.", + ) + maxValueCents: int | None = Field( + None, + description="Maximum cumulative USD value in cents within the window. Mutually exclusive with maxCount.", + ) + + class SendEndUserEvmTransactionRule(BaseModel): """Type representing a 'sendEndUserEvmTransaction' policy rule that can accept or reject specific operations based on a set of criteria.""" @@ -811,6 +832,30 @@ class SendEndUserEvmTransactionRule(BaseModel): ) +class SendEndUserEvmAssetRule(BaseModel): + """Type representing a 'sendEndUserEvmAsset' policy rule that can accept or reject specific operations based on a set of criteria.""" + + action: Action = Field( + ..., + description="Determines whether matching the rule will cause a request to be rejected or accepted. 'accept' will allow the asset transfer, 'reject' will block it.", + ) + operation: Literal["sendEndUserEvmAsset"] = Field( + "sendEndUserEvmAsset", + description="The operation to which this rule applies. Must be 'sendEndUserEvmAsset'.", + ) + criteria: list[ + EthValueCriterion + | EvmAddressCriterion + | EvmNetworkCriterion + | EvmDataCriterion + | NetUSDChangeCriterion + | RateLimitingCriterion + ] = Field( + ..., + description="The set of criteria that must be matched for this rule to apply. Must be compatible with the specified operation type.", + ) + + class SignEndUserEvmMessageRule(BaseModel): """Type representing a 'signEndUserEvmMessage' policy rule that can accept or reject specific operations based on a set of criteria.""" @@ -898,6 +943,33 @@ class SendEndUserSolTransactionRule(BaseModel): ) +class SendEndUserSolAssetRule(BaseModel): + """Type representing a 'sendEndUserSolAsset' policy rule that can accept or reject specific operations based on a set of criteria.""" + + action: Action = Field( + ..., + description="Determines whether matching the rule will cause a request to be rejected or accepted. 'accept' will allow the asset transfer, 'reject' will block it.", + ) + operation: Literal["sendEndUserSolAsset"] = Field( + "sendEndUserSolAsset", + description="The operation to which this rule applies. Must be 'sendEndUserSolAsset'.", + ) + criteria: list[ + SolAddressCriterion + | SolValueCriterion + | SplAddressCriterion + | SplValueCriterion + | MintAddressCriterion + | SolDataCriterion + | ProgramIdCriterion + | SolNetworkCriterion + | RateLimitingCriterion + ] = Field( + ..., + description="The set of criteria that must be matched for this rule to apply. Must be compatible with the specified operation type.", + ) + + class SignEndUserSolMessageRule(BaseModel): """Type representing a 'signEndUserSolMessage' policy rule that can accept or reject specific operations based on a set of criteria.""" @@ -976,10 +1048,12 @@ class SendUserOperationRule(BaseModel): | SendUserOperationRule | SignEndUserEvmTransactionRule | SendEndUserEvmTransactionRule + | SendEndUserEvmAssetRule | SignEndUserEvmMessageRule | SignEndUserEvmTypedDataRule | SignEndUserSolTransactionRule | SendEndUserSolTransactionRule + | SendEndUserSolAssetRule | SignEndUserSolMessageRule ) diff --git a/python/cdp/test/test_policies_client.py b/python/cdp/test/test_policies_client.py index 70c35f93d..92877fd1e 100644 --- a/python/cdp/test/test_policies_client.py +++ b/python/cdp/test/test_policies_client.py @@ -10,15 +10,20 @@ from cdp.openapi_client.models.list_policies200_response import ListPolicies200Response from cdp.openapi_client.models.update_policy_request import UpdatePolicyRequest from cdp.policies.request_transformer import map_request_rules_to_openapi_format +from cdp.policies.response_transformer import map_openapi_rules_to_response_format from cdp.policies.types import ( CreatePolicyOptions, + EthValueCriterion, EvmAddressCriterion, EvmNetworkCriterion, MintAddressCriterion, NetUSDChangeCriterion, PrepareUserOperationRule, ProgramIdCriterion, + RateLimitingCriterion, + SendEndUserEvmAssetRule, SendEndUserEvmTransactionRule, + SendEndUserSolAssetRule, SendEndUserSolTransactionRule, SendEvmTransactionRule, SendSolanaTransactionRule, @@ -1331,3 +1336,377 @@ async def test_create_policy_with_multiple_new_criteria( assert result.rules == policy_model.rules assert result.created_at == policy_model.created_at assert result.updated_at == policy_model.updated_at + + +# ---- SendEndUserEvmAsset / SendEndUserSolAsset rule tests ---- + + +@pytest.mark.asyncio +async def test_create_policy_with_send_end_user_evm_asset_rule( + openapi_policy_model_factory, policy_model_factory +): + """Test the creation of a policy with a SendEndUserEvmAssetRule and ethValue criterion.""" + openapi_policy_model = openapi_policy_model_factory() + mock_policies_api = AsyncMock() + mock_api_clients = AsyncMock() + mock_api_clients.policies = mock_policies_api + mock_policies_api.create_policy = AsyncMock(return_value=openapi_policy_model) + + policy_model = policy_model_factory() + client = PoliciesClient(api_clients=mock_api_clients) + + create_options = CreatePolicyOptions( + scope="account", + description="EndUser EVM Asset Policy with ethValue", + rules=[ + SendEndUserEvmAssetRule( + action="accept", + operation="sendEndUserEvmAsset", + criteria=[ + EthValueCriterion( + type="ethValue", + ethValue="1000000000000000000", + operator="<=", + ), + ], + ) + ], + ) + + result = await client.create_policy(create_options) + + mock_policies_api.create_policy.assert_called_once_with( + create_policy_request=CreatePolicyRequest( + scope=create_options.scope, + description=create_options.description, + rules=map_request_rules_to_openapi_format(create_options.rules), + ), + x_idempotency_key=None, + ) + assert result.id is not None + assert result.scope == policy_model.scope + assert result.description == policy_model.description + assert result.rules == policy_model.rules + assert result.created_at == policy_model.created_at + assert result.updated_at == policy_model.updated_at + + +@pytest.mark.asyncio +async def test_create_policy_with_send_end_user_evm_asset_rate_limiting( + openapi_policy_model_factory, policy_model_factory +): + """Test the creation of a policy with a SendEndUserEvmAssetRule and rateLimiting criterion.""" + openapi_policy_model = openapi_policy_model_factory() + mock_policies_api = AsyncMock() + mock_api_clients = AsyncMock() + mock_api_clients.policies = mock_policies_api + mock_policies_api.create_policy = AsyncMock(return_value=openapi_policy_model) + + policy_model = policy_model_factory() + client = PoliciesClient(api_clients=mock_api_clients) + + create_options = CreatePolicyOptions( + scope="account", + description="EndUser EVM Asset Policy with rateLimiting", + rules=[ + SendEndUserEvmAssetRule( + action="accept", + operation="sendEndUserEvmAsset", + criteria=[ + RateLimitingCriterion( + type="rateLimiting", + window="1h", + maxCount=10, + maxValueCents=50000, + ), + ], + ) + ], + ) + + result = await client.create_policy(create_options) + + mock_policies_api.create_policy.assert_called_once_with( + create_policy_request=CreatePolicyRequest( + scope=create_options.scope, + description=create_options.description, + rules=map_request_rules_to_openapi_format(create_options.rules), + ), + x_idempotency_key=None, + ) + assert result.id is not None + assert result.scope == policy_model.scope + assert result.description == policy_model.description + assert result.rules == policy_model.rules + assert result.created_at == policy_model.created_at + assert result.updated_at == policy_model.updated_at + + +@pytest.mark.asyncio +async def test_create_policy_with_send_end_user_sol_asset_rule( + openapi_policy_model_factory, policy_model_factory +): + """Test the creation of a policy with a SendEndUserSolAssetRule and solAddress criterion.""" + openapi_policy_model = openapi_policy_model_factory() + mock_policies_api = AsyncMock() + mock_api_clients = AsyncMock() + mock_api_clients.policies = mock_policies_api + mock_policies_api.create_policy = AsyncMock(return_value=openapi_policy_model) + + policy_model = policy_model_factory() + client = PoliciesClient(api_clients=mock_api_clients) + + create_options = CreatePolicyOptions( + scope="account", + description="EndUser SOL Asset Policy with solAddress", + rules=[ + SendEndUserSolAssetRule( + action="accept", + operation="sendEndUserSolAsset", + criteria=[ + SolAddressCriterion( + type="solAddress", + addresses=["So11111111111111111111111111111111111111112"], + operator="in", + ), + ], + ) + ], + ) + + result = await client.create_policy(create_options) + + mock_policies_api.create_policy.assert_called_once_with( + create_policy_request=CreatePolicyRequest( + scope=create_options.scope, + description=create_options.description, + rules=map_request_rules_to_openapi_format(create_options.rules), + ), + x_idempotency_key=None, + ) + assert result.id is not None + assert result.scope == policy_model.scope + assert result.description == policy_model.description + assert result.rules == policy_model.rules + assert result.created_at == policy_model.created_at + assert result.updated_at == policy_model.updated_at + + +@pytest.mark.asyncio +async def test_create_policy_with_send_end_user_sol_asset_rate_limiting( + openapi_policy_model_factory, policy_model_factory +): + """Test the creation of a policy with a SendEndUserSolAssetRule and rateLimiting criterion.""" + openapi_policy_model = openapi_policy_model_factory() + mock_policies_api = AsyncMock() + mock_api_clients = AsyncMock() + mock_api_clients.policies = mock_policies_api + mock_policies_api.create_policy = AsyncMock(return_value=openapi_policy_model) + + policy_model = policy_model_factory() + client = PoliciesClient(api_clients=mock_api_clients) + + create_options = CreatePolicyOptions( + scope="account", + description="EndUser SOL Asset Policy with rateLimiting", + rules=[ + SendEndUserSolAssetRule( + action="accept", + operation="sendEndUserSolAsset", + criteria=[ + RateLimitingCriterion( + type="rateLimiting", + window="24h", + maxCount=100, + maxValueCents=100000, + ), + ], + ) + ], + ) + + result = await client.create_policy(create_options) + + mock_policies_api.create_policy.assert_called_once_with( + create_policy_request=CreatePolicyRequest( + scope=create_options.scope, + description=create_options.description, + rules=map_request_rules_to_openapi_format(create_options.rules), + ), + x_idempotency_key=None, + ) + assert result.id is not None + assert result.scope == policy_model.scope + assert result.description == policy_model.description + assert result.rules == policy_model.rules + assert result.created_at == policy_model.created_at + assert result.updated_at == policy_model.updated_at + + +# ---- Transformer round-trip tests ---- + + +def test_request_transformer_round_trip_evm_asset(): + """Verify request transformer correctly converts SendEndUserEvmAssetRule with rateLimiting.""" + rules = [ + SendEndUserEvmAssetRule( + action="accept", + operation="sendEndUserEvmAsset", + criteria=[ + EthValueCriterion( + type="ethValue", + ethValue="500000000000000000", + operator="<=", + ), + RateLimitingCriterion( + type="rateLimiting", + window="1h", + maxCount=5, + maxValueCents=10000, + ), + ], + ) + ] + openapi_rules = map_request_rules_to_openapi_format(rules) + assert len(openapi_rules) == 1 + rule = openapi_rules[0].actual_instance + assert rule.operation == "sendEndUserEvmAsset" + assert rule.action == "accept" + assert len(rule.criteria) == 2 + + +def test_request_transformer_round_trip_sol_asset(): + """Verify request transformer correctly converts SendEndUserSolAssetRule with rateLimiting.""" + rules = [ + SendEndUserSolAssetRule( + action="reject", + operation="sendEndUserSolAsset", + criteria=[ + SolAddressCriterion( + type="solAddress", + addresses=["So11111111111111111111111111111111111111112"], + operator="not in", + ), + RateLimitingCriterion( + type="rateLimiting", + window="24h", + maxCount=50, + maxValueCents=500000, + ), + ], + ) + ] + openapi_rules = map_request_rules_to_openapi_format(rules) + assert len(openapi_rules) == 1 + rule = openapi_rules[0].actual_instance + assert rule.operation == "sendEndUserSolAsset" + assert rule.action == "reject" + assert len(rule.criteria) == 2 + + +def test_response_transformer_round_trip_evm_asset(): + """Verify response transformer correctly converts OpenAPI SendEndUserEvmAsset rules.""" + from cdp.openapi_client.models.eth_value_criterion import ( + EthValueCriterion as OpenAPIEthValueCriterion, + ) + from cdp.openapi_client.models.rate_limiting_criterion import ( + RateLimitingCriterion as OpenAPIRateLimitingCriterion, + ) + from cdp.openapi_client.models.rule import Rule + from cdp.openapi_client.models.send_end_user_evm_asset_criteria_inner import ( + SendEndUserEvmAssetCriteriaInner, + ) + from cdp.openapi_client.models.send_end_user_evm_asset_rule import ( + SendEndUserEvmAssetRule as OpenAPISendEndUserEvmAssetRule, + ) + + openapi_rules = [ + Rule( + actual_instance=OpenAPISendEndUserEvmAssetRule( + action="accept", + operation="sendEndUserEvmAsset", + criteria=[ + SendEndUserEvmAssetCriteriaInner( + actual_instance=OpenAPIEthValueCriterion( + type="ethValue", + eth_value="1000000000000000000", + operator="<=", + ) + ), + SendEndUserEvmAssetCriteriaInner( + actual_instance=OpenAPIRateLimitingCriterion( + type="rateLimiting", + window="1h", + max_count=10, + max_value_cents=50000, + ) + ), + ], + ) + ) + ] + result = map_openapi_rules_to_response_format(openapi_rules) + assert len(result) == 1 + rule = result[0] + assert isinstance(rule, SendEndUserEvmAssetRule) + assert rule.operation == "sendEndUserEvmAsset" + assert len(rule.criteria) == 2 + assert isinstance(rule.criteria[0], EthValueCriterion) + assert isinstance(rule.criteria[1], RateLimitingCriterion) + assert rule.criteria[1].window == "1h" + assert rule.criteria[1].maxCount == 10 + assert rule.criteria[1].maxValueCents == 50000 + + +def test_response_transformer_round_trip_sol_asset(): + """Verify response transformer correctly converts OpenAPI SendEndUserSolAsset rules.""" + from cdp.openapi_client.models.rate_limiting_criterion import ( + RateLimitingCriterion as OpenAPIRateLimitingCriterion, + ) + from cdp.openapi_client.models.rule import Rule + from cdp.openapi_client.models.send_end_user_sol_asset_criteria_inner import ( + SendEndUserSolAssetCriteriaInner, + ) + from cdp.openapi_client.models.send_end_user_sol_asset_rule import ( + SendEndUserSolAssetRule as OpenAPISendEndUserSolAssetRule, + ) + from cdp.openapi_client.models.sol_address_criterion import ( + SolAddressCriterion as OpenAPISolAddressCriterion, + ) + + openapi_rules = [ + Rule( + actual_instance=OpenAPISendEndUserSolAssetRule( + action="accept", + operation="sendEndUserSolAsset", + criteria=[ + SendEndUserSolAssetCriteriaInner( + actual_instance=OpenAPISolAddressCriterion( + type="solAddress", + addresses=["So11111111111111111111111111111111111111112"], + operator="in", + ) + ), + SendEndUserSolAssetCriteriaInner( + actual_instance=OpenAPIRateLimitingCriterion( + type="rateLimiting", + window="24h", + max_count=100, + max_value_cents=100000, + ) + ), + ], + ) + ) + ] + result = map_openapi_rules_to_response_format(openapi_rules) + assert len(result) == 1 + rule = result[0] + assert isinstance(rule, SendEndUserSolAssetRule) + assert rule.operation == "sendEndUserSolAsset" + assert len(rule.criteria) == 2 + assert isinstance(rule.criteria[0], SolAddressCriterion) + assert isinstance(rule.criteria[1], RateLimitingCriterion) + assert rule.criteria[1].window == "24h" + assert rule.criteria[1].maxCount == 100 + assert rule.criteria[1].maxValueCents == 100000 diff --git a/typescript/src/client/policies/policies.test.ts b/typescript/src/client/policies/policies.test.ts index dde1d8d67..4fa3999a7 100644 --- a/typescript/src/client/policies/policies.test.ts +++ b/typescript/src/client/policies/policies.test.ts @@ -2209,5 +2209,191 @@ describe("PoliciesClient", () => { expect(result).toEqual(mockPolicy); expect(createPolicyMock).toHaveBeenCalledWith(policyWithEvmNetwork, "idem-key"); }); + + it("should create policies with sendEndUserEvmAsset rule and ethValue criterion", async () => { + const createPolicyMock = CdpOpenApiClient.createPolicy as MockedFunction< + typeof CdpOpenApiClient.createPolicy + >; + createPolicyMock.mockResolvedValue(mockPolicy); + + const policyWithEvmAsset = { + scope: "account" as const, + description: "EVM asset transfer policy", + rules: [ + { + action: "reject" as const, + operation: "sendEndUserEvmAsset" as const, + criteria: [ + { + type: "ethValue" as const, + ethValue: "1000000000000000000", + operator: ">" as const, + }, + ], + }, + ], + }; + + const result = await client.createPolicy({ + policy: policyWithEvmAsset, + }); + + expect(result).toEqual(mockPolicy); + expect(createPolicyMock).toHaveBeenCalledWith(policyWithEvmAsset, undefined); + }); + + it("should create policies with sendEndUserEvmAsset rule and rateLimiting criterion", async () => { + const createPolicyMock = CdpOpenApiClient.createPolicy as MockedFunction< + typeof CdpOpenApiClient.createPolicy + >; + createPolicyMock.mockResolvedValue(mockPolicy); + + const policyWithRateLimiting = { + scope: "account" as const, + description: "EVM asset rate limiting policy", + rules: [ + { + action: "reject" as const, + operation: "sendEndUserEvmAsset" as const, + criteria: [ + { + type: "rateLimiting" as const, + window: "4d2h45m", + maxCount: 10, + }, + ], + }, + ], + }; + + const result = await client.createPolicy({ + policy: policyWithRateLimiting, + }); + + expect(result).toEqual(mockPolicy); + expect(createPolicyMock).toHaveBeenCalledWith(policyWithRateLimiting, undefined); + }); + + it("should create policies with sendEndUserSolAsset rule and solAddress criterion", async () => { + const createPolicyMock = CdpOpenApiClient.createPolicy as MockedFunction< + typeof CdpOpenApiClient.createPolicy + >; + createPolicyMock.mockResolvedValue(mockPolicy); + + const policyWithSolAsset = { + scope: "account" as const, + description: "Solana asset transfer policy", + rules: [ + { + action: "accept" as const, + operation: "sendEndUserSolAsset" as const, + criteria: [ + { + type: "solAddress" as const, + addresses: ["9ZNTfG4NyQgxy2SWjSiQoUyBPEvXT2xo7fKc5hPYYJ7b"], + operator: "in" as const, + }, + ], + }, + ], + }; + + const result = await client.createPolicy({ + policy: policyWithSolAsset, + }); + + expect(result).toEqual(mockPolicy); + expect(createPolicyMock).toHaveBeenCalledWith(policyWithSolAsset, undefined); + }); + + it("should create policies with sendEndUserSolAsset rule and rateLimiting criterion", async () => { + const createPolicyMock = CdpOpenApiClient.createPolicy as MockedFunction< + typeof CdpOpenApiClient.createPolicy + >; + createPolicyMock.mockResolvedValue(mockPolicy); + + const policyWithSolRateLimiting = { + scope: "account" as const, + description: "Solana asset rate limiting policy", + rules: [ + { + action: "reject" as const, + operation: "sendEndUserSolAsset" as const, + criteria: [ + { + type: "rateLimiting" as const, + window: "1d", + maxValueCents: 100000, + }, + ], + }, + ], + }; + + const result = await client.createPolicy({ + policy: policyWithSolRateLimiting, + }); + + expect(result).toEqual(mockPolicy); + expect(createPolicyMock).toHaveBeenCalledWith(policyWithSolRateLimiting, undefined); + }); + + it("should reject sendEndUserEvmAsset with invalid criteria", async () => { + const createPolicyMock = CdpOpenApiClient.createPolicy as MockedFunction< + typeof CdpOpenApiClient.createPolicy + >; + + await expect( + client.createPolicy({ + policy: { + scope: "account" as const, + rules: [ + { + action: "reject" as const, + operation: "sendEndUserEvmAsset" as const, + criteria: [ + { + // @ts-expect-error Intentionally using invalid criterion for test + type: "solAddress", + addresses: ["9ZNTfG4NyQgxy2SWjSiQoUyBPEvXT2xo7fKc5hPYYJ7b"], + operator: "in", + }, + ], + }, + ], + }, + }), + ).rejects.toThrow(ZodError); + expect(createPolicyMock).not.toHaveBeenCalled(); + }); + + it("should reject sendEndUserSolAsset with invalid criteria", async () => { + const createPolicyMock = CdpOpenApiClient.createPolicy as MockedFunction< + typeof CdpOpenApiClient.createPolicy + >; + + await expect( + client.createPolicy({ + policy: { + scope: "account" as const, + rules: [ + { + action: "reject" as const, + operation: "sendEndUserSolAsset" as const, + criteria: [ + { + // @ts-expect-error Intentionally using invalid criterion for test + type: "ethValue", + ethValue: "1000", + operator: ">", + }, + ], + }, + ], + }, + }), + ).rejects.toThrow(ZodError); + expect(createPolicyMock).not.toHaveBeenCalled(); + }); }); }); diff --git a/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts b/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts index 43152cca4..2c0955a67 100644 --- a/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts +++ b/typescript/src/openapi-client/generated/coinbaseDeveloperPlatformAPIs.schemas.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -2497,6 +2497,75 @@ export interface SendEndUserEvmTransactionRule { criteria: SendEndUserEvmTransactionCriteria; } +/** + * The type of criterion to use. This should be `rateLimiting`. + */ +export type RateLimitingCriterionType = + (typeof RateLimitingCriterionType)[keyof typeof RateLimitingCriterionType]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const RateLimitingCriterionType = { + rateLimiting: "rateLimiting", +} as const; + +/** + * A criterion that limits the number or value of operations within a time window. When the limit is exceeded, subsequent operations matching this criterion will be rejected until the window resets. + */ +export interface RateLimitingCriterion { + /** The type of criterion to use. This should be `rateLimiting`. */ + type: RateLimitingCriterionType; + /** The time window for the rate limit. Operations are counted within this rolling window. */ + window: string; + /** The maximum number of operations allowed within the window. When the count is exceeded, subsequent operations will be rejected. Mutually exclusive with `maxValueCents`. */ + maxCount?: number; + /** The maximum cumulative USD value in cents of operations allowed within the window. When the value is exceeded, subsequent operations will be rejected. Mutually exclusive with `maxCount`. */ + maxValueCents?: number; +} + +export type SendEndUserEvmAssetCriteriaItem = + | EthValueCriterion + | EvmAddressCriterion + | EvmNetworkCriterion + | EvmDataCriterion + | NetUSDChangeCriterion + | RateLimitingCriterion; + +/** + * A schema for specifying criteria for the sendEndUserEvmAsset operation. + */ +export type SendEndUserEvmAssetCriteria = SendEndUserEvmAssetCriteriaItem[]; + +/** + * Whether matching the rule will cause the request to be rejected or accepted. + */ +export type SendEndUserEvmAssetRuleAction = + (typeof SendEndUserEvmAssetRuleAction)[keyof typeof SendEndUserEvmAssetRuleAction]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SendEndUserEvmAssetRuleAction = { + reject: "reject", + accept: "accept", +} as const; + +/** + * The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. + */ +export type SendEndUserEvmAssetRuleOperation = + (typeof SendEndUserEvmAssetRuleOperation)[keyof typeof SendEndUserEvmAssetRuleOperation]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SendEndUserEvmAssetRuleOperation = { + sendEndUserEvmAsset: "sendEndUserEvmAsset", +} as const; + +export interface SendEndUserEvmAssetRule { + /** Whether matching the rule will cause the request to be rejected or accepted. */ + action: SendEndUserEvmAssetRuleAction; + /** The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. */ + operation: SendEndUserEvmAssetRuleOperation; + criteria: SendEndUserEvmAssetCriteria; +} + /** * A schema for specifying criteria for the signEndUserEvmMessage operation. */ @@ -2664,6 +2733,53 @@ export interface SendEndUserSolTransactionRule { criteria: SendEndUserSolTransactionCriteria; } +export type SendEndUserSolAssetCriteriaItem = + | SolAddressCriterion + | SolValueCriterion + | SplAddressCriterion + | SplValueCriterion + | MintAddressCriterion + | SolDataCriterion + | ProgramIdCriterion + | SolNetworkCriterion + | RateLimitingCriterion; + +/** + * A schema for specifying criteria for the sendEndUserSolAsset operation. + */ +export type SendEndUserSolAssetCriteria = SendEndUserSolAssetCriteriaItem[]; + +/** + * Whether matching the rule will cause the request to be rejected or accepted. + */ +export type SendEndUserSolAssetRuleAction = + (typeof SendEndUserSolAssetRuleAction)[keyof typeof SendEndUserSolAssetRuleAction]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SendEndUserSolAssetRuleAction = { + reject: "reject", + accept: "accept", +} as const; + +/** + * The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. + */ +export type SendEndUserSolAssetRuleOperation = + (typeof SendEndUserSolAssetRuleOperation)[keyof typeof SendEndUserSolAssetRuleOperation]; + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SendEndUserSolAssetRuleOperation = { + sendEndUserSolAsset: "sendEndUserSolAsset", +} as const; + +export interface SendEndUserSolAssetRule { + /** Whether matching the rule will cause the request to be rejected or accepted. */ + action: SendEndUserSolAssetRuleAction; + /** The operation to which the rule applies. Every element of the `criteria` array must match the specified operation. */ + operation: SendEndUserSolAssetRuleOperation; + criteria: SendEndUserSolAssetCriteria; +} + /** * A schema for specifying criteria for the signEndUserSolMessage operation. */ @@ -2720,7 +2836,9 @@ export type Rule = | SignEndUserEvmTypedDataRule | SignEndUserSolTransactionRule | SendEndUserSolTransactionRule - | SignEndUserSolMessageRule; + | SignEndUserSolMessageRule + | SendEndUserEvmAssetRule + | SendEndUserSolAssetRule; /** * The scope of the policy. Only one project-level policy can exist at any time. @@ -4130,6 +4248,8 @@ If `userId` is not provided in the request, the server will generate a random UU export type ListEndUsersParams = { /** * The number of end users to return per page. + * @minimum 1 + * @maximum 100 */ pageSize?: number; /** @@ -4825,6 +4945,8 @@ export type ListDataTokenBalances200 = ListDataTokenBalances200AllOf & ListRespo export type ListWebhookSubscriptionsParams = { /** * The number of subscriptions to return per page. + * @minimum 1 + * @maximum 100 */ pageSize?: number; /** diff --git a/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts b/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts index 55007c8b5..18182c99d 100644 --- a/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts +++ b/typescript/src/openapi-client/generated/end-user-accounts/end-user-accounts.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -31,7 +31,7 @@ This API is intended to be used by the developer's own backend, and is authentic */ export const createEndUser = ( createEndUserBody: CreateEndUserBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -50,7 +50,7 @@ By default, the response is sorted by creation date in ascending order and pagin */ export const listEndUsers = ( params?: ListEndUsersParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient({ url: `/v2/end-users`, method: "GET", params }, options); }; @@ -62,7 +62,7 @@ This API is intended to be used by the developer's own backend, and is authentic */ export const validateEndUserAccessToken = ( validateEndUserAccessTokenBody: ValidateEndUserAccessTokenBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -80,7 +80,10 @@ export const validateEndUserAccessToken = ( This API is intended to be used by the developer's own backend, and is authenticated using the developer's CDP API key. * @summary Get an end user */ -export const getEndUser = (userId: string, options?: SecondParameter) => { +export const getEndUser = ( + userId: string, + options?: SecondParameter>, +) => { return cdpApiClient({ url: `/v2/end-users/${userId}`, method: "GET" }, options); }; /** @@ -91,7 +94,7 @@ This API is intended to be used by the developer's own backend, and is authentic export const addEndUserEvmAccount = ( userId: string, addEndUserEvmAccountBody?: AddEndUserEvmAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -111,7 +114,7 @@ This API is intended to be used by the developer's own backend, and is authentic export const addEndUserEvmSmartAccount = ( userId: string, addEndUserEvmSmartAccountBody?: AddEndUserEvmSmartAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -131,7 +134,7 @@ This API is intended to be used by the developer's own backend, and is authentic export const addEndUserSolanaAccount = ( userId: string, addEndUserSolanaAccountBody?: AddEndUserSolanaAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -151,7 +154,7 @@ This endpoint allows developers to import existing keys for their end users, sup */ export const importEndUser = ( importEndUserBody: ImportEndUserBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts b/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts index 37ab8d8ed..c55af269a 100644 --- a/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts +++ b/typescript/src/openapi-client/generated/evm-accounts/evm-accounts.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -42,7 +42,7 @@ The response is paginated, and by default, returns 20 accounts per page. */ export const listEvmAccounts = ( params?: ListEvmAccountsParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/accounts`, method: "GET", params }, @@ -55,7 +55,7 @@ export const listEvmAccounts = ( */ export const createEvmAccount = ( createEvmAccountBody?: CreateEvmAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -71,7 +71,10 @@ export const createEvmAccount = ( * Gets an EVM account by its address. * @summary Get an EVM account by address */ -export const getEvmAccount = (address: string, options?: SecondParameter) => { +export const getEvmAccount = ( + address: string, + options?: SecondParameter>, +) => { return cdpApiClient({ url: `/v2/evm/accounts/${address}`, method: "GET" }, options); }; /** @@ -81,7 +84,7 @@ export const getEvmAccount = (address: string, options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -99,7 +102,7 @@ export const updateEvmAccount = ( */ export const getEvmAccountByName = ( name: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/accounts/by-name/${name}`, method: "GET" }, @@ -138,7 +141,7 @@ The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com export const sendEvmTransaction = ( address: string, sendEvmTransactionBody: SendEvmTransactionBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -160,7 +163,7 @@ The transaction must be an [EIP-1559 dynamic fee transaction](https://github.com export const signEvmTransaction = ( address: string, signEvmTransactionBody: SignEvmTransactionBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -179,7 +182,7 @@ export const signEvmTransaction = ( export const signEvmHash = ( address: string, signEvmHashBody: SignEvmHashBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -200,7 +203,7 @@ Per the specification, the message in the request body is prepended with `0x19 < export const signEvmMessage = ( address: string, signEvmMessageBody: SignEvmMessageBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -219,7 +222,7 @@ export const signEvmMessage = ( export const signEvmTypedData = ( address: string, eIP712Message: EIP712Message, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -246,7 +249,7 @@ The delegation allows the EVM EOA to be used as a smart account, which enables b export const createEvmEip7702Delegation = ( address: string, createEvmEip7702DelegationBody: CreateEvmEip7702DelegationBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -264,7 +267,7 @@ export const createEvmEip7702Delegation = ( */ export const getEvmEip7702DelegationOperationById = ( delegationOperationId: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/eip7702/delegation-operations/${delegationOperationId}`, method: "GET" }, @@ -277,7 +280,7 @@ export const getEvmEip7702DelegationOperationById = ( */ export const importEvmAccount = ( importEvmAccountBody: ImportEvmAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -296,7 +299,7 @@ export const importEvmAccount = ( export const exportEvmAccount = ( address: string, exportEvmAccountBody: ExportEvmAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -315,7 +318,7 @@ export const exportEvmAccount = ( export const exportEvmAccountByName = ( name: string, exportEvmAccountByNameBody: ExportEvmAccountByNameBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts b/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts index 50659fd4f..7e453b344 100644 --- a/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts +++ b/typescript/src/openapi-client/generated/evm-smart-accounts/evm-smart-accounts.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -32,7 +32,7 @@ The response is paginated, and by default, returns 20 accounts per page. */ export const listEvmSmartAccounts = ( params?: ListEvmSmartAccountsParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/smart-accounts`, method: "GET", params }, @@ -45,7 +45,7 @@ export const listEvmSmartAccounts = ( */ export const createEvmSmartAccount = ( createEvmSmartAccountBody: CreateEvmSmartAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -63,7 +63,7 @@ export const createEvmSmartAccount = ( */ export const getEvmSmartAccountByName = ( name: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/smart-accounts/by-name/${name}`, method: "GET" }, @@ -76,7 +76,7 @@ export const getEvmSmartAccountByName = ( */ export const getEvmSmartAccount = ( address: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/smart-accounts/${address}`, method: "GET" }, @@ -90,7 +90,7 @@ export const getEvmSmartAccount = ( export const updateEvmSmartAccount = ( address: string, updateEvmSmartAccountBody: UpdateEvmSmartAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -109,7 +109,7 @@ export const updateEvmSmartAccount = ( export const prepareUserOperation = ( address: string, prepareUserOperationBody: PrepareUserOperationBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -128,7 +128,7 @@ export const prepareUserOperation = ( export const prepareAndSendUserOperation = ( address: string, prepareAndSendUserOperationBody: PrepareAndSendUserOperationBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -147,7 +147,7 @@ export const prepareAndSendUserOperation = ( export const getUserOperation = ( address: string, userOpHash: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/smart-accounts/${address}/user-operations/${userOpHash}`, method: "GET" }, @@ -165,7 +165,7 @@ export const sendUserOperation = ( address: string, userOpHash: string, sendUserOperationBody: SendUserOperationBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -184,7 +184,7 @@ export const sendUserOperation = ( export const createSpendPermission = ( address: string, createSpendPermissionRequest: CreateSpendPermissionRequest, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -203,7 +203,7 @@ export const createSpendPermission = ( export const listSpendPermissions = ( address: string, params?: ListSpendPermissionsParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/smart-accounts/${address}/spend-permissions/list`, method: "GET", params }, @@ -217,7 +217,7 @@ export const listSpendPermissions = ( export const revokeSpendPermission = ( address: string, revokeSpendPermissionRequest: RevokeSpendPermissionRequest, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts b/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts index 6fdbd22de..0befa1b8a 100644 --- a/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts +++ b/typescript/src/openapi-client/generated/evm-swaps/evm-swaps.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -22,7 +22,7 @@ type SecondParameter unknown> = Parameters[1]; */ export const getEvmSwapPrice = ( params: GetEvmSwapPriceParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/swaps/quote`, method: "GET", params }, @@ -35,7 +35,7 @@ export const getEvmSwapPrice = ( */ export const createEvmSwapQuote = ( createEvmSwapQuoteBody: CreateEvmSwapQuoteBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/evm-token-balances/evm-token-balances.ts b/typescript/src/openapi-client/generated/evm-token-balances/evm-token-balances.ts index 236e8c7cb..9e7bf44a1 100644 --- a/typescript/src/openapi-client/generated/evm-token-balances/evm-token-balances.ts +++ b/typescript/src/openapi-client/generated/evm-token-balances/evm-token-balances.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -24,7 +24,7 @@ export const listEvmTokenBalances = ( network: ListEvmTokenBalancesNetwork, address: string, params?: ListEvmTokenBalancesParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/evm/token-balances/${network}/${address}`, method: "GET", params }, diff --git a/typescript/src/openapi-client/generated/faucets/faucets.ts b/typescript/src/openapi-client/generated/faucets/faucets.ts index 1c8f27321..530774aba 100644 --- a/typescript/src/openapi-client/generated/faucets/faucets.ts +++ b/typescript/src/openapi-client/generated/faucets/faucets.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -36,7 +36,7 @@ A single blockchain address cannot exceed the specified limits, even if multiple */ export const requestEvmFaucet = ( requestEvmFaucetBody: RequestEvmFaucetBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -66,7 +66,7 @@ A single blockchain address cannot exceed the specified limits, even if multiple */ export const requestSolanaFaucet = ( requestSolanaFaucetBody: RequestSolanaFaucetBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/onchain-data/onchain-data.ts b/typescript/src/openapi-client/generated/onchain-data/onchain-data.ts index f76acec24..4199ea1a4 100644 --- a/typescript/src/openapi-client/generated/onchain-data/onchain-data.ts +++ b/typescript/src/openapi-client/generated/onchain-data/onchain-data.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -25,7 +25,7 @@ Analyzes transaction history to discover token interactions. export const listTokensForAccount = ( network: "base" | "base-sepolia", address: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/data/evm/token-ownership/${network}/${address}`, method: "GET" }, @@ -42,7 +42,7 @@ export const listDataTokenBalances = ( network: ListEvmTokenBalancesNetwork, address: string, params?: ListDataTokenBalancesParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/data/evm/token-balances/${network}/${address}`, method: "GET", params }, diff --git a/typescript/src/openapi-client/generated/onramp/onramp.ts b/typescript/src/openapi-client/generated/onramp/onramp.ts index ebc6cbffd..fba5a80de 100644 --- a/typescript/src/openapi-client/generated/onramp/onramp.ts +++ b/typescript/src/openapi-client/generated/onramp/onramp.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -29,7 +29,7 @@ For detailed integration instructions and to get access to this API, refer to th */ export const createOnrampOrder = ( createOnrampOrderBody: CreateOnrampOrderBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -47,7 +47,7 @@ export const createOnrampOrder = ( */ export const getOnrampOrderById = ( orderId: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/onramp/orders/${orderId}`, method: "GET" }, @@ -77,7 +77,7 @@ export const getOnrampOrderById = ( */ export const createOnrampSession = ( createOnrampSessionBody: CreateOnrampSessionBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -96,7 +96,7 @@ Currently supports `GUEST_CHECKOUT_APPLE_PAY` payment method with phone number i */ export const getOnrampUserLimits = ( getOnrampUserLimitsBody: GetOnrampUserLimitsBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts b/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts index 0fbff1cfe..220041ddb 100644 --- a/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts +++ b/typescript/src/openapi-client/generated/policy-engine/policy-engine.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -24,7 +24,7 @@ The response is paginated, and by default, returns 20 policies per page. */ export const listPolicies = ( params?: ListPoliciesParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/policy-engine/policies`, method: "GET", params }, @@ -37,7 +37,7 @@ export const listPolicies = ( */ export const createPolicy = ( createPolicyBody: CreatePolicyBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -53,7 +53,10 @@ export const createPolicy = ( * Get a policy by its ID. * @summary Get a policy by ID */ -export const getPolicyById = (policyId: string, options?: SecondParameter) => { +export const getPolicyById = ( + policyId: string, + options?: SecondParameter>, +) => { return cdpApiClient( { url: `/v2/policy-engine/policies/${policyId}`, method: "GET" }, options, @@ -63,7 +66,10 @@ export const getPolicyById = (policyId: string, options?: SecondParameter) => { +export const deletePolicy = ( + policyId: string, + options?: SecondParameter>, +) => { return cdpApiClient( { url: `/v2/policy-engine/policies/${policyId}`, method: "DELETE" }, options, @@ -76,7 +82,7 @@ export const deletePolicy = (policyId: string, options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts b/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts index 03f88e648..efdb5cadc 100644 --- a/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts +++ b/typescript/src/openapi-client/generated/solana-accounts/solana-accounts.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -37,7 +37,7 @@ If a name is provided, the response will contain only the account with that name */ export const listSolanaAccounts = ( params?: ListSolanaAccountsParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/solana/accounts`, method: "GET", params }, @@ -50,7 +50,7 @@ export const listSolanaAccounts = ( */ export const createSolanaAccount = ( createSolanaAccountBody?: CreateSolanaAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -68,7 +68,7 @@ export const createSolanaAccount = ( */ export const getSolanaAccount = ( address: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/solana/accounts/${address}`, method: "GET" }, @@ -82,7 +82,7 @@ export const getSolanaAccount = ( export const updateSolanaAccount = ( address: string, updateSolanaAccountBody: UpdateSolanaAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -100,7 +100,7 @@ export const updateSolanaAccount = ( */ export const getSolanaAccountByName = ( name: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/solana/accounts/by-name/${name}`, method: "GET" }, @@ -113,7 +113,7 @@ export const getSolanaAccountByName = ( */ export const importSolanaAccount = ( importSolanaAccountBody: ImportSolanaAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -132,7 +132,7 @@ export const importSolanaAccount = ( export const exportSolanaAccount = ( address: string, exportSolanaAccountBody: ExportSolanaAccountBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -151,7 +151,7 @@ export const exportSolanaAccount = ( export const exportSolanaAccountByName = ( name: string, exportSolanaAccountByNameBody: ExportSolanaAccountByNameBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -179,7 +179,7 @@ The developer is responsible for ensuring that the unsigned transaction is valid export const signSolanaTransaction = ( address: string, signSolanaTransactionBody: SignSolanaTransactionBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -200,7 +200,7 @@ export const signSolanaTransaction = ( export const signSolanaMessage = ( address: string, signSolanaMessageBody: SignSolanaMessageBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -238,7 +238,7 @@ The developer is responsible for ensuring that the unsigned transaction is valid */ export const sendSolanaTransaction = ( sendSolanaTransactionBody: SendSolanaTransactionBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { diff --git a/typescript/src/openapi-client/generated/solana-token-balances/solana-token-balances.ts b/typescript/src/openapi-client/generated/solana-token-balances/solana-token-balances.ts index 982779fdc..ef62955fe 100644 --- a/typescript/src/openapi-client/generated/solana-token-balances/solana-token-balances.ts +++ b/typescript/src/openapi-client/generated/solana-token-balances/solana-token-balances.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -25,7 +25,7 @@ export const listSolanaTokenBalances = ( network: ListSolanaTokenBalancesNetwork, address: string, params?: ListSolanaTokenBalancesParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/solana/token-balances/${network}/${address}`, method: "GET", params }, diff --git a/typescript/src/openapi-client/generated/sql-api-alpha/sql-api-alpha.ts b/typescript/src/openapi-client/generated/sql-api-alpha/sql-api-alpha.ts index a724ccf90..c1667b0df 100644 --- a/typescript/src/openapi-client/generated/sql-api-alpha/sql-api-alpha.ts +++ b/typescript/src/openapi-client/generated/sql-api-alpha/sql-api-alpha.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -44,7 +44,7 @@ Queries are executed against optimized data structures for high-performance anal */ export const runSQLQuery = ( onchainDataQuery: OnchainDataQuery, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -65,7 +65,7 @@ This endpoint returns the ANTLR4 grammar that is used to evaluate the SQL querie * @summary Get SQL grammar */ -export const getSQLGrammar = (options?: SecondParameter) => { +export const getSQLGrammar = (options?: SecondParameter>) => { return cdpApiClient({ url: `/v2/data/query/grammar`, method: "GET" }, options); }; export type RunSQLQueryResult = NonNullable>>; diff --git a/typescript/src/openapi-client/generated/webhooks/webhooks.ts b/typescript/src/openapi-client/generated/webhooks/webhooks.ts index f18ee8e5b..8d294326c 100644 --- a/typescript/src/openapi-client/generated/webhooks/webhooks.ts +++ b/typescript/src/openapi-client/generated/webhooks/webhooks.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -31,7 +31,7 @@ in descending order by creation time. */ export const listWebhookSubscriptions = ( params?: ListWebhookSubscriptionsParams, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/data/webhooks/subscriptions`, method: "GET", params }, @@ -94,7 +94,7 @@ For `onchain.activity.detected` events, use `labels` for precise filtering with */ export const createWebhookSubscription = ( webhookSubscriptionRequest: WebhookSubscriptionRequest, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -120,7 +120,7 @@ configuration, status, creation timestamp, and webhook signature secret. */ export const getWebhookSubscription = ( subscriptionId: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/data/webhooks/subscriptions/${subscriptionId}`, method: "GET" }, @@ -143,7 +143,7 @@ All required fields must be provided, even if they are not being changed. export const updateWebhookSubscription = ( subscriptionId: string, webhookSubscriptionUpdateRequest: WebhookSubscriptionUpdateRequest, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -168,7 +168,7 @@ This action cannot be undone. */ export const deleteWebhookSubscription = ( subscriptionId: string, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { url: `/v2/data/webhooks/subscriptions/${subscriptionId}`, method: "DELETE" }, diff --git a/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts b/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts index 96174ad70..bb6189d8e 100644 --- a/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts +++ b/typescript/src/openapi-client/generated/x402-facilitator/x402-facilitator.ts @@ -1,5 +1,5 @@ /** - * Generated by orval v7.6.0 🍺 + * Generated by orval v7.21.0 🍺 * Do not edit manually. * Coinbase Developer Platform APIs * The Coinbase Developer Platform APIs - leading the world's transition onchain. @@ -23,7 +23,7 @@ type SecondParameter unknown> = Parameters[1]; */ export const verifyX402Payment = ( verifyX402PaymentBody: VerifyX402PaymentBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -41,7 +41,7 @@ export const verifyX402Payment = ( */ export const settleX402Payment = ( settleX402PaymentBody: SettleX402PaymentBody, - options?: SecondParameter, + options?: SecondParameter>, ) => { return cdpApiClient( { @@ -57,7 +57,9 @@ export const settleX402Payment = ( * Get the supported x402 protocol payment schemes and networks that the facilitator is able to verify and settle payments for. * @summary Get supported payment schemes and networks */ -export const supportedX402PaymentKinds = (options?: SecondParameter) => { +export const supportedX402PaymentKinds = ( + options?: SecondParameter>, +) => { return cdpApiClient( { url: `/v2/x402/supported`, method: "GET" }, options, diff --git a/typescript/src/policies/evmSchema.ts b/typescript/src/policies/evmSchema.ts index 61e5e0812..546242196 100644 --- a/typescript/src/policies/evmSchema.ts +++ b/typescript/src/policies/evmSchema.ts @@ -810,6 +810,79 @@ export const SendEndUserEvmTransactionRuleSchema = z.object({ }); export type SendEndUserEvmTransactionRule = z.infer; +/** + * Schema for the RateLimiting criterion type. + * Limits the number or value of operations within a time window. + */ +export const RateLimitingCriterionSchema = z.object({ + /** + * The type of criterion. Must be "rateLimiting". + */ + type: z.literal("rateLimiting"), + /** + * The time window for the rate limit (e.g. "4d2h45m"). + */ + window: z.string(), + /** + * Maximum number of operations allowed within the window. + * Mutually exclusive with maxValueCents. + */ + maxCount: z.number().int().optional(), + /** + * Maximum cumulative USD value in cents within the window. + * Mutually exclusive with maxCount. + */ + maxValueCents: z.number().int().optional(), +}); +/** + * Type representing a RateLimiting criterion. + */ +export type RateLimitingCriterion = z.infer; + +/** + * Schema for criteria used in SendEndUserEvmAsset operations + */ +export const SendEndUserEvmAssetCriteriaSchema = z + .array( + z.discriminatedUnion("type", [ + EthValueCriterionSchema, + EvmAddressCriterionSchema, + PrepareUserOperationEvmNetworkCriterionSchema, + EvmDataCriterionSchema, + NetUSDChangeCriterionSchema, + RateLimitingCriterionSchema, + ]), + ) + .max(10) + .min(1); +/** + * Type representing a set of criteria for the sendEndUserEvmAsset operation. + */ +export type SendEndUserEvmAssetCriteria = z.infer; + +/** + * Type representing a 'sendEndUserEvmAsset' policy rule that can accept or reject specific operations + * based on a set of criteria. + */ +export const SendEndUserEvmAssetRuleSchema = z.object({ + /** + * Determines whether matching the rule will cause a request to be rejected or accepted. + * "accept" will allow the asset transfer, "reject" will block it. + */ + action: ActionEnum, + /** + * The operation to which this rule applies. + * Must be "sendEndUserEvmAsset". + */ + operation: z.literal("sendEndUserEvmAsset"), + /** + * The set of criteria that must be matched for this rule to apply. + * Must be compatible with the specified operation type. + */ + criteria: SendEndUserEvmAssetCriteriaSchema, +}); +export type SendEndUserEvmAssetRule = z.infer; + /** * Type representing a 'signEndUserEvmMessage' policy rule that can accept or reject specific operations * based on a set of criteria. diff --git a/typescript/src/policies/solanaSchema.ts b/typescript/src/policies/solanaSchema.ts index 5cc39935b..478ec592c 100644 --- a/typescript/src/policies/solanaSchema.ts +++ b/typescript/src/policies/solanaSchema.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +import { RateLimitingCriterionSchema } from "./evmSchema.js"; + /** * Enum for Action types */ @@ -578,6 +580,53 @@ export const SendEndUserSolTransactionRuleSchema = z.object({ }); export type SendEndUserSolTransactionRule = z.infer; +/** + * Schema for criteria used in SendEndUserSolAsset operations + */ +export const SendEndUserSolAssetCriteriaSchema = z + .array( + z.discriminatedUnion("type", [ + SolAddressCriterionSchema, + SolValueCriterionSchema, + SplAddressCriterionSchema, + SplValueCriterionSchema, + MintAddressCriterionSchema, + SolDataCriterionSchema, + ProgramIdCriterionSchema, + SolNetworkCriterionSchema, + RateLimitingCriterionSchema, + ]), + ) + .max(10) + .min(1); +/** + * Type representing a set of criteria for the sendEndUserSolAsset operation. + */ +export type SendEndUserSolAssetCriteria = z.infer; + +/** + * Type representing a 'sendEndUserSolAsset' policy rule that can accept or reject specific operations + * based on a set of criteria. + */ +export const SendEndUserSolAssetRuleSchema = z.object({ + /** + * Determines whether matching the rule will cause a request to be rejected or accepted. + * "accept" will allow the asset transfer, "reject" will block it. + */ + action: ActionEnum, + /** + * The operation to which this rule applies. + * Must be "sendEndUserSolAsset". + */ + operation: z.literal("sendEndUserSolAsset"), + /** + * The set of criteria that must be matched for this rule to apply. + * Must be compatible with the specified operation type. + */ + criteria: SendEndUserSolAssetCriteriaSchema, +}); +export type SendEndUserSolAssetRule = z.infer; + /** * Type representing a 'signEndUserSolMessage' policy rule that can accept or reject specific operations * based on a set of criteria. diff --git a/typescript/src/policies/types.ts b/typescript/src/policies/types.ts index 164f14756..d86c25e9c 100644 --- a/typescript/src/policies/types.ts +++ b/typescript/src/policies/types.ts @@ -12,6 +12,7 @@ import { SendEndUserEvmTransactionRuleSchema, SignEndUserEvmMessageRuleSchema, SignEndUserEvmTypedDataRuleSchema, + SendEndUserEvmAssetRuleSchema, } from "./evmSchema.js"; import { SendSolTransactionRuleSchema, @@ -20,6 +21,7 @@ import { SignEndUserSolTransactionRuleSchema, SendEndUserSolTransactionRuleSchema, SignEndUserSolMessageRuleSchema, + SendEndUserSolAssetRuleSchema, } from "./solanaSchema.js"; /** @@ -71,6 +73,8 @@ export const RuleSchema = z.discriminatedUnion("operation", [ SignEndUserSolTransactionRuleSchema, SendEndUserSolTransactionRuleSchema, SignEndUserSolMessageRuleSchema, + SendEndUserEvmAssetRuleSchema, + SendEndUserSolAssetRuleSchema, ]); /**