├── go ├── .go-version ├── client-config.yaml ├── .env.example ├── CHANGELOG.md ├── .cursor │ └── rules │ │ └── go-development.mdc ├── go.mod └── .golangci.yaml ├── python ├── cdp │ ├── auth │ │ ├── test │ │ │ ├── __init__.py │ │ │ └── factories │ │ │ │ ├── __init__.py │ │ │ │ ├── auth_headers_factory.py │ │ │ │ ├── auth_client_options_factory.py │ │ │ │ ├── http_client_factory.py │ │ │ │ └── http_response_factory.py │ │ ├── clients │ │ │ ├── urllib3 │ │ │ │ └── __init__.py │ │ │ └── __init__.py │ │ ├── utils │ │ │ └── __init__.py │ │ └── __init__.py │ ├── .python-version │ ├── openapi_client │ │ ├── test │ │ │ ├── __init__.py │ │ │ ├── test_error_type.py │ │ │ ├── test_x402_version.py │ │ │ ├── test_known_abi_type.py │ │ │ ├── test_known_idl_type.py │ │ │ ├── test_evm_swaps_network.py │ │ │ ├── test_onramp_order_status.py │ │ │ ├── test_abi_state_mutability.py │ │ │ ├── test_o_auth2_provider_type.py │ │ │ ├── test_onramp_payment_link_type.py │ │ │ ├── test_x402_settle_error_reason.py │ │ │ ├── test_spend_permission_network.py │ │ │ ├── test_evm_user_operation_network.py │ │ │ ├── test_x402_verify_invalid_reason.py │ │ │ ├── test_list_evm_token_balances_network.py │ │ │ ├── test_list_solana_token_balances_network.py │ │ │ ├── test_onramp_order_payment_method_type_id.py │ │ │ ├── test_onramp_quote_payment_method_type_id.py │ │ │ ├── test_x402_supported_payment_kind_network.py │ │ │ ├── test_evm_token_balances_api.py │ │ │ ├── test_solana_token_balances_api.py │ │ │ ├── test_sqlapi_alpha_api.py │ │ │ ├── test_evm_swaps_api.py │ │ │ ├── test_faucets_api.py │ │ │ └── test_onchain_data_api.py │ │ ├── constants.py │ │ ├── api_response.py │ │ ├── models │ │ │ ├── x402_version.py │ │ │ ├── o_auth2_provider_type.py │ │ │ ├── onramp_payment_link_type.py │ │ │ ├── evm_swaps_network.py │ │ │ ├── abi_state_mutability.py │ │ │ ├── onramp_order_payment_method_type_id.py │ │ │ ├── list_solana_token_balances_network.py │ │ │ ├── list_evm_token_balances_network.py │ │ │ ├── x402_supported_payment_kind_network.py │ │ │ ├── onramp_quote_payment_method_type_id.py │ │ │ ├── spend_permission_network.py │ │ │ ├── evm_user_operation_network.py │ │ │ └── onramp_order_status.py │ │ └── api │ │ │ └── __init__.py │ ├── __version__.py │ ├── actions │ │ ├── evm │ │ │ ├── transfer │ │ │ │ ├── __init__.py │ │ │ │ ├── utils.py │ │ │ │ └── constants.py │ │ │ ├── spend_permissions │ │ │ │ └── __init__.py │ │ │ └── request_faucet.py │ │ ├── solana │ │ │ ├── constants.py │ │ │ ├── types.py │ │ │ ├── request_faucet.py │ │ │ ├── send_transaction.py │ │ │ ├── sign_message.py │ │ │ └── sign_transaction.py │ │ └── util.py │ ├── test │ │ └── factories │ │ │ ├── local_account_factory.py │ │ │ ├── evm_server_account_factory.py │ │ │ └── solana_token_balances_factory.py │ ├── update_smart_account_types.py │ ├── errors.py │ ├── update_account_types.py │ ├── spend_permissions │ │ └── __init__.py │ ├── constants.py │ └── evm_message_types.py ├── changelog.d │ ├── .gitignore │ └── twin-fans-bowling.bug.md ├── docs │ ├── README.md │ ├── modules.rst │ ├── cdp.auth.clients.rst │ ├── cdp.auth.rst │ ├── cdp.x402.rst │ ├── index.rst │ ├── cdp.auth.clients.urllib3.rst │ ├── Makefile │ ├── cdp.auth.utils.rst │ ├── make.bat │ └── cdp.auth.test.rst ├── client_config.yaml ├── .env.example ├── .cursor │ └── rules │ │ └── python-development.mdc └── templates │ └── __init__package.mustache ├── typescript ├── README.md ├── pnpm-workspace.yaml ├── src │ ├── version.ts │ ├── auth │ │ ├── hooks │ │ │ └── axios │ │ │ │ └── index.ts │ │ ├── utils │ │ │ ├── index.ts │ │ │ └── hash.ts │ │ └── index.ts │ ├── client │ │ ├── solana │ │ │ └── index.ts │ │ ├── policies │ │ │ └── index.ts │ │ └── end-user │ │ │ └── endUser.types.ts │ ├── utils │ │ ├── hash.ts │ │ ├── serializeTransaction.ts │ │ ├── bigint.ts │ │ ├── sortKeys.ts │ │ └── uuidV4.ts │ ├── actions │ │ ├── solana │ │ │ ├── constants.ts │ │ │ ├── rpc.ts │ │ │ └── signMessage.ts │ │ └── evm │ │ │ ├── spend-permissions │ │ │ └── types.ts │ │ │ └── transfer │ │ │ └── utils.ts │ ├── accounts │ │ ├── solana │ │ │ └── types.ts │ │ └── evm │ │ │ ├── networkToChainResolver.ts │ │ │ ├── chainToNetworkMapper.ts │ │ │ └── getBaseNodeRpcUrl.ts │ ├── index.ts │ ├── spend-permissions │ │ ├── utils.test.ts │ │ └── utils.ts │ ├── errors.test.ts │ ├── errors.ts │ ├── LICENSE │ └── constants.ts ├── .eslintignore ├── .prettierignore ├── tsconfig.esm.json ├── .env.example ├── .prettierrc ├── tsconfig.cjs.json ├── tsconfig.types.json ├── .changeset │ ├── config.json │ └── README.md ├── vitest.config.ts ├── vitest.e2e.config.ts ├── scripts │ ├── sort-msw-index.ts │ └── prepublish.ts ├── tsconfig.json ├── orval.config.ts ├── .cursor │ └── rules │ │ └── typescript-development.mdc ├── ts-frontmatter.mjs ├── typedoc.index.json └── patches │ └── @orval__core@7.6.0.patch ├── examples ├── go │ ├── .go-version │ ├── .env.example │ ├── README.md │ └── main.go ├── python │ ├── .python-version │ ├── .env.example │ ├── main.py │ ├── pyproject.toml │ ├── evm │ │ ├── policies │ │ │ ├── list_policies.py │ │ │ ├── delete_policy.py │ │ │ ├── get_policy_by_id.py │ │ │ └── create_usd_spend_restriction_policy.py │ │ ├── accounts │ │ │ ├── create_account.py │ │ │ ├── get_account.py │ │ │ ├── create_account_idempotency.py │ │ │ ├── import_account.py │ │ │ └── get_or_create_account.py │ │ ├── token-balances │ │ │ ├── account.list_token_balances.py │ │ │ └── list_token_balances.py │ │ ├── fund │ │ │ ├── account.fund.py │ │ │ ├── account.request_faucet.py │ │ │ └── account.quote_fund.py │ │ ├── smart-accounts │ │ │ ├── smart_account.fund.py │ │ │ ├── smart_account.request_faucet.py │ │ │ ├── smart_account.quote_fund.py │ │ │ ├── get_or_create_smart_account.py │ │ │ ├── smart_account.wait_for_user_operation.py │ │ │ ├── smart_account.get_user_operation.py │ │ │ ├── smart_account.list_token_balances.py │ │ │ ├── smart_account.send_user_operation.py │ │ │ └── smart_account.quote_fund_and_execute.py │ │ └── transactions │ │ │ └── transfer.py │ ├── solana │ │ ├── accounts │ │ │ ├── create_account.py │ │ │ ├── get_account.py │ │ │ └── get_or_create_account.py │ │ ├── funding │ │ │ └── account.request_faucet.py │ │ ├── transactions │ │ │ └── account.sign_message.py │ │ └── policies │ │ │ └── create_sol_message_policy.py │ ├── README.md │ └── end_user │ │ ├── validate_access_token.py │ │ ├── create_end_user.py │ │ └── list_end_users.py ├── typescript │ ├── pnpm-workspace.yaml │ ├── .env.example │ ├── safePrettyPrint.ts │ ├── evm │ │ ├── accounts │ │ │ ├── createAccount.ts │ │ │ ├── importAccount.ts │ │ │ ├── updateAccount.ts │ │ │ ├── listAccounts.ts │ │ │ ├── getAccount.ts │ │ │ └── getOrCreateAccount.ts │ │ ├── policies │ │ │ ├── listPolicies.ts │ │ │ ├── listAccountPolicies.ts │ │ │ ├── listProjectPolicies.ts │ │ │ ├── createUSDSpendRestrictionPolicy.ts │ │ │ ├── createSendUserOperationPolicy.ts │ │ │ ├── createPrepareUserOperationPolicy.ts │ │ │ ├── deletePolicy.ts │ │ │ ├── getPolicyById.ts │ │ │ └── updatePolicy.ts │ │ ├── smart-accounts │ │ │ ├── createSmartAccount.ts │ │ │ ├── listSmartAccounts.ts │ │ │ ├── getSmartAccount.ts │ │ │ ├── prepareUserOperation.ts │ │ │ ├── sendUserOperation.ts │ │ │ ├── getUserOperation.ts │ │ │ ├── smartAccount.signTypedData.ts │ │ │ ├── smartAccount.listTokenBalances.ts │ │ │ └── update.ts │ │ ├── transactions │ │ │ ├── signMessage.ts │ │ │ ├── signHash.ts │ │ │ ├── signTransaction.ts │ │ │ ├── baseAccount.transfer.ts │ │ │ └── baseAccount.sendTransaction.ts │ │ ├── fund │ │ │ ├── requestFaucet.ts │ │ │ └── account.requestFaucet.ts │ │ ├── token-balances │ │ │ ├── listTokenBalances.ts │ │ │ └── account.listTokenBalances.ts │ │ ├── spend-permissions │ │ │ ├── listSpendPermissions.ts │ │ │ └── createSpendPermission.ts │ │ └── account.signTypedData.ts │ ├── tsconfig.json │ ├── solana │ │ ├── accounts │ │ │ ├── createAccount.ts │ │ │ ├── updateAccount.ts │ │ │ ├── listAccounts.ts │ │ │ ├── getAccount.ts │ │ │ └── getOrCreateAccount.ts │ │ ├── funding │ │ │ ├── requestFaucet.ts │ │ │ └── account.requestFaucet.ts │ │ ├── transactions │ │ │ ├── account.signMessage.ts │ │ │ └── signMessage.ts │ │ └── policies │ │ │ ├── createSolAllowlistPolicy.ts │ │ │ ├── createSolMessagePolicy.ts │ │ │ └── createSplTokenLimitsPolicy.ts │ ├── quickstart │ │ ├── tsconfig.json │ │ └── package.json │ ├── README.md │ ├── end-users │ │ ├── validateAccessToken.ts │ │ ├── createEndUser.ts │ │ └── listEndUsers.ts │ └── package.json ├── rust │ ├── .env.example │ └── README.md └── README.md ├── rust ├── .gitignore ├── src │ ├── error.rs │ └── lib.rs ├── clippy.toml ├── changelog.d │ └── .gitignore └── CHANGELOG.md ├── Cargo.toml ├── NOTICE.md ├── rust-toolchain.toml ├── SECURITY.md ├── .cursor └── rules │ └── repository-structure.mdc ├── .github └── workflows │ ├── go_lint.yml │ ├── go_test.yml │ └── typescript_test.yml ├── LICENSE.md └── .gitignore /go/.go-version: -------------------------------------------------------------------------------- 1 | 1.23.3 2 | -------------------------------------------------------------------------------- /python/cdp/auth/test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python/changelog.d/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python/docs/README.md: -------------------------------------------------------------------------------- 1 | ../README.md -------------------------------------------------------------------------------- /typescript/README.md: -------------------------------------------------------------------------------- 1 | src/README.md -------------------------------------------------------------------------------- /examples/go/.go-version: -------------------------------------------------------------------------------- 1 | 1.23.3 2 | -------------------------------------------------------------------------------- /python/cdp/.python-version: -------------------------------------------------------------------------------- 1 | 3.10 2 | -------------------------------------------------------------------------------- /examples/python/.python-version: -------------------------------------------------------------------------------- 1 | 3.10 2 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python/cdp/__version__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.35.0" 2 | -------------------------------------------------------------------------------- /rust/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /typescript/pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - "src" 3 | -------------------------------------------------------------------------------- /typescript/src/version.ts: -------------------------------------------------------------------------------- 1 | export const version = "1.40.1"; 2 | -------------------------------------------------------------------------------- /typescript/src/auth/hooks/axios/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./withAuth.js"; 2 | -------------------------------------------------------------------------------- /examples/typescript/pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - "../../typescript/src" 3 | -------------------------------------------------------------------------------- /typescript/src/client/solana/index.ts: -------------------------------------------------------------------------------- 1 | export { SolanaClient } from "./solana.js"; 2 | -------------------------------------------------------------------------------- /python/cdp/auth/test/factories/__init__.py: -------------------------------------------------------------------------------- 1 | """Test factories for the auth package.""" 2 | -------------------------------------------------------------------------------- /typescript/src/client/policies/index.ts: -------------------------------------------------------------------------------- 1 | export { PoliciesClient } from "./policies.js"; 2 | -------------------------------------------------------------------------------- /python/changelog.d/twin-fans-bowling.bug.md: -------------------------------------------------------------------------------- 1 | Added unauthed flow to x402 facilitator config 2 | -------------------------------------------------------------------------------- /python/docs/modules.rst: -------------------------------------------------------------------------------- 1 | cdp 2 | === 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | cdp 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "rust", 4 | "examples/rust" 5 | ] 6 | 7 | resolver = "2" 8 | -------------------------------------------------------------------------------- /python/client_config.yaml: -------------------------------------------------------------------------------- 1 | packageName: cdp.openapi_client 2 | generateSourceCodeOnly: true 3 | library: asyncio 4 | -------------------------------------------------------------------------------- /typescript/src/auth/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./http.js"; 2 | export * from "./jwt.js"; 3 | export * from "./ws.js"; 4 | -------------------------------------------------------------------------------- /typescript/.eslintignore: -------------------------------------------------------------------------------- 1 | docs/ 2 | coverage/ 3 | .github/ 4 | **/**/*.json 5 | *.md 6 | dist/ 7 | src/_types/ 8 | src/_cjs/ 9 | src/_esm/ -------------------------------------------------------------------------------- /go/client-config.yaml: -------------------------------------------------------------------------------- 1 | package: openapi 2 | generate: 3 | client: true 4 | models: true 5 | output-options: 6 | client-type-name: CDPClient -------------------------------------------------------------------------------- /go/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | -------------------------------------------------------------------------------- /NOTICE.md: -------------------------------------------------------------------------------- 1 | This project includes software from https://github.com/wevm/viem/ 2 | * Copyright (c) 2023-present weth, LLC 3 | * Licensed under MIT License -------------------------------------------------------------------------------- /python/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | -------------------------------------------------------------------------------- /typescript/.prettierignore: -------------------------------------------------------------------------------- 1 | docs/ 2 | coverage/ 3 | .github/ 4 | **/**/*.json 5 | *.md 6 | dist/ 7 | src/_types/ 8 | src/_cjs/ 9 | src/_esm/ 10 | -------------------------------------------------------------------------------- /examples/go/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | -------------------------------------------------------------------------------- /examples/python/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | -------------------------------------------------------------------------------- /examples/rust/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | -------------------------------------------------------------------------------- /examples/python/main.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python main.py 2 | def main(): 3 | print("Hello from python!") 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /examples/typescript/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | -------------------------------------------------------------------------------- /typescript/src/utils/hash.ts: -------------------------------------------------------------------------------- 1 | import { createHash } from "crypto"; 2 | 3 | export const hash = (data: Buffer) => createHash("sha256").update(data).digest("hex"); 4 | -------------------------------------------------------------------------------- /typescript/src/auth/index.ts: -------------------------------------------------------------------------------- 1 | import * as axiosHooks from "./hooks/axios/index.js"; 2 | 3 | export * from "./utils/http.js"; 4 | export * from "./utils/jwt.js"; 5 | export * from "./utils/ws.js"; 6 | export { axiosHooks }; 7 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.86.0" 3 | profile = "minimal" 4 | components = [ 5 | "rustc", 6 | "cargo", 7 | "rustfmt", 8 | "clippy", 9 | "rust-docs", 10 | "rust-src", 11 | ] 12 | -------------------------------------------------------------------------------- /python/cdp/auth/clients/urllib3/__init__.py: -------------------------------------------------------------------------------- 1 | """Request hooks for different HTTP clients.""" 2 | 3 | from .client import Urllib3AuthClient, Urllib3AuthClientOptions 4 | 5 | __all__ = ["Urllib3AuthClient", "Urllib3AuthClientOptions"] 6 | -------------------------------------------------------------------------------- /typescript/tsconfig.esm.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src"], 4 | "exclude": ["src/**/*.test.ts"], 5 | "compilerOptions": { 6 | "outDir": "./src/_esm", 7 | "sourceMap": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /typescript/.env.example: -------------------------------------------------------------------------------- 1 | CDP_API_KEY_ID=your_api_key_id_here 2 | CDP_API_KEY_SECRET=your_private_key_here 3 | CDP_WALLET_SECRET=your_wallet_auth_key_here 4 | 5 | # Address of the smart account used in e2e tests 6 | CDP_E2E_SMART_ACCOUNT_ADDRESS= 7 | -------------------------------------------------------------------------------- /rust/src/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | #[derive(Error, Debug)] 4 | pub enum CdpError { 5 | #[error("Configuration error: {0}")] 6 | Config(String), 7 | 8 | #[error("Authentication error: {0}")] 9 | Auth(String), 10 | } 11 | -------------------------------------------------------------------------------- /examples/typescript/safePrettyPrint.ts: -------------------------------------------------------------------------------- 1 | export function safePrettyPrint(obj: any) { 2 | console.log( 3 | JSON.stringify( 4 | obj, 5 | (_, value) => (typeof value === "bigint" ? value.toString() : value), 6 | 2 7 | ) 8 | ); 9 | } 10 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | The Coinbase team takes security seriously. Please do not file a public ticket discussing a potential vulnerability. 4 | 5 | Please report your findings through our [HackerOne][1] program. 6 | 7 | [1]: https://hackerone.com/coinbase 8 | -------------------------------------------------------------------------------- /typescript/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 2, 3 | "useTabs": false, 4 | "semi": true, 5 | "singleQuote": false, 6 | "trailingComma": "all", 7 | "bracketSpacing": true, 8 | "arrowParens": "avoid", 9 | "printWidth": 100, 10 | "proseWrap": "never" 11 | } 12 | -------------------------------------------------------------------------------- /typescript/tsconfig.cjs.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src"], 4 | "exclude": ["src/**/*.test.ts"], 5 | "compilerOptions": { 6 | "outDir": "./src/_cjs", 7 | "module": "CommonJS", 8 | "moduleResolution": "node", 9 | "sourceMap": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /go/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Go SDK Changelog 2 | 3 | ## [1.1.0] - 2025-07-21 4 | 5 | ### Changes 6 | 7 | - Hash request body in wallet JWT claims instead of including the full body to avoid large header size issues. 8 | 9 | ## [1.0.0] - 2025-04-14 10 | 11 | ### Features 12 | 13 | - Initial release of the CDP SDK. 14 | -------------------------------------------------------------------------------- /examples/typescript/evm/accounts/createAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/accounts/createAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const account = await cdp.evm.createAccount(); 8 | console.log("Created account: ", account.address); 9 | -------------------------------------------------------------------------------- /typescript/tsconfig.types.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src"], 4 | "exclude": ["src/**/*.test.ts"], 5 | "compilerOptions": { 6 | "declaration": true, 7 | "declarationDir": "./src/_types", 8 | "emitDeclarationOnly": true, 9 | "declarationMap": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/listPolicies.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/listPolicies.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policies = await cdp.policies.listPolicies(); 8 | console.log("Listed policies: ", JSON.stringify(policies, null, 2)); 9 | -------------------------------------------------------------------------------- /rust/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::doc_lazy_continuation)] 2 | #![allow(clippy::doc_overindented_list_items)] 3 | 4 | include!("./api.rs"); 5 | 6 | pub mod api; 7 | pub mod auth; 8 | pub mod error; 9 | 10 | /// The default base URL for the Coinbase Developer Platform API 11 | pub const CDP_BASE_URL: &str = "https://api.cdp.coinbase.com/platform"; 12 | -------------------------------------------------------------------------------- /python/cdp/actions/evm/transfer/__init__.py: -------------------------------------------------------------------------------- 1 | from .account_transfer_strategy import account_transfer_strategy 2 | from .smart_account_transfer_strategy import smart_account_transfer_strategy 3 | from .transfer import transfer 4 | 5 | __all__ = [ 6 | "account_transfer_strategy", 7 | "smart_account_transfer_strategy", 8 | "transfer", 9 | ] 10 | -------------------------------------------------------------------------------- /rust/clippy.toml: -------------------------------------------------------------------------------- 1 | # Clippy configuration for CDP Rust SDK 2 | 3 | # Allow certain patterns common in generated code 4 | too-many-arguments-threshold = 15 5 | enum-variant-name-threshold = 300 6 | enum-variant-size-threshold = 300 7 | 8 | # Configuration for generated code patterns 9 | avoid-breaking-exported-api = false 10 | allow-unwrap-in-tests = true 11 | -------------------------------------------------------------------------------- /python/docs/cdp.auth.clients.rst: -------------------------------------------------------------------------------- 1 | cdp.auth.clients package 2 | ======================== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | :maxdepth: 4 9 | 10 | cdp.auth.clients.urllib3 11 | 12 | Module contents 13 | --------------- 14 | 15 | .. automodule:: cdp.auth.clients 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | -------------------------------------------------------------------------------- /python/docs/cdp.auth.rst: -------------------------------------------------------------------------------- 1 | cdp.auth package 2 | ================ 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | :maxdepth: 4 9 | 10 | cdp.auth.clients 11 | cdp.auth.test 12 | cdp.auth.utils 13 | 14 | Module contents 15 | --------------- 16 | 17 | .. automodule:: cdp.auth 18 | :members: 19 | :undoc-members: 20 | :show-inheritance: 21 | -------------------------------------------------------------------------------- /examples/typescript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "NodeNext", 4 | "moduleResolution": "NodeNext", 5 | "baseUrl": ".", 6 | "strict": true, 7 | "types": ["node"], 8 | "noEmit": true, 9 | "paths": { 10 | "@coinbase/cdp-sdk": ["../../typescript/src"] 11 | } 12 | }, 13 | "exclude": ["node_modules"] 14 | } 15 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/listAccountPolicies.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/listAccountPolicies.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policies = await cdp.policies.listPolicies({ scope: "account" }); 8 | console.log("Listed account policies: ", JSON.stringify(policies, null, 2)); 9 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/listProjectPolicies.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/listProjectPolicies.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policies = await cdp.policies.listPolicies({ scope: "project" }); 8 | console.log("Listed project policies: ", JSON.stringify(policies, null, 2)); 9 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/constants.py: -------------------------------------------------------------------------------- 1 | """Specifies package level constants used throughout the package.""" 2 | 3 | # SDK_DEFAULT_SOURCE (str): Denotes the default source for the Python SDK. 4 | SDK_DEFAULT_SOURCE = "sdk" 5 | 6 | # ERROR_DOCS_PAGE_URL (str): The URL to the Coinbase CDP API error docs page. 7 | ERROR_DOCS_PAGE_URL = "https://docs.cloud.coinbase.com/cdp/docs/errors" 8 | -------------------------------------------------------------------------------- /typescript/.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json", 3 | "changelog": ["@changesets/changelog-github", { "repo": "coinbase/cdp-sdk" }], 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } 12 | -------------------------------------------------------------------------------- /python/cdp/test/factories/local_account_factory.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from eth_account import Account 3 | 4 | 5 | @pytest.fixture 6 | def local_account_factory(): 7 | """Create and return a factory for test accounts.""" 8 | 9 | def _create_local_account(private_key="0x" + "1" * 64): 10 | return Account.from_key(private_key) 11 | 12 | return _create_local_account 13 | -------------------------------------------------------------------------------- /examples/typescript/solana/accounts/createAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/accounts/createAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.solana.createAccount(); 9 | console.log( 10 | "Successfully created Solana account:", 11 | JSON.stringify(account, null, 2) 12 | ); 13 | -------------------------------------------------------------------------------- /python/cdp/actions/evm/spend_permissions/__init__.py: -------------------------------------------------------------------------------- 1 | """Spend Permissions actions module.""" 2 | 3 | from cdp.actions.evm.spend_permissions.account_use import account_use_spend_permission 4 | from cdp.actions.evm.spend_permissions.smart_account_use import smart_account_use_spend_permission 5 | 6 | __all__ = [ 7 | "account_use_spend_permission", 8 | "smart_account_use_spend_permission", 9 | ] 10 | -------------------------------------------------------------------------------- /go/.cursor/rules/go-development.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | globs: go/** 3 | alwaysApply: false 4 | --- 5 | 6 | ## Development Commands 7 | 8 | ```bash 9 | # Clean and prepare 10 | make clean 11 | 12 | # Run tests 13 | make test 14 | 15 | # Lint code 16 | make lint 17 | 18 | # Fix linting issues 19 | make lint-fix 20 | 21 | # Generate OpenAPI client 22 | make client 23 | 24 | # Generate docs 25 | make docs 26 | ``` 27 | -------------------------------------------------------------------------------- /python/cdp/actions/solana/constants.py: -------------------------------------------------------------------------------- 1 | GENESIS_HASH_MAINNET = "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d" 2 | GENESIS_HASH_DEVNET = "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG" 3 | GENESIS_HASH_TESTNET = "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY" 4 | 5 | USDC_MAINNET_MINT_ADDRESS = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" 6 | USDC_DEVNET_MINT_ADDRESS = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU" 7 | -------------------------------------------------------------------------------- /examples/typescript/quickstart/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "NodeNext", 5 | "moduleResolution": "NodeNext", 6 | "esModuleInterop": true, 7 | "strict": false, 8 | "types": ["node"], 9 | "skipLibCheck": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "outDir": "dist" 12 | }, 13 | "include": ["index.ts"] 14 | } 15 | -------------------------------------------------------------------------------- /python/cdp/auth/clients/__init__.py: -------------------------------------------------------------------------------- 1 | """HTTP client implementations for CDP authentication. 2 | 3 | This module exports concrete HTTP client implementations for making authenticated 4 | requests to CDP services. 5 | """ 6 | 7 | from cdp.auth.clients.urllib3.client import Urllib3AuthClient, Urllib3AuthClientOptions 8 | 9 | __all__ = [ 10 | "Urllib3AuthClient", 11 | "Urllib3AuthClientOptions", 12 | ] 13 | -------------------------------------------------------------------------------- /python/docs/cdp.x402.rst: -------------------------------------------------------------------------------- 1 | cdp.x402 package 2 | ================ 3 | 4 | Submodules 5 | ---------- 6 | 7 | cdp.x402.x402 module 8 | -------------------- 9 | 10 | .. automodule:: cdp.x402.x402 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | Module contents 16 | --------------- 17 | 18 | .. automodule:: cdp.x402 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | -------------------------------------------------------------------------------- /examples/python/pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "examples" 3 | version = "0.0.0" 4 | requires-python = ">=3.10" 5 | dependencies = [ 6 | "cdp-sdk", 7 | "solana>=0.36.6", 8 | "web3>=7.6.0", 9 | "base58>=2.1.1", 10 | "pydantic==2.11.3", 11 | "dotenv>=0.9.9", 12 | ] 13 | 14 | [tool.uv] 15 | package = false 16 | 17 | [tool.uv.sources] 18 | cdp-sdk = { path = "../../python", editable = true } 19 | -------------------------------------------------------------------------------- /examples/python/evm/policies/list_policies.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/policies/list_policies.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | policies = await cdp.policies.list_policies() 13 | print("Listed policies: ", policies) 14 | 15 | 16 | asyncio.run(main()) 17 | -------------------------------------------------------------------------------- /typescript/vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vitest/config"; 2 | 3 | export default defineConfig({ 4 | test: { 5 | globals: true, 6 | environment: "node", 7 | include: ["src/**/*.test.ts"], 8 | exclude: ["node_modules", "dist", "src/e2e.test.ts"], 9 | coverage: { 10 | provider: "v8", 11 | reporter: ["html"], 12 | exclude: ["node_modules", "dist"], 13 | }, 14 | }, 15 | }); 16 | -------------------------------------------------------------------------------- /rust/changelog.d/.gitignore: -------------------------------------------------------------------------------- 1 | # This directory is for changelog fragments 2 | # Each fragment should be a .md file named with the format: 3 | # {pr_number}.{type}.md 4 | # 5 | # Where type is one of: 6 | # - feature.md (for new features) 7 | # - bugfix.md (for bug fixes) 8 | # - removal.md (for breaking changes/removals) 9 | # 10 | # Example: 123.feature.md 11 | # 12 | # The content of the file should be a single line describing the change. -------------------------------------------------------------------------------- /typescript/vitest.e2e.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vitest/config"; 2 | 3 | export default defineConfig({ 4 | test: { 5 | globals: true, 6 | environment: "node", 7 | include: ["src/e2e.test.ts"], 8 | exclude: ["node_modules", "dist"], 9 | coverage: { 10 | provider: "v8", 11 | reporter: ["html"], 12 | exclude: ["node_modules", "dist"], 13 | }, 14 | testTimeout: 30000, 15 | }, 16 | }); 17 | -------------------------------------------------------------------------------- /examples/python/evm/accounts/create_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/accounts/create_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.evm.create_account() 14 | print(f"Successfully created account: {account.address}") 15 | 16 | 17 | asyncio.run(main()) 18 | -------------------------------------------------------------------------------- /examples/typescript/evm/accounts/importAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/accounts/importAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | import { generatePrivateKey } from "viem/accounts"; 6 | 7 | const cdp = new CdpClient(); 8 | const account = await cdp.evm.importAccount({ 9 | privateKey: generatePrivateKey(), 10 | name: "MyAccount", 11 | }); 12 | console.log("Imported account: ", account.address); 13 | -------------------------------------------------------------------------------- /examples/go/README.md: -------------------------------------------------------------------------------- 1 | # CDP SDK Examples 2 | 3 | ## Setup 4 | 5 | Follow these steps to get started: 6 | 7 | 1. Get a CDP API key and wallet secret from the [CDP Portal](https://portal.cdp.coinbase.com/access/api) 8 | 2. Fill in your API key and wallet secret in `.env.example`, then run `mv .env.example .env` 9 | 10 | ## Usage 11 | 12 | To run the example, run: 13 | 14 | ```bash 15 | go run . send_transaction 16 | go run . send_user_operation 17 | ``` 18 | -------------------------------------------------------------------------------- /examples/python/solana/accounts/create_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python solana/accounts/create_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.solana.create_account() 14 | print(f"Successfully created account: {account.address}") 15 | 16 | 17 | asyncio.run(main()) 18 | -------------------------------------------------------------------------------- /python/cdp/update_smart_account_types.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class UpdateSmartAccountOptions(BaseModel): 5 | """Options for updating an EVM smart account.""" 6 | 7 | """An optional name for the smart account. Smart account names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long. Smart account names must be unique across all EVM smart accounts in the developer's CDP Project.""" 8 | name: str | None = None 9 | -------------------------------------------------------------------------------- /python/cdp/errors.py: -------------------------------------------------------------------------------- 1 | """Custom error types for the CDP SDK.""" 2 | 3 | 4 | class UserInputValidationError(ValueError): 5 | """UserInputValidationError is thrown when validation of a user-supplied input fails.""" 6 | 7 | def __init__(self, message: str): 8 | """Initialize a new UserInputValidationError instance. 9 | 10 | Args: 11 | message: The user input validation error message. 12 | 13 | """ 14 | super().__init__(message) 15 | -------------------------------------------------------------------------------- /typescript/src/actions/solana/constants.ts: -------------------------------------------------------------------------------- 1 | export const GENESIS_HASH_MAINNET = "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d"; 2 | export const GENESIS_HASH_DEVNET = "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG"; 3 | export const GENESIS_HASH_TESTNET = "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY"; 4 | 5 | export const USDC_MAINNET_MINT_ADDRESS = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; 6 | export const USDC_DEVNET_MINT_ADDRESS = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"; 7 | -------------------------------------------------------------------------------- /examples/python/solana/funding/account.request_faucet.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python solana/funding/account.request_faucet.py 2 | import asyncio 3 | from cdp import CdpClient 4 | from dotenv import load_dotenv 5 | 6 | load_dotenv() 7 | 8 | 9 | async def main(): 10 | async with CdpClient() as cdp: 11 | account = await cdp.solana.create_account() 12 | response = await account.request_faucet(token="sol") 13 | print(response) 14 | 15 | 16 | asyncio.run(main()) 17 | -------------------------------------------------------------------------------- /examples/typescript/solana/funding/requestFaucet.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/funding/requestFaucet.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.solana.createAccount(); 9 | 10 | const { signature } = await cdp.solana.requestFaucet({ 11 | address: account.address, 12 | token: "sol", 13 | }); 14 | 15 | console.log("Successfully requested Solana faucet:", signature); 16 | -------------------------------------------------------------------------------- /python/docs/index.rst: -------------------------------------------------------------------------------- 1 | .. CDP SDK documentation master file, created by 2 | sphinx-quickstart on Tue Apr 1 14:01:44 2025. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | CDP SDK documentation 7 | ===================== 8 | 9 | .. include:: README.md 10 | :parser: myst_parser.sphinx_ 11 | 12 | .. toctree:: 13 | :maxdepth: 2 14 | :caption: Contents: 15 | :hidden: 16 | 17 | modules 18 | 19 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # CDP SDK Examples 2 | 3 | This directory contains runnable examples of how to use the CDP SDK. 4 | 5 | ## Typescript 6 | 7 | To run TypeScript examples, see [typescript/README.md](./typescript/README.md). 8 | 9 | ## Python 10 | 11 | To run Python examples, see [python/README.md](./python/README.md). 12 | 13 | ## Go 14 | 15 | To run Go examples, see [go/README.md](./go/README.md). 16 | 17 | ## Rust 18 | 19 | To run Rust examples, see [rust/README.md](./rust/README.md). 20 | -------------------------------------------------------------------------------- /examples/python/solana/transactions/account.sign_message.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python solana/transactions/account.sign_message.py 2 | import asyncio 3 | from cdp import CdpClient 4 | from dotenv import load_dotenv 5 | 6 | load_dotenv() 7 | 8 | 9 | async def main(): 10 | async with CdpClient() as cdp: 11 | account = await cdp.solana.create_account() 12 | response = await account.sign_message(message="Hello, world!") 13 | print(response) 14 | 15 | 16 | asyncio.run(main()) 17 | -------------------------------------------------------------------------------- /examples/python/solana/accounts/get_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python solana/accounts/get_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.solana.create_account() 14 | account = await cdp.solana.get_account(address=account.address) 15 | print("Account Address: ", account.address) 16 | 17 | 18 | asyncio.run(main()) 19 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/createSmartAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/createSmartAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.createAccount(); 9 | 10 | const smartAccount = await cdp.evm.createSmartAccount({ 11 | owner: account, 12 | }); 13 | 14 | console.log( 15 | `Created smart account: ${smartAccount.address}. Owner address: ${account.address}` 16 | ); 17 | -------------------------------------------------------------------------------- /examples/typescript/evm/transactions/signMessage.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/transactions/signMessage.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.createAccount(); 9 | 10 | console.log("Created account:", account.address); 11 | 12 | const signature = await cdp.evm.signMessage({ 13 | address: account.address, 14 | message: "Hello, world!", 15 | }); 16 | 17 | console.log("Signature:", signature); 18 | -------------------------------------------------------------------------------- /examples/typescript/solana/funding/account.requestFaucet.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/funding/account.requestFaucet.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.solana.getOrCreateAccount({ name: "MyAccount" }); 9 | const { signature } = await account.requestFaucet({ 10 | token: "sol", 11 | }); 12 | 13 | console.log( 14 | `Request faucet funds. Explorer link: https://sepolia.basescan.org/tx/${signature}` 15 | ); 16 | -------------------------------------------------------------------------------- /python/docs/cdp.auth.clients.urllib3.rst: -------------------------------------------------------------------------------- 1 | cdp.auth.clients.urllib3 package 2 | ================================ 3 | 4 | Submodules 5 | ---------- 6 | 7 | cdp.auth.clients.urllib3.client module 8 | -------------------------------------- 9 | 10 | .. automodule:: cdp.auth.clients.urllib3.client 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | Module contents 16 | --------------- 17 | 18 | .. automodule:: cdp.auth.clients.urllib3 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | -------------------------------------------------------------------------------- /examples/typescript/evm/accounts/updateAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/accounts/updateAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | 5 | const cdp = new CdpClient(); 6 | 7 | const account = await cdp.evm.createAccount(); 8 | console.log("Created account: ", account.address); 9 | 10 | const updatedAccount = await cdp.evm.updateAccount({ 11 | address: account.address, 12 | update: { 13 | name: "New Name" 14 | } 15 | }); 16 | console.log("Updated account:", JSON.stringify(updatedAccount, null, 2)); 17 | -------------------------------------------------------------------------------- /python/cdp/actions/util.py: -------------------------------------------------------------------------------- 1 | from decimal import Decimal 2 | 3 | 4 | def format_units(amount, decimals): 5 | """Convert an amount from atomic units to decimal units. 6 | 7 | Args: 8 | amount: The amount in atomic units, e.g. wei. 9 | decimals: The number of decimal places to convert to (e.g. 18 for ETH, 6 for USDC). 10 | 11 | Returns: 12 | str: The amount formatted as a decimal string (e.g. "1.23" for 1.23 ETH). 13 | 14 | """ 15 | return str(Decimal(amount) / (Decimal(10) ** decimals)) 16 | -------------------------------------------------------------------------------- /examples/typescript/evm/accounts/listAccounts.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/accounts/listAccounts.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | let page = await cdp.evm.listAccounts(); 9 | 10 | page.accounts.forEach((account) => console.log(account.address)); 11 | 12 | while (page.nextPageToken) { 13 | page = await cdp.evm.listAccounts({ pageToken: page.nextPageToken }); 14 | page.accounts.forEach((account) => console.log(account.address)); 15 | } 16 | -------------------------------------------------------------------------------- /examples/typescript/solana/transactions/account.signMessage.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/transactions/account.signMessage.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.solana.getOrCreateAccount({ name: "MyAccount" }); 9 | const { signature } = await account.signMessage({ 10 | message: "Hello, world!", 11 | }); 12 | 13 | console.log( 14 | `Sign message. Explorer link: https://sepolia.basescan.org/tx/${signature}` 15 | ); 16 | -------------------------------------------------------------------------------- /examples/python/README.md: -------------------------------------------------------------------------------- 1 | # CDP SDK Examples 2 | 3 | ## Setup 4 | 5 | Follow these steps to get started: 6 | 7 | 1. Get a CDP API key and wallet secret from the [CDP Portal](https://portal.cdp.coinbase.com/access/api) 8 | 1. Fill in your API key and wallet secret in `.env.example`, then run `mv .env.example .env` 9 | 1. Install dependencies: `uv sync` 10 | 11 | ## Usage 12 | 13 | To run an example, use `uv run python` followed by the path to the example file, for example: 14 | 15 | ```bash 16 | uv run python evm/create_account.py 17 | ``` 18 | -------------------------------------------------------------------------------- /examples/typescript/evm/fund/requestFaucet.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/fund/requestFaucet.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.createAccount(); 9 | const { transactionHash } = await cdp.evm.requestFaucet({ 10 | address: account.address, 11 | network: "base-sepolia", 12 | token: "eth", 13 | }); 14 | 15 | console.log( 16 | `Request faucet funds. Explorer link: https://sepolia.basescan.org/tx/${transactionHash}` 17 | ); 18 | -------------------------------------------------------------------------------- /examples/typescript/solana/accounts/updateAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/accounts/updateAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | 5 | const cdp = new CdpClient(); 6 | 7 | const account = await cdp.solana.createAccount(); 8 | console.log("Created account: ", account.address); 9 | 10 | const updatedAccount = await cdp.solana.updateAccount({ 11 | address: account.address, 12 | update: { 13 | name: "New Name" 14 | } 15 | }); 16 | console.log("Updated account:", JSON.stringify(updatedAccount, null, 2)); 17 | -------------------------------------------------------------------------------- /python/cdp/actions/solana/types.py: -------------------------------------------------------------------------------- 1 | from typing import Literal 2 | 3 | from pydantic import BaseModel, ConfigDict 4 | from solana.rpc.api import Client as SolanaClient 5 | 6 | from cdp.actions.solana.utils import Network 7 | 8 | 9 | class TransferOptions(BaseModel): 10 | """The options for the transfer.""" 11 | 12 | model_config = ConfigDict(arbitrary_types_allowed=True) 13 | 14 | from_account: str 15 | to_account: str 16 | amount: int 17 | token: str | Literal["sol", "usdc"] 18 | network: Network | SolanaClient 19 | -------------------------------------------------------------------------------- /typescript/src/actions/solana/rpc.ts: -------------------------------------------------------------------------------- 1 | import { createSolanaRpc } from "@solana/kit"; 2 | 3 | import type { Network } from "./utils.js"; 4 | 5 | /** 6 | * Create a Solana RPC client for the given network 7 | * 8 | * @param network - The network to connect to 9 | * 10 | * @returns The RPC client 11 | */ 12 | export function createRpcClient(network: Network) { 13 | const endpoint = 14 | network === "mainnet" ? "https://api.mainnet-beta.solana.com" : "https://api.devnet.solana.com"; 15 | 16 | return createSolanaRpc(endpoint); 17 | } 18 | -------------------------------------------------------------------------------- /typescript/.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /examples/typescript/evm/fund/account.requestFaucet.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/fund/account.requestFaucet.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.getOrCreateAccount({ name: "MyAccount" }); 9 | const { transactionHash } = await account.requestFaucet({ 10 | network: "base-sepolia", 11 | token: "eth", 12 | }); 13 | 14 | console.log( 15 | `Request faucet funds. Explorer link: https://sepolia.basescan.org/tx/${transactionHash}` 16 | ); 17 | -------------------------------------------------------------------------------- /examples/typescript/evm/transactions/signHash.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/transactions/signHash.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.createAccount(); 9 | 10 | console.log("Created account:", account.address); 11 | 12 | const signature = await cdp.evm.signHash({ 13 | address: account.address, 14 | hash: "0x1234567890123456789012345678901234567890123456789012345678901234", 15 | }); 16 | 17 | console.log("Signature:", signature); 18 | -------------------------------------------------------------------------------- /examples/typescript/quickstart/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cdp-quickstart", 3 | "version": "1.0.0", 4 | "type": "module", 5 | "bin": { 6 | "cdp-quickstart": "dist/index.js" 7 | }, 8 | "scripts": { 9 | "build": "tsc", 10 | "start": "node dist/index.js" 11 | }, 12 | "main": "dist/index.js", 13 | "dependencies": { 14 | "@coinbase/cdp-sdk": "^1.40.1", 15 | "viem": "^2.31.0" 16 | }, 17 | "devDependencies": { 18 | "@types/node": "^22.15.30", 19 | "tsx": "^4.19.4", 20 | "typescript": "^5.4.0" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /examples/typescript/solana/accounts/listAccounts.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/accounts/listAccounts.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | let page = await cdp.solana.listAccounts(); 9 | 10 | page.accounts.forEach((account) => console.log(account)); 11 | 12 | while (page.nextPageToken) { 13 | page = await cdp.solana.listAccounts({ 14 | pageToken: page.nextPageToken, 15 | }); 16 | 17 | page.accounts.forEach((account) => console.log(account)); 18 | } 19 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/listSmartAccounts.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/listSmartAccounts.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | let page = await cdp.evm.listSmartAccounts(); 9 | 10 | page.accounts.forEach((account) => console.log(account.address)); 11 | 12 | while (page.nextPageToken) { 13 | page = await cdp.evm.listSmartAccounts({ pageToken: page.nextPageToken }); 14 | page.accounts.forEach((account) => console.log(account.address)); 15 | } 16 | -------------------------------------------------------------------------------- /typescript/src/auth/utils/hash.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @module Hash 3 | */ 4 | 5 | import { subtle } from "uncrypto"; 6 | 7 | /** 8 | * Auth-specific hash function using uncrypto for Edge runtime compatibility. 9 | * Computes SHA-256 hash of the given data. 10 | * 11 | * @param data - The data to hash 12 | * @returns Promise that resolves to the hex-encoded hash 13 | */ 14 | export const authHash = async (data: Buffer): Promise => { 15 | const hashBuffer = await subtle.digest("SHA-256", data); 16 | return Buffer.from(hashBuffer).toString("hex"); 17 | }; 18 | -------------------------------------------------------------------------------- /python/cdp/test/factories/evm_server_account_factory.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from cdp.openapi_client.models.evm_account import EvmAccount as EvmServerAccountModel 4 | 5 | 6 | @pytest.fixture 7 | def server_account_model_factory(): 8 | """Create and return a factory for WalletModel fixtures.""" 9 | 10 | def _create_server_account_model( 11 | address="0x1234567890123456789012345678901234567890", 12 | name="test-server-account", 13 | ): 14 | return EvmServerAccountModel(address=address, name=name) 15 | 16 | return _create_server_account_model 17 | -------------------------------------------------------------------------------- /typescript/src/actions/evm/spend-permissions/types.ts: -------------------------------------------------------------------------------- 1 | import type { SpendPermissionNetwork } from "../../../openapi-client/index.js"; 2 | import type { SpendPermission } from "../../../spend-permissions/types.js"; 3 | 4 | /** 5 | * Options for using a spend permission 6 | */ 7 | export type UseSpendPermissionOptions = { 8 | /** The spend permission to use */ 9 | spendPermission: SpendPermission; 10 | /** The amount to spend (must be ≤ allowance) */ 11 | value: bigint; 12 | /** The network to execute the transaction on */ 13 | network: SpendPermissionNetwork; 14 | }; 15 | -------------------------------------------------------------------------------- /typescript/src/utils/serializeTransaction.ts: -------------------------------------------------------------------------------- 1 | import { serializeTransaction } from "viem"; 2 | 3 | import { TransactionRequestEIP1559 } from "../types/misc.js"; 4 | 5 | /** 6 | * Serializes a transaction for the Coinbase API. 7 | * 8 | * @param transaction - The transaction to serialize. 9 | * @returns The serialized transaction. 10 | */ 11 | export function serializeEIP1559Transaction(transaction: TransactionRequestEIP1559) { 12 | return serializeTransaction({ 13 | ...transaction, 14 | chainId: 1, // ignored by Coinbase API 15 | type: "eip1559", 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /examples/typescript/solana/transactions/signMessage.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/transactions/signMessage.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.solana.createAccount(); 9 | console.log( 10 | "Successfully created Solana account:", 11 | JSON.stringify(account, null, 2) 12 | ); 13 | 14 | const signature = await cdp.solana.signMessage({ 15 | address: account.address, 16 | message: "Hello, world!", 17 | }); 18 | 19 | console.log("Successfully signed message:", signature); 20 | -------------------------------------------------------------------------------- /python/.cursor/rules/python-development.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | globs: python/** 3 | alwaysApply: false 4 | --- 5 | 6 | ## Development Commands 7 | 8 | ```bash 9 | # Install dependencies (with dev dependencies) 10 | uv sync 11 | 12 | # Run tests 13 | make test 14 | 15 | # Run only unit tests (exclude E2E) 16 | make e2e 17 | 18 | # Lint 19 | make lint 20 | 21 | # Fix linting issues 22 | make lint-fix 23 | 24 | # Format code 25 | make format 26 | 27 | # Check formatting 28 | make format-check 29 | 30 | # Generate docs 31 | make docs 32 | 33 | # Generate OpenAPI client 34 | make python-client 35 | ``` 36 | -------------------------------------------------------------------------------- /typescript/src/client/end-user/endUser.types.ts: -------------------------------------------------------------------------------- 1 | import type { CreateEndUserBody, ListEndUsersParams } from "../../openapi-client/index.js"; 2 | 3 | /** 4 | * The options for validating an access token. 5 | */ 6 | export interface ValidateAccessTokenOptions { 7 | /** 8 | * The access token to validate. 9 | */ 10 | accessToken: string; 11 | } 12 | 13 | /** 14 | * The options for listing end users. 15 | */ 16 | export type ListEndUsersOptions = ListEndUsersParams; 17 | 18 | /** 19 | * The options for creating an end user. 20 | */ 21 | export type CreateEndUserOptions = CreateEndUserBody; 22 | -------------------------------------------------------------------------------- /python/cdp/update_account_types.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class UpdateAccountOptions(BaseModel): 5 | """Options for updating an account.""" 6 | 7 | """An optional name for the account. Account names can consist of alphanumeric characters and hyphens, and be between 2 and 36 characters long. Account names must be unique across all EVM accounts in the developer's CDP Project.""" 8 | name: str | None = None 9 | 10 | """An optional account policy for the account. The account policy will be applied to the account when it is created.""" 11 | account_policy: str | None = None 12 | -------------------------------------------------------------------------------- /typescript/scripts/sort-msw-index.ts: -------------------------------------------------------------------------------- 1 | import fs from "node:fs"; 2 | import path from "node:path"; 3 | 4 | const indexPath = path.join(process.cwd(), "src/openapi-client/generated/index.msw.ts"); 5 | 6 | if (fs.existsSync(indexPath)) { 7 | const content = fs.readFileSync(indexPath, "utf-8"); 8 | const lines = content.split("\n").filter(line => line.trim()); 9 | const sortedLines = lines.sort((a, b) => a.localeCompare(b)); 10 | fs.writeFileSync(indexPath, sortedLines.join("\n") + "\n"); 11 | console.log("✅ Sorted MSW index exports"); 12 | } else { 13 | console.log("MSW index file not found, skipping sort"); 14 | } 15 | -------------------------------------------------------------------------------- /typescript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2022", 4 | "moduleResolution": "NodeNext", 5 | "module": "NodeNext", 6 | "strict": true, 7 | "resolveJsonModule": true, 8 | "esModuleInterop": true, 9 | "skipLibCheck": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "noImplicitAny": false, 12 | "removeComments": false, 13 | "allowJs": false, 14 | "checkJs": false, 15 | "rootDir": "./src" 16 | }, 17 | "include": ["src/**/*.ts"], 18 | "exclude": ["node_modules", "dist", "src/**/*.test.ts", "**/tests/**", "src/examples", "fixtures"] 19 | } 20 | -------------------------------------------------------------------------------- /examples/python/evm/accounts/get_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/accounts/get_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.evm.create_account(name="Account1") 14 | account = await cdp.evm.get_account(address=account.address) 15 | print("Account Address: ", account.address) 16 | account = await cdp.evm.get_account(name=account.name) 17 | print("Account Name: ", account.name) 18 | 19 | 20 | asyncio.run(main()) 21 | -------------------------------------------------------------------------------- /python/cdp/auth/utils/__init__.py: -------------------------------------------------------------------------------- 1 | """CDP SDK Auth Utils package.""" 2 | 3 | from .http import GetAuthHeadersOptions, get_auth_headers 4 | from .jwt import JwtOptions, WalletJwtOptions, generate_jwt, generate_wallet_jwt 5 | from .ws import GetWebSocketAuthHeadersOptions, get_websocket_auth_headers 6 | 7 | __all__ = [ 8 | "GetAuthHeadersOptions", 9 | "GetWebSocketAuthHeadersOptions", 10 | "JwtOptions", 11 | "WalletJwtOptions", 12 | # JWT utils 13 | "generate_jwt", 14 | "generate_wallet_jwt", 15 | # HTTP utils 16 | "get_auth_headers", 17 | # WebSocket utils 18 | "get_websocket_auth_headers", 19 | ] 20 | -------------------------------------------------------------------------------- /typescript/orval.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "orval"; 2 | 3 | export default defineConfig({ 4 | cdp: { 5 | input: { 6 | target: "../openapi.yaml", 7 | }, 8 | output: { 9 | clean: true, 10 | target: "./generated", 11 | mode: "tags-split", 12 | mock: false, 13 | override: { 14 | mutator: { 15 | path: "./cdpApiClient.ts", 16 | name: "cdpApiClient", 17 | extension: ".js", 18 | }, 19 | }, 20 | workspace: "./src/openapi-client", 21 | }, 22 | hooks: { 23 | afterAllFilesWrite: "pnpm format", 24 | }, 25 | }, 26 | }); 27 | -------------------------------------------------------------------------------- /typescript/src/accounts/solana/types.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @module Accounts 3 | */ 4 | 5 | import { AccountActions } from "../../actions/solana/types.js"; 6 | import { SolanaAccount as OpenAPISolanaAccount } from "../../openapi-client/index.js"; 7 | import { Prettify } from "../../types/utils.js"; 8 | 9 | /** 10 | * A base Solana account. 11 | * 12 | * @internal 13 | */ 14 | export type Account = OpenAPISolanaAccount; 15 | 16 | /** 17 | * A Solana account with actions. 18 | * 19 | * @see {@link OpenAPISolanaAccount} 20 | * @see {@link AccountActions} 21 | */ 22 | export type SolanaAccount = Prettify; 23 | -------------------------------------------------------------------------------- /examples/typescript/evm/accounts/getAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/accounts/getAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | let account = await cdp.evm.createAccount({ 9 | name: `Account-${Math.floor(Math.random() * 100)}`, 10 | }); 11 | console.log("Created account:", account.address); 12 | 13 | account = await cdp.evm.getAccount({ address: account.address }); 14 | console.log("Retrieved account by address:", account.address); 15 | 16 | account = await cdp.evm.getAccount({ name: account.name }); 17 | console.log("Retrieved account by name:", account.name); 18 | -------------------------------------------------------------------------------- /python/cdp/spend_permissions/__init__.py: -------------------------------------------------------------------------------- 1 | """Spend Permissions module for CDP SDK.""" 2 | 3 | from cdp.spend_permissions.constants import ( 4 | SPEND_PERMISSION_MANAGER_ABI, 5 | SPEND_PERMISSION_MANAGER_ADDRESS, 6 | ) 7 | from cdp.spend_permissions.types import ( 8 | SpendPermission, 9 | SpendPermissionInput, 10 | ) 11 | from cdp.spend_permissions.utils import resolve_spend_permission, resolve_token_address 12 | 13 | __all__ = [ 14 | "SPEND_PERMISSION_MANAGER_ADDRESS", 15 | "SPEND_PERMISSION_MANAGER_ABI", 16 | "SpendPermission", 17 | "SpendPermissionInput", 18 | "resolve_token_address", 19 | "resolve_spend_permission", 20 | ] 21 | -------------------------------------------------------------------------------- /go/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/coinbase/cdp-sdk/go 2 | 3 | go 1.23.0 4 | 5 | require ( 6 | github.com/golang-jwt/jwt/v5 v5.2.2 7 | github.com/oapi-codegen/runtime v1.1.1 8 | github.com/stretchr/testify v1.10.0 9 | ) 10 | 11 | require ( 12 | github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect 13 | github.com/davecgh/go-spew v1.1.1 // indirect 14 | github.com/google/uuid v1.5.0 // indirect 15 | github.com/kr/pretty v0.3.1 // indirect 16 | github.com/pmezard/go-difflib v1.0.0 // indirect 17 | github.com/rogpeppe/go-internal v1.12.0 // indirect 18 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 19 | gopkg.in/yaml.v3 v3.0.1 // indirect 20 | ) 21 | -------------------------------------------------------------------------------- /typescript/.cursor/rules/typescript-development.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | globs: typescript/** 3 | alwaysApply: false 4 | --- 5 | 6 | ## Development Commands 7 | 8 | ```bash 9 | # Install dependencies 10 | pnpm install 11 | 12 | # Build the SDK 13 | pnpm build 14 | 15 | # Run tests 16 | pnpm test 17 | 18 | # Run E2E tests 19 | pnpm test:e2e 20 | 21 | # Lint code 22 | pnpm lint 23 | 24 | # Fix linting issues 25 | pnpm lint:fix 26 | 27 | # Format code 28 | pnpm format 29 | 30 | # Check formatting 31 | pnpm format:check 32 | 33 | # Generate docs 34 | pnpm run docs 35 | 36 | # Generate Markdown docs 37 | pnpm run docs:md 38 | 39 | # Generate OpenAPI client 40 | pnpm orval 41 | ``` 42 | -------------------------------------------------------------------------------- /examples/typescript/evm/token-balances/listTokenBalances.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/token-balances/listTokenBalances.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | // Get the first page of token balances for barmstrong.eth. 9 | const address = "0x5b76f5B8fc9D700624F78208132f91AD4e61a1f0"; 10 | 11 | const result = await cdp.evm.listTokenBalances({ 12 | address, 13 | network: "base-sepolia", 14 | }); 15 | 16 | for (const balance of result.balances) { 17 | console.log("Token contract address:", balance.token.contractAddress); 18 | console.log("Token balance:", balance.amount.amount); 19 | } 20 | -------------------------------------------------------------------------------- /python/cdp/auth/test/factories/auth_headers_factory.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.fixture 5 | def auth_headers_factory(): 6 | """Create and return a factory for authentication headers. 7 | 8 | Returns: 9 | callable: A factory function that creates auth header dictionaries 10 | 11 | """ 12 | 13 | def _create_headers( 14 | token="test.token", content_type="application/json", additional_headers=None 15 | ): 16 | headers = {"Authorization": f"Bearer {token}", "Content-Type": content_type} 17 | if additional_headers: 18 | headers.update(additional_headers) 19 | return headers 20 | 21 | return _create_headers 22 | -------------------------------------------------------------------------------- /examples/typescript/README.md: -------------------------------------------------------------------------------- 1 | # CDP SDK Examples 2 | 3 | ## Setup 4 | 5 | Follow these steps to get started: 6 | 7 | 1. Get a CDP API key and wallet secret from the [CDP Portal](https://portal.cdp.coinbase.com/access/api) 8 | 1. Fill in your API key and wallet secret in `.env.example`, then run `mv .env.example .env` 9 | 1. In the root `typescript/` folder, run `pnpm install && pnpm build`. You only need to do this once 10 | 1. In the `examples/typescript` folder, run `pnpm install` to install the dependencies 11 | 12 | ## Usage 13 | 14 | To run an example, use `pnpm tsx` followed by the path to the example file, for example: 15 | 16 | ```bash 17 | pnpm tsx evm/createAccount.ts 18 | ``` 19 | -------------------------------------------------------------------------------- /examples/typescript/end-users/validateAccessToken.ts: -------------------------------------------------------------------------------- 1 | // Usage: CDP_ACCESS_TOKEN=... pnpm tsx end-users/validateAccessToken.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const accessToken = process.env.CDP_ACCESS_TOKEN; 9 | if (!accessToken) { 10 | throw new Error("CDP_ACCESS_TOKEN is not set"); 11 | } 12 | 13 | try { 14 | const endUser = await cdp.endUser.validateAccessToken({ 15 | accessToken, 16 | }); 17 | console.log("Access token validated: ", endUser); 18 | } catch (error) { 19 | console.error("Error validating access token: ", (error as { errorMessage: string }).errorMessage); 20 | } -------------------------------------------------------------------------------- /typescript/src/utils/bigint.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-explicit-any */ 2 | /** 3 | * Converts bigint values in an object to strings for safe serialization 4 | * 5 | * @param obj - The object to convert 6 | * @returns A new object with bigint values converted to strings 7 | */ 8 | export const convertBigIntsToStrings = (obj: any): any => { 9 | if (typeof obj === "bigint") { 10 | return obj.toString(); 11 | } 12 | if (Array.isArray(obj)) { 13 | return obj.map(convertBigIntsToStrings); 14 | } 15 | if (obj && typeof obj === "object") { 16 | return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, convertBigIntsToStrings(v)])); 17 | } 18 | return obj; 19 | }; 20 | -------------------------------------------------------------------------------- /typescript/src/utils/sortKeys.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-explicit-any */ 2 | /** 3 | * Recursively sorts object keys to ensure consistent JSON stringification 4 | * 5 | * @param obj - The object to sort 6 | * @returns A new object with sorted keys 7 | */ 8 | export const sortKeys = (obj: any): any => { 9 | if (!obj || typeof obj !== "object") { 10 | return obj; 11 | } 12 | 13 | if (Array.isArray(obj)) { 14 | return obj.map(sortKeys); 15 | } 16 | 17 | return Object.keys(obj) 18 | .sort() 19 | .reduce( 20 | (acc, key) => { 21 | acc[key] = sortKeys(obj[key]); 22 | return acc; 23 | }, 24 | {} as Record, 25 | ); 26 | }; 27 | -------------------------------------------------------------------------------- /examples/python/evm/accounts/create_account_idempotency.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/accounts/create_account_idempotency.py 2 | 3 | import asyncio 4 | import uuid 5 | 6 | from cdp import CdpClient 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() 10 | 11 | 12 | async def main(): 13 | async with CdpClient() as cdp: 14 | key = str(uuid.uuid4()) 15 | account = await cdp.evm.create_account(idempotency_key=key) 16 | account2 = await cdp.evm.create_account(idempotency_key=key) 17 | account3 = await cdp.evm.create_account(idempotency_key=key) 18 | 19 | print(account.address) 20 | print(account2.address) 21 | print(account3.address) 22 | 23 | 24 | asyncio.run(main()) 25 | -------------------------------------------------------------------------------- /examples/python/evm/token-balances/account.list_token_balances.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/token-balances/account.list_token_balances.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | account = await cdp.evm.get_or_create_account(name="Account1") 13 | print(f"Account: {account.address}") 14 | 15 | print("Listing token balances for account...") 16 | balances = await account.list_token_balances( 17 | network="base-sepolia", 18 | page_size=10, 19 | ) 20 | print(f"Balances: {balances}") 21 | 22 | 23 | asyncio.run(main()) 24 | -------------------------------------------------------------------------------- /examples/python/evm/token-balances/list_token_balances.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/tokens/list_token_balances.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | address = "0x5b76f5B8fc9D700624F78208132f91AD4e61a1f0" 14 | network = "base-sepolia" 15 | token_balances = await cdp.evm.list_token_balances(address, network) 16 | 17 | for balance in token_balances.balances: 18 | print( 19 | f"Contract Address: {balance.token.contract_address} Balance: {balance.amount.amount}" 20 | ) 21 | 22 | 23 | asyncio.run(main()) 24 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/getSmartAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/getSmartAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; 5 | import "dotenv/config"; 6 | 7 | const cdp = new CdpClient(); 8 | 9 | const privateKey = generatePrivateKey(); 10 | const owner = privateKeyToAccount(privateKey); 11 | 12 | let smartAccount = await cdp.evm.createSmartAccount({ owner }); 13 | console.log("Created smart account:", smartAccount.address); 14 | 15 | smartAccount = await cdp.evm.getSmartAccount({ 16 | address: smartAccount.address, 17 | owner, 18 | }); 19 | 20 | console.log("Retrieved smart account: ", smartAccount); 21 | -------------------------------------------------------------------------------- /examples/typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "type": "module", 4 | "dependencies": { 5 | "@coinbase/cdp-sdk": "workspace:*", 6 | "@solana/kit": "^3.0.3", 7 | "@solana-program/token": "^0.6.0", 8 | "@solana-program/system": "^0.8.0", 9 | "@solana/web3.js": "^1.98.1", 10 | "@types/node": "^22.14.1", 11 | "bs58": "^6.0.0", 12 | "dotenv": "^16.5.0", 13 | "permissionless": "^0.2.47", 14 | "tsx": "^4.19.3", 15 | "viem": "^2.21.26" 16 | }, 17 | "scripts": { 18 | "build": "tsc" 19 | }, 20 | "packageManager": "pnpm@10.11.1+sha512.e519b9f7639869dc8d5c3c5dfef73b3f091094b0a006d7317353c72b124e80e1afd429732e28705ad6bfa1ee879c1fce46c128ccebd3192101f43dd67c667912" 21 | } 22 | -------------------------------------------------------------------------------- /python/docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /examples/typescript/end-users/createEndUser.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx end-users/createEndUser.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | try { 9 | // Create an end user with an email authentication method with an EVM account. 10 | const endUser = await cdp.endUser.createEndUser({ 11 | authenticationMethods: [ 12 | { type: "email", email: "user@example.com" } 13 | ], 14 | evmAccount: { createSmartAccount: false } 15 | }); 16 | 17 | console.log("Created end user:", endUser); 18 | } catch (error) { 19 | console.error("Error creating end user: ", (error as { errorMessage: string }).errorMessage); 20 | } 21 | -------------------------------------------------------------------------------- /examples/python/evm/fund/account.fund.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/fund/account.fund.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | account = await cdp.evm.get_or_create_account(name="account") 13 | 14 | fund_operation = await account.fund( 15 | network="base", 16 | token="eth", 17 | amount=500000000000000, # 0.0005 eth 18 | ) 19 | 20 | completed_transfer = await account.wait_for_fund_operation_receipt( 21 | transfer_id=fund_operation.id, 22 | ) 23 | 24 | print(completed_transfer) 25 | 26 | 27 | asyncio.run(main()) -------------------------------------------------------------------------------- /examples/typescript/solana/accounts/getAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/accounts/getAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | let account = await cdp.solana.createAccount({ 9 | name: `Account-${Math.floor(Math.random() * 100)}`, 10 | }); 11 | console.log( 12 | "Successfully created Solana account:", 13 | JSON.stringify(account, null, 2) 14 | ); 15 | 16 | account = await cdp.solana.getAccount({ 17 | address: account.address, 18 | }); 19 | 20 | console.log("Got Solana account by address:", account.address); 21 | 22 | account = await cdp.solana.getAccount({ 23 | name: account.name, 24 | }); 25 | 26 | console.log("Got Solana account by name:", account.name); 27 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/api_response.py: -------------------------------------------------------------------------------- 1 | """API response object.""" 2 | 3 | from __future__ import annotations 4 | from typing import Optional, Generic, Mapping, TypeVar 5 | from pydantic import Field, StrictInt, StrictBytes, BaseModel 6 | 7 | T = TypeVar("T") 8 | 9 | class ApiResponse(BaseModel, Generic[T]): 10 | """ 11 | API response object 12 | """ 13 | 14 | status_code: StrictInt = Field(description="HTTP status code") 15 | headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") 16 | data: T = Field(description="Deserialized data given the data type") 17 | raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") 18 | 19 | model_config = { 20 | "arbitrary_types_allowed": True 21 | } 22 | -------------------------------------------------------------------------------- /examples/go/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | if len(os.Args) < 2 { 10 | printUsage() 11 | os.Exit(1) 12 | } 13 | 14 | exampleName := os.Args[1] 15 | 16 | switch exampleName { 17 | case "send_transaction": 18 | SendTransactionExample() 19 | case "send_user_operation": 20 | SendUserOperationExample() 21 | default: 22 | fmt.Printf("Unknown example: %s\n", exampleName) 23 | printUsage() 24 | os.Exit(1) 25 | } 26 | } 27 | 28 | func printUsage() { 29 | fmt.Println("Usage: go run . ") 30 | fmt.Println("Available examples:") 31 | fmt.Println(" send_transaction - Create an EVM account and send a transaction") 32 | fmt.Println(" send_user_operation - Create a smart account and send a user operation") 33 | } -------------------------------------------------------------------------------- /examples/python/end_user/validate_access_token.py: -------------------------------------------------------------------------------- 1 | # Usage: CDP_ACCESS_TOKEN=... uv run python end_user/validate_access_token.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | import os 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | access_token = os.getenv("CDP_ACCESS_TOKEN") 11 | 12 | if not access_token: 13 | raise ValueError("CDP_ACCESS_TOKEN must be set") 14 | 15 | 16 | async def main(): 17 | async with CdpClient() as cdp: 18 | try: 19 | end_user = await cdp.end_user.validate_access_token( 20 | access_token=access_token, 21 | ) 22 | print(end_user) 23 | except Exception as e: 24 | # Access token is invalid or expired 25 | raise e 26 | 27 | 28 | asyncio.run(main()) -------------------------------------------------------------------------------- /examples/typescript/evm/policies/createUSDSpendRestrictionPolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/createUSDSpendRestrictionPolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "Reject over one hundred dollars", 11 | rules: [ 12 | { 13 | action: "reject", 14 | operation: "sendEvmTransaction", 15 | criteria: [ 16 | { 17 | type: "netUSDChange", 18 | changeCents: 10000, 19 | operator: ">", 20 | }, 21 | ], 22 | }, 23 | ], 24 | }, 25 | }); 26 | console.log("Created USD restriction policy: ", policy.id); 27 | -------------------------------------------------------------------------------- /python/docs/cdp.auth.utils.rst: -------------------------------------------------------------------------------- 1 | cdp.auth.utils package 2 | ====================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | cdp.auth.utils.http module 8 | -------------------------- 9 | 10 | .. automodule:: cdp.auth.utils.http 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | cdp.auth.utils.jwt module 16 | ------------------------- 17 | 18 | .. automodule:: cdp.auth.utils.jwt 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | cdp.auth.utils.ws module 24 | ------------------------ 25 | 26 | .. automodule:: cdp.auth.utils.ws 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | Module contents 32 | --------------- 33 | 34 | .. automodule:: cdp.auth.utils 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | -------------------------------------------------------------------------------- /.cursor/rules/repository-structure.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | alwaysApply: true 3 | --- 4 | 5 | ## Overview 6 | 7 | This is the Coinbase Developer Platform (CDP) SDK repository containing multi-language client libraries for creating, managing, and using crypto wallets. The SDK supports TypeScript, Python, and Go implementations. 8 | 9 | ## Repository Structure 10 | 11 | - `typescript/` - TypeScript/Node.js SDK implementation 12 | - `python/` - Python SDK implementation 13 | - `go/` - Go SDK implementation 14 | - `examples/` - Working examples for all languages 15 | - `openapi.yaml` - OpenAPI specification for the CDP API 16 | 17 | ## Root Level Development Commands 18 | 19 | ```bash 20 | # Update OpenAPI specification 21 | make update-openapi 22 | 23 | # Check if OpenAPI spec is up to date 24 | make check-openapi 25 | ``` 26 | -------------------------------------------------------------------------------- /examples/typescript/solana/policies/createSolAllowlistPolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/policies/createSolAllowlistPolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "SOL Allowlist Policy", 11 | rules: [ 12 | { 13 | action: "accept", 14 | operation: "signSolTransaction", 15 | criteria: [ 16 | { 17 | type: "solAddress", 18 | addresses: ["DtdSSG8ZJRZVv5Jx7K1MeWp7Zxcu19GD5wQRGRpQ9uMF"], 19 | operator: "in", 20 | }, 21 | ], 22 | }, 23 | ], 24 | }, 25 | }); 26 | console.log("Created sol allowlist policy: ", policy.id); 27 | -------------------------------------------------------------------------------- /examples/typescript/solana/policies/createSolMessagePolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/policies/createSolMessagePolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | // Create a policy that only allows signing messages starting with "CDP:" 9 | const policy = await cdp.policies.createPolicy({ 10 | policy: { 11 | scope: "account", 12 | description: "Allow messages with CDP prefix only", 13 | rules: [ 14 | { 15 | action: "accept", 16 | operation: "signSolMessage", 17 | criteria: [ 18 | { 19 | type: "solMessage", 20 | match: "^CDP:.*", 21 | }, 22 | ], 23 | }, 24 | ], 25 | }, 26 | }); 27 | 28 | console.log("Created sol message policy: ", policy.id); 29 | -------------------------------------------------------------------------------- /examples/python/evm/accounts/import_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/accounts/import_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | from eth_account import Account 8 | 9 | load_dotenv() 10 | 11 | 12 | async def main(): 13 | async with CdpClient() as cdp: 14 | account = Account.create() 15 | print("Account address: ", account.address) 16 | imported_account = await cdp.evm.import_account( 17 | private_key=account.key.hex(), 18 | name="MyImportedAccount", 19 | ) 20 | print("Imported account: ", imported_account.address) 21 | retrieved_account = await cdp.evm.get_account(address=imported_account.address) 22 | print("Retrieved account: ", retrieved_account.address) 23 | 24 | 25 | asyncio.run(main()) 26 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.fund.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.fund.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | account = await cdp.evm.create_account() 13 | smart_account = await cdp.evm.create_smart_account(owner=account) 14 | 15 | fund_operation = await smart_account.fund( 16 | network="base", 17 | token="usdc", 18 | amount=1000000, # 1 USDC 19 | ) 20 | 21 | completed_transfer = await smart_account.wait_for_fund_operation_receipt( 22 | transfer_id=fund_operation.id, 23 | ) 24 | 25 | print(completed_transfer) 26 | 27 | 28 | asyncio.run(main()) -------------------------------------------------------------------------------- /typescript/ts-frontmatter.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import { MarkdownPageEvent } from "typedoc-plugin-markdown"; 3 | 4 | /** 5 | * @param {import('typedoc-plugin-markdown').MarkdownApplication} app 6 | */ 7 | export function load(app) { 8 | app.renderer.on( 9 | MarkdownPageEvent.BEGIN, 10 | /** @param {import('typedoc-plugin-markdown').MarkdownPageEvent} page */ 11 | page => { 12 | /** 13 | * Update page.frontmatter object using information from the page model 14 | */ 15 | 16 | // Set the frontmatter title to just the name 17 | page.frontmatter = { 18 | // Just use the plain name 19 | title: page.model?.name || "", 20 | sidebarTitle: page.model?.name || "", 21 | // spread the existing frontmatter 22 | ...page.frontmatter, 23 | }; 24 | }, 25 | ); 26 | } 27 | -------------------------------------------------------------------------------- /python/cdp/auth/test/factories/auth_client_options_factory.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from cdp.auth.clients.urllib3.client import Urllib3AuthClientOptions 4 | 5 | 6 | @pytest.fixture 7 | def auth_client_options_factory(): 8 | """Create and return a factory for Urllib3AuthClientOptions fixtures. 9 | 10 | Returns: 11 | callable: A factory function that creates Urllib3AuthClientOptions instances 12 | 13 | """ 14 | 15 | def _create_auth_client_options( 16 | api_key_id="test-key-id", 17 | api_key_secret="test-secret", 18 | wallet_secret="test-wallet-key", 19 | ): 20 | return Urllib3AuthClientOptions( 21 | api_key_id=api_key_id, 22 | api_key_secret=api_key_secret, 23 | wallet_secret=wallet_secret, 24 | ) 25 | 26 | return _create_auth_client_options 27 | -------------------------------------------------------------------------------- /python/cdp/auth/test/factories/http_client_factory.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import MagicMock 2 | 3 | import pytest 4 | 5 | 6 | @pytest.fixture 7 | def http_client_factory(http_response_factory): 8 | """Create and return a factory for mock HTTP clients. 9 | 10 | Args: 11 | http_response_factory: Factory for creating mock HTTP responses 12 | 13 | Returns: 14 | callable: A factory function that creates mock HTTP client objects 15 | 16 | """ 17 | 18 | def _create_client(response=None): 19 | mock_client = MagicMock() 20 | mock_client.request = MagicMock() 21 | 22 | if response: 23 | mock_client.request.return_value = response 24 | else: 25 | mock_client.request.return_value = http_response_factory() 26 | 27 | return mock_client 28 | 29 | return _create_client 30 | -------------------------------------------------------------------------------- /examples/python/evm/fund/account.request_faucet.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/fund/account.request_faucet.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from web3 import Web3 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.evm.get_or_create_account(name="Account1") 14 | print(f"Account: {account.address}") 15 | 16 | print("Requesting ETH from faucet for account...") 17 | faucet_hash = await account.request_faucet( 18 | network="base-sepolia", 19 | token="eth", 20 | ) 21 | 22 | w3 = Web3(Web3.HTTPProvider("https://sepolia.base.org")) 23 | w3.eth.wait_for_transaction_receipt(faucet_hash) 24 | print("Received funds from faucet!") 25 | 26 | 27 | asyncio.run(main()) 28 | -------------------------------------------------------------------------------- /examples/typescript/evm/spend-permissions/listSpendPermissions.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/spend-permissions/listSpendPermissions.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | import { safePrettyPrint } from "../../safePrettyPrint.js"; 7 | 8 | const cdp = new CdpClient(); 9 | 10 | const smartAccount = await cdp.evm.getOrCreateSmartAccount({ 11 | enableSpendPermissions: true, 12 | name: "Example-Account", 13 | owner: await cdp.evm.getOrCreateAccount({ 14 | name: "Example-Account-Owner", 15 | }), 16 | }); 17 | 18 | console.log("Smart Account Address:", smartAccount.address); 19 | 20 | const permissions = await cdp.evm.listSpendPermissions({ 21 | address: smartAccount.address, 22 | }); 23 | 24 | console.log("All permissions granted by smart account:", smartAccount.address); 25 | safePrettyPrint(permissions); 26 | -------------------------------------------------------------------------------- /examples/typescript/evm/transactions/signTransaction.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/transactions/signTransaction.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | 5 | import { parseEther, serializeTransaction } from "viem"; 6 | import { baseSepolia } from "viem/chains"; 7 | import "dotenv/config"; 8 | 9 | const cdp = new CdpClient(); 10 | 11 | const account = await cdp.evm.createAccount(); 12 | 13 | console.log("Created account:", account.address); 14 | 15 | const serializedTx = serializeTransaction({ 16 | chainId: baseSepolia.id, 17 | data: "0x", 18 | to: "0x4252e0c9A3da5A2700e7d91cb50aEf522D0C6Fe8", 19 | type: "eip1559", 20 | value: parseEther("0.000001"), 21 | }); 22 | 23 | const signature = await cdp.evm.signTransaction({ 24 | address: account.address, 25 | transaction: serializedTx, 26 | }); 27 | 28 | console.log("Signature:", signature); 29 | -------------------------------------------------------------------------------- /typescript/scripts/prepublish.ts: -------------------------------------------------------------------------------- 1 | import { readFile, writeFile } from "node:fs/promises"; 2 | import { join, dirname } from "node:path"; 3 | import { fileURLToPath } from "node:url"; 4 | 5 | // Get the directory of the current module 6 | const __dirname = dirname(fileURLToPath(import.meta.url)); 7 | 8 | const packageJsonPath = join(__dirname, "../src/package.json"); 9 | 10 | // Read package.json 11 | const packageJsonContent = await readFile(packageJsonPath, "utf-8"); 12 | const packageJson = JSON.parse(packageJsonContent); 13 | 14 | /* 15 | * NOTE: We explicitly don't want to publish the type field. 16 | * We create a separate package.json for `dist/cjs` and `dist/esm` that has the type field. 17 | */ 18 | delete packageJson.type; 19 | 20 | // Write the modified package.json back to file 21 | await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2)); 22 | -------------------------------------------------------------------------------- /typescript/src/actions/evm/transfer/utils.ts: -------------------------------------------------------------------------------- 1 | import { Network } from "./types.js"; 2 | 3 | /** 4 | * The address of an ERC20 token for a given network. 5 | */ 6 | const addressMap = { 7 | base: { 8 | usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", 9 | }, 10 | "base-sepolia": { 11 | usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", 12 | }, 13 | }; 14 | 15 | /** 16 | * Get the address of an ERC20 token for a given network. 17 | * If a contract address is provided, it will not be found in the map and will be returned as is. 18 | * 19 | * @param token - The token symbol or contract address. 20 | * @param network - The network to get the address for. 21 | * 22 | * @returns The address of the ERC20 token. 23 | */ 24 | export function getErc20Address(token: string, network: Network) { 25 | return addressMap[network][token] ?? token; 26 | } 27 | -------------------------------------------------------------------------------- /typescript/typedoc.index.json: -------------------------------------------------------------------------------- 1 | { 2 | "entryPoints": [], 3 | "out": "./docs-md", 4 | "plugin": ["typedoc-plugin-markdown", "typedoc-plugin-frontmatter"], 5 | "readme": "./TYPEDOC-README.md", 6 | "name": "CDP SDK TypeScript", 7 | "includeVersion": true, 8 | "excludePrivate": true, 9 | "excludeInternal": true, 10 | "excludeProtected": false, 11 | "skipErrorChecking": true, 12 | "treatWarningsAsErrors": false, 13 | "fileExtension": ".mdx", 14 | "entryFileName": "index", 15 | "mergeReadme": true, 16 | "hidePageHeader": true, 17 | "hideBreadcrumbs": true, 18 | "hidePageTitle": true, 19 | "useCodeBlocks": true, 20 | "publicPath": "/sdks/cdp-sdks-v2/typescript", 21 | "expandObjects": true, 22 | "expandParameters": true, 23 | "readmeFrontmatter": { 24 | "title": "Overview" 25 | }, 26 | "disableSources": true, 27 | "hideGenerator": true 28 | } 29 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_error_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.error_type import ErrorType 19 | 20 | class TestErrorType(unittest.TestCase): 21 | """ErrorType unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testErrorType(self): 30 | """Test ErrorType""" 31 | # inst = ErrorType() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_x402_version.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.x402_version import X402Version 19 | 20 | class TestX402Version(unittest.TestCase): 21 | """X402Version unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testX402Version(self): 30 | """Test X402Version""" 31 | # inst = X402Version() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/auth/test/factories/http_response_factory.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import MagicMock 2 | 3 | import pytest 4 | 5 | 6 | @pytest.fixture 7 | def http_response_factory(): 8 | """Create and return a factory for mock HTTP responses. 9 | 10 | Returns: 11 | callable: A factory function that creates mock HTTP response objects 12 | 13 | """ 14 | 15 | def _create_response( 16 | status: int = 200, 17 | data: bytes = b'{"test": "data"}', 18 | headers: dict[str, str] | None = None, 19 | ): 20 | """Create a mock HTTP response object.""" 21 | if not headers: 22 | headers = {"Content-Type": "application/json"} 23 | mock_response = MagicMock() 24 | mock_response.status = status 25 | mock_response.data = data 26 | mock_response.headers = headers 27 | return mock_response 28 | 29 | return _create_response 30 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_known_abi_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.known_abi_type import KnownAbiType 19 | 20 | class TestKnownAbiType(unittest.TestCase): 21 | """KnownAbiType unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testKnownAbiType(self): 30 | """Test KnownAbiType""" 31 | # inst = KnownAbiType() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_known_idl_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.known_idl_type import KnownIdlType 19 | 20 | class TestKnownIdlType(unittest.TestCase): 21 | """KnownIdlType unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testKnownIdlType(self): 30 | """Test KnownIdlType""" 31 | # inst = KnownIdlType() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_evm_swaps_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.evm_swaps_network import EvmSwapsNetwork 19 | 20 | class TestEvmSwapsNetwork(unittest.TestCase): 21 | """EvmSwapsNetwork unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testEvmSwapsNetwork(self): 30 | """Test EvmSwapsNetwork""" 31 | # inst = EvmSwapsNetwork() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_onramp_order_status.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.onramp_order_status import OnrampOrderStatus 19 | 20 | class TestOnrampOrderStatus(unittest.TestCase): 21 | """OnrampOrderStatus unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testOnrampOrderStatus(self): 30 | """Test OnrampOrderStatus""" 31 | # inst = OnrampOrderStatus() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/createSendUserOperationPolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/createSendUserOperationPolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "SendUserOperation Example", 11 | rules: [ 12 | { 13 | action: "accept", 14 | operation: "sendUserOperation", 15 | criteria: [ 16 | { 17 | type: "ethValue", 18 | ethValue: "1000000000000000000", 19 | operator: "<=", 20 | }, 21 | { 22 | type: "evmAddress", 23 | addresses: ["0x000000000000000000000000000000000000dEaD"], 24 | operator: "in", 25 | }, 26 | ], 27 | }, 28 | ], 29 | }, 30 | }); 31 | console.log("Created account policy: ", policy.id); 32 | -------------------------------------------------------------------------------- /python/docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | %SPHINXBUILD% >NUL 2>NUL 14 | if errorlevel 9009 ( 15 | echo. 16 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 17 | echo.installed, then set the SPHINXBUILD environment variable to point 18 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 19 | echo.may add the Sphinx directory to PATH. 20 | echo. 21 | echo.If you don't have Sphinx installed, grab it from 22 | echo.https://www.sphinx-doc.org/ 23 | exit /b 1 24 | ) 25 | 26 | if "%1" == "" goto help 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /typescript/src/index.ts: -------------------------------------------------------------------------------- 1 | export { CdpClient } from "./client/cdp.js"; 2 | export type { EvmServerAccount, EvmSmartAccount } from "./accounts/evm/types.js"; 3 | export type { Policy } from "./policies/types.js"; 4 | export { 5 | CreatePolicyBodySchema, 6 | UpdatePolicyBodySchema, 7 | type CreatePolicyBody, 8 | type UpdatePolicyBody, 9 | } from "./policies/types.js"; 10 | export { NetworkError } from "./openapi-client/errors.js"; 11 | export type { SpendPermission, SpendPermissionInput } from "./spend-permissions/types.js"; 12 | export type { SpendPermissionNetwork, ListEndUsers200, EndUser } from "./openapi-client/index.js"; 13 | export type { ListEndUsersOptions } from "./client/end-user/endUser.types.js"; 14 | export { 15 | SPEND_PERMISSION_MANAGER_ABI as spendPermissionManagerAbi, 16 | SPEND_PERMISSION_MANAGER_ADDRESS as spendPermissionManagerAddress, 17 | } from "./spend-permissions/constants.js"; 18 | 19 | export { parseEther, parseUnits } from "viem"; 20 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.request_faucet.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.request_faucet.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from web3 import Web3 6 | from eth_account import Account 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() 10 | 11 | 12 | async def main(): 13 | async with CdpClient() as cdp: 14 | smart_account = await cdp.evm.create_smart_account(owner=Account.create()) 15 | print(f"Smart Account: {smart_account.address}") 16 | 17 | print("Requesting ETH from faucet for smart account...") 18 | faucet_hash = await smart_account.request_faucet( 19 | network="base-sepolia", 20 | token="eth", 21 | ) 22 | 23 | w3 = Web3(Web3.HTTPProvider("https://sepolia.base.org")) 24 | w3.eth.wait_for_transaction_receipt(faucet_hash) 25 | print("Received funds from faucet!") 26 | 27 | 28 | asyncio.run(main()) 29 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_abi_state_mutability.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.abi_state_mutability import AbiStateMutability 19 | 20 | class TestAbiStateMutability(unittest.TestCase): 21 | """AbiStateMutability unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testAbiStateMutability(self): 30 | """Test AbiStateMutability""" 31 | # inst = AbiStateMutability() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_o_auth2_provider_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.o_auth2_provider_type import OAuth2ProviderType 19 | 20 | class TestOAuth2ProviderType(unittest.TestCase): 21 | """OAuth2ProviderType unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testOAuth2ProviderType(self): 30 | """Test OAuth2ProviderType""" 31 | # inst = OAuth2ProviderType() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/createPrepareUserOperationPolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/createPrepareUserOperationPolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "PrepareUserOperation Example", 11 | rules: [ 12 | { 13 | action: "accept", 14 | operation: "prepareUserOperation", 15 | criteria: [ 16 | { 17 | type: "ethValue", 18 | ethValue: "1000000000000000000", 19 | operator: "<=", 20 | }, 21 | { 22 | type: "evmAddress", 23 | addresses: ["0x000000000000000000000000000000000000dEaD"], 24 | operator: "in", 25 | }, 26 | ], 27 | }, 28 | ], 29 | }, 30 | }); 31 | console.log("Created account policy: ", policy.id); 32 | -------------------------------------------------------------------------------- /.github/workflows/go_lint.yml: -------------------------------------------------------------------------------- 1 | name: Go Linting 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened, ready_for_review] 6 | 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | lint: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Harden the runner (Audit all outbound calls) 16 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 17 | with: 18 | egress-policy: audit 19 | 20 | - name: Checkout 21 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 22 | 23 | - name: Set up Go 24 | uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5.4.0 25 | with: 26 | go-version: "1.23" 27 | cache: true 28 | 29 | - name: Lint Go 30 | uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 31 | with: 32 | working-directory: ./go 33 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/deletePolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/deletePolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "Temporary Policy", 11 | rules: [ 12 | { 13 | action: "accept", 14 | operation: "signEvmTransaction", 15 | criteria: [ 16 | { 17 | type: "ethValue", 18 | ethValue: "1000000000000000000", 19 | operator: "<=", 20 | }, 21 | { 22 | type: "evmAddress", 23 | addresses: ["0x000000000000000000000000000000000000dEaD"], 24 | operator: "in", 25 | }, 26 | ], 27 | }, 28 | ], 29 | }, 30 | }); 31 | 32 | await cdp.policies.deletePolicy({ id: policy.id }); 33 | console.log("Deleted policy: ", policy.id); 34 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/prepareUserOperation.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/prepareUserOperation.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import { parseEther } from "viem"; 5 | import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; 6 | import "dotenv/config"; 7 | 8 | const cdp = new CdpClient(); 9 | 10 | const privateKey = generatePrivateKey(); 11 | const owner = privateKeyToAccount(privateKey); 12 | 13 | const smartAccount = await cdp.evm.createSmartAccount({ 14 | owner, 15 | }); 16 | 17 | const userOperation = await cdp.evm.prepareUserOperation({ 18 | smartAccount, 19 | network: "base-sepolia", 20 | calls: [ 21 | { 22 | to: "0x0000000000000000000000000000000000000000", 23 | value: parseEther("0"), 24 | data: "0x", 25 | // overrideGasLimit: "1000000", if you want to override the gas limit. 26 | }, 27 | ], 28 | }); 29 | 30 | console.log("User Operation:", userOperation); 31 | -------------------------------------------------------------------------------- /typescript/src/utils/uuidV4.ts: -------------------------------------------------------------------------------- 1 | import { createHash } from "crypto"; 2 | 3 | /** 4 | * Deterministically generates a UUIDv4 from a given input string. 5 | * This is necessary when we need to generate downstream idempotency keys for operations that have multiple calls. 6 | * 7 | * @param input - The input string to derive from 8 | * @param salt - Optional salt to append to the input (defaults to "salt") 9 | * @returns A UUIDv4 formatted string 10 | */ 11 | export function createDeterministicUuidV4(input: string, salt = "salt"): string { 12 | const hash = createHash("sha256") 13 | .update(input + "-" + salt) 14 | .digest("hex"); 15 | // Format as UUIDv4: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 16 | return [ 17 | hash.slice(0, 8), 18 | hash.slice(8, 12), 19 | "4" + hash.slice(13, 16), // Version 4 20 | ((parseInt(hash.slice(16, 17), 16) & 0x3) | 0x8).toString(16) + hash.slice(17, 20), // Variant bits 21 | hash.slice(20, 32), 22 | ].join("-"); 23 | } 24 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/x402_version.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class X402Version(int, Enum): 23 | """ 24 | The version of the x402 protocol. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | NUMBER_1 = 1 31 | NUMBER_2 = 2 32 | 33 | @classmethod 34 | def from_json(cls, json_str: str) -> Self: 35 | """Create an instance of X402Version from a JSON string""" 36 | return cls(json.loads(json_str)) 37 | 38 | 39 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_onramp_payment_link_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.onramp_payment_link_type import OnrampPaymentLinkType 19 | 20 | class TestOnrampPaymentLinkType(unittest.TestCase): 21 | """OnrampPaymentLinkType unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testOnrampPaymentLinkType(self): 30 | """Test OnrampPaymentLinkType""" 31 | # inst = OnrampPaymentLinkType() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_x402_settle_error_reason.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.x402_settle_error_reason import X402SettleErrorReason 19 | 20 | class TestX402SettleErrorReason(unittest.TestCase): 21 | """X402SettleErrorReason unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testX402SettleErrorReason(self): 30 | """Test X402SettleErrorReason""" 31 | # inst = X402SettleErrorReason() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/sendUserOperation.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/sendUserOperation.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | 5 | import { parseEther } from "viem"; 6 | import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; 7 | import "dotenv/config"; 8 | 9 | const cdp = new CdpClient(); 10 | 11 | const privateKey = generatePrivateKey(); 12 | const owner = privateKeyToAccount(privateKey); 13 | 14 | const smartAccount = await cdp.evm.createSmartAccount({ 15 | owner, 16 | }); 17 | 18 | const userOperationResult = await cdp.evm.sendUserOperation({ 19 | smartAccount, 20 | network: "base-sepolia", 21 | calls: [ 22 | { 23 | to: "0x0000000000000000000000000000000000000000", 24 | value: parseEther("0.000001"), 25 | data: "0x", 26 | // overrideGasLimit: "3000000", if you want to override the gas limit. 27 | }, 28 | ], 29 | }); 30 | 31 | console.log("User Operation Result:", userOperationResult); 32 | -------------------------------------------------------------------------------- /python/cdp/actions/evm/transfer/utils.py: -------------------------------------------------------------------------------- 1 | from typing import cast 2 | 3 | from eth_typing import HexStr 4 | 5 | # The address of an ERC20 token for a given network 6 | ADDRESS_MAP = { 7 | "base": { 8 | "usdc": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", 9 | }, 10 | "base-sepolia": { 11 | "usdc": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", 12 | }, 13 | } 14 | 15 | 16 | def get_erc20_address(token: str, network: str) -> HexStr: 17 | """Get the address of an ERC20 token for a given network. 18 | 19 | If a contract address is provided, it will not be found in the map and will be returned as is. 20 | 21 | Args: 22 | token: The token symbol or contract address 23 | network: The network to get the address for 24 | 25 | Returns: 26 | The address of the ERC20 token 27 | 28 | """ 29 | network_addresses = ADDRESS_MAP.get(network, {}) 30 | address = network_addresses.get(token, token) 31 | return cast(HexStr, address) 32 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_spend_permission_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.spend_permission_network import SpendPermissionNetwork 19 | 20 | class TestSpendPermissionNetwork(unittest.TestCase): 21 | """SpendPermissionNetwork unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testSpendPermissionNetwork(self): 30 | """Test SpendPermissionNetwork""" 31 | # inst = SpendPermissionNetwork() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/actions/evm/request_faucet.py: -------------------------------------------------------------------------------- 1 | from cdp.openapi_client.api.faucets_api import FaucetsApi 2 | from cdp.openapi_client.models.request_evm_faucet_request import RequestEvmFaucetRequest 3 | 4 | 5 | async def request_faucet( 6 | faucets: FaucetsApi, 7 | address: str, 8 | network: str, 9 | token: str, 10 | ) -> str: 11 | """Request a token from the faucet in the test network. 12 | 13 | Args: 14 | faucets (FaucetsApi): The faucets API. 15 | address (str): The address to request the faucet for. 16 | network (str): The network to request the faucet for. 17 | token (str): The token to request the faucet for. 18 | 19 | Returns: 20 | str: The transaction hash of the faucet request. 21 | 22 | """ 23 | response = await faucets.request_evm_faucet( 24 | request_evm_faucet_request=RequestEvmFaucetRequest( 25 | address=address, network=network, token=token 26 | ) 27 | ) 28 | return response.transaction_hash 29 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_evm_user_operation_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.evm_user_operation_network import EvmUserOperationNetwork 19 | 20 | class TestEvmUserOperationNetwork(unittest.TestCase): 21 | """EvmUserOperationNetwork unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testEvmUserOperationNetwork(self): 30 | """Test EvmUserOperationNetwork""" 31 | # inst = EvmUserOperationNetwork() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_x402_verify_invalid_reason.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.x402_verify_invalid_reason import X402VerifyInvalidReason 19 | 20 | class TestX402VerifyInvalidReason(unittest.TestCase): 21 | """X402VerifyInvalidReason unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testX402VerifyInvalidReason(self): 30 | """Test X402VerifyInvalidReason""" 31 | # inst = X402VerifyInvalidReason() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/getUserOperation.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/getUserOperation.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import { parseEther } from "viem"; 5 | import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; 6 | import "dotenv/config"; 7 | 8 | const cdp = new CdpClient(); 9 | 10 | const privateKey = generatePrivateKey(); 11 | const owner = privateKeyToAccount(privateKey); 12 | 13 | const smartAccount = await cdp.evm.createSmartAccount({ 14 | owner, 15 | }); 16 | 17 | const { userOpHash } = await cdp.evm.prepareUserOperation({ 18 | smartAccount, 19 | network: "base-sepolia", 20 | calls: [ 21 | { 22 | to: "0x0000000000000000000000000000000000000000", 23 | value: parseEther("0"), 24 | data: "0x", 25 | }, 26 | ], 27 | }); 28 | 29 | const userOperationResult = await cdp.evm.getUserOperation({ 30 | smartAccount, 31 | userOpHash, 32 | }); 33 | 34 | console.log("User Operation:", userOperationResult); 35 | -------------------------------------------------------------------------------- /examples/typescript/evm/token-balances/account.listTokenBalances.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/token-balances/account.listTokenBalances.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import { createPublicClient, http } from "viem"; 5 | import { baseSepolia } from "viem/chains"; 6 | import "dotenv/config"; 7 | 8 | const cdp = new CdpClient(); 9 | 10 | const account = await cdp.evm.getOrCreateAccount({ name: "MyAccount" }); 11 | 12 | const { transactionHash } = await account.requestFaucet({ 13 | network: "base-sepolia", 14 | token: "eth", 15 | }); 16 | 17 | await createPublicClient({ 18 | transport: http(), 19 | chain: baseSepolia, 20 | }).waitForTransactionReceipt({ 21 | hash: transactionHash, 22 | }); 23 | 24 | const result = await account.listTokenBalances({ 25 | network: "base-sepolia", 26 | }); 27 | 28 | for (const balance of result.balances) { 29 | console.log("Token contract address:", balance.token.contractAddress); 30 | console.log("Token balance:", balance.amount.amount); 31 | } 32 | -------------------------------------------------------------------------------- /.github/workflows/go_test.yml: -------------------------------------------------------------------------------- 1 | name: Go Tests 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened, ready_for_review] 6 | 7 | permissions: 8 | contents: read 9 | 10 | defaults: 11 | run: 12 | working-directory: ./go 13 | 14 | jobs: 15 | test: 16 | runs-on: ubuntu-latest 17 | 18 | strategy: 19 | matrix: 20 | go-version: ["1.23", "1.24"] 21 | 22 | steps: 23 | - name: Harden the runner (Audit all outbound calls) 24 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 25 | with: 26 | egress-policy: audit 27 | 28 | - name: Checkout 29 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 30 | 31 | - name: Set up Go 32 | uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5.4.0 33 | with: 34 | go-version: ${{ matrix.go-version }} 35 | cache: true 36 | 37 | - name: Run unit tests 38 | run: make test 39 | -------------------------------------------------------------------------------- /typescript/src/spend-permissions/utils.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from "vitest"; 2 | import { resolveTokenAddress } from "./utils.js"; 3 | import { UserInputValidationError } from "../errors.js"; 4 | 5 | describe("utils", () => { 6 | describe("resolveTokenAddress", () => { 7 | it("should resolve the token address for the given network", () => { 8 | expect(resolveTokenAddress("eth", "ethereum")).toBe( 9 | "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", 10 | ); 11 | expect(resolveTokenAddress("usdc", "base")).toBe( 12 | "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", 13 | ); 14 | expect(resolveTokenAddress("usdc", "base-sepolia")).toBe( 15 | "0x036CbD53842c5426634e7929541eC2318f3dCF7e", 16 | ); 17 | }); 18 | 19 | it("should throw an error if automatic address lookup for token is not supported on the network", () => { 20 | expect(() => resolveTokenAddress("usdc", "arbitrum")).toThrow(UserInputValidationError); 21 | }); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/smartAccount.signTypedData.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/smartAccount.signTypedData.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const owner = await cdp.evm.getOrCreateAccount({ 9 | name: "SignTypedData-Example-Owner", 10 | }); 11 | 12 | const smartAccount = await cdp.evm.getOrCreateSmartAccount({ 13 | owner, 14 | name: "SignTypedData-Example-SmartAccount", 15 | }); 16 | 17 | console.log("Created smart account:", smartAccount.address); 18 | 19 | const signature = await smartAccount.signTypedData({ 20 | domain: { 21 | name: "Test", 22 | chainId: 84532, 23 | verifyingContract: "0x0000000000000000000000000000000000000000", 24 | }, 25 | types: { 26 | Test: [{ name: "name", type: "string" }], 27 | }, 28 | primaryType: "Test", 29 | message: { 30 | name: "John Doe", 31 | }, 32 | network: "base-sepolia", 33 | }); 34 | 35 | console.log("Signature:", signature); 36 | -------------------------------------------------------------------------------- /typescript/src/errors.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, it, expect } from "vitest"; 2 | import { TimeoutError } from "./errors.js"; 3 | 4 | describe("TimeoutError", () => { 5 | it("should create an error with default message", () => { 6 | const error = new TimeoutError(); 7 | expect(error).toBeInstanceOf(Error); 8 | expect(error).toBeInstanceOf(TimeoutError); 9 | expect(error.message).toBe("Timeout Error"); 10 | expect(error.name).toBe("TimeoutError"); 11 | }); 12 | 13 | it("should create an error with custom message", () => { 14 | const customMessage = "Operation timed out after 5000ms"; 15 | const error = new TimeoutError(customMessage); 16 | expect(error).toBeInstanceOf(Error); 17 | expect(error).toBeInstanceOf(TimeoutError); 18 | expect(error.message).toBe(customMessage); 19 | expect(error.name).toBe("TimeoutError"); 20 | }); 21 | 22 | it("should capture stack trace", () => { 23 | const error = new TimeoutError(); 24 | expect(error.stack).toBeDefined(); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/o_auth2_provider_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class OAuth2ProviderType(str, Enum): 23 | """ 24 | The type of OAuth2 provider. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | GOOGLE = 'google' 31 | APPLE = 'apple' 32 | X = 'x' 33 | 34 | @classmethod 35 | def from_json(cls, json_str: str) -> Self: 36 | """Create an instance of OAuth2ProviderType from a JSON string""" 37 | return cls(json.loads(json_str)) 38 | 39 | 40 | -------------------------------------------------------------------------------- /examples/typescript/evm/transactions/baseAccount.transfer.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/transactions/baseAccount.transfer.ts 2 | 3 | import { CdpClient, parseEther } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.getOrCreateAccount({ 9 | name: "Playground-Account", 10 | }); 11 | 12 | const baseAccount = await account.useNetwork("base-sepolia"); 13 | 14 | const faucetTx = 15 | await baseAccount.requestFaucet({ 16 | token: "eth", 17 | }); 18 | 19 | await baseAccount.waitForTransactionReceipt(faucetTx); 20 | 21 | console.log("Faucet transaction receipt:", faucetTx); 22 | 23 | const transfer = await baseAccount.transfer({ 24 | to: "0x4252e0c9A3da5A2700e7d91cb50aEf522D0C6Fe8", 25 | amount: parseEther("0.000001"), 26 | token: "eth", 27 | }); 28 | 29 | console.log("Transaction hash:", transfer.transactionHash); 30 | 31 | const receipt = await baseAccount.waitForTransactionReceipt(transfer); 32 | 33 | console.log("Transaction receipt:", receipt); 34 | -------------------------------------------------------------------------------- /examples/typescript/solana/policies/createSplTokenLimitsPolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/policies/createSplTokenLimitsPolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | // Create a policy that allows sending up to 1 USDC on Solana devnet 9 | const policy = await cdp.policies.createPolicy({ 10 | policy: { 11 | scope: "account", 12 | description: "SPL Token Limits Policy", 13 | rules: [ 14 | { 15 | action: "accept", 16 | operation: "sendSolTransaction", 17 | criteria: [ 18 | { 19 | type: "splValue", 20 | splValue: "1000000", 21 | operator: "<=", 22 | }, 23 | { 24 | type: "mintAddress", 25 | addresses: ["4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"], 26 | operator: "in", 27 | }, 28 | ], 29 | }, 30 | ], 31 | }, 32 | }); 33 | console.log("Created spl token limits policy: ", policy.id); 34 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_list_evm_token_balances_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.list_evm_token_balances_network import ListEvmTokenBalancesNetwork 19 | 20 | class TestListEvmTokenBalancesNetwork(unittest.TestCase): 21 | """ListEvmTokenBalancesNetwork unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testListEvmTokenBalancesNetwork(self): 30 | """Test ListEvmTokenBalancesNetwork""" 31 | # inst = ListEvmTokenBalancesNetwork() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.quote_fund.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.quote_fund.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | account = await cdp.evm.create_account() 13 | smart_account = await cdp.evm.create_smart_account(owner=account) 14 | 15 | quote = await smart_account.quote_fund( 16 | network="base", 17 | token="usdc", 18 | amount=1000000, # 1 USDC 19 | ) 20 | 21 | # get details of the quote 22 | print(quote.fiat_amount) 23 | print(quote.token_amount) 24 | print(quote.token) 25 | print(quote.network) 26 | for fee in quote.fees: 27 | print(fee.type) # operation or network 28 | print(fee.amount) # amount in the token 29 | print(fee.currency) # currency of the amount 30 | 31 | 32 | asyncio.run(main()) -------------------------------------------------------------------------------- /examples/typescript/evm/policies/getPolicyById.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/getPolicyById.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "Project Policy", 11 | rules: [ 12 | { 13 | action: "accept", 14 | operation: "signEvmTransaction", 15 | criteria: [ 16 | { 17 | type: "ethValue", 18 | ethValue: "1000000000000000000", 19 | operator: "<=", 20 | }, 21 | { 22 | type: "evmAddress", 23 | addresses: ["0x000000000000000000000000000000000000dEaD"], 24 | operator: "in", 25 | }, 26 | ], 27 | }, 28 | ], 29 | }, 30 | }); 31 | 32 | const retrievedPolicy = await cdp.policies.getPolicyById({ 33 | id: policy.id, 34 | }); 35 | console.log("Retrieved policy: ", JSON.stringify(retrievedPolicy, null, 2)); 36 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/onramp_payment_link_type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class OnrampPaymentLinkType(str, Enum): 23 | """ 24 | The type of payment link. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | PAYMENT_LINK_TYPE_APPLE_PAY_BUTTON = 'PAYMENT_LINK_TYPE_APPLE_PAY_BUTTON' 31 | 32 | @classmethod 33 | def from_json(cls, json_str: str) -> Self: 34 | """Create an instance of OnrampPaymentLinkType from a JSON string""" 35 | return cls(json.loads(json_str)) 36 | 37 | 38 | -------------------------------------------------------------------------------- /rust/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.2.0] 9 | 10 | ### 🚀 Features 11 | 12 | - Support OAuth2 Embedded Wallet authentication 13 | - Add x402 V2 support 14 | 15 | ## [0.1.1] 16 | 17 | ### Patch Changes 18 | 19 | - Removed default audience claim from JWT generation 20 | 21 | ## [0.1.0] 22 | 23 | ### 🚀 Features 24 | 25 | - Initial release of CDP SDK for Rust 26 | - Complete EVM and Solana account management 27 | - JWT-based authentication with automatic middleware 28 | - Trait-based architecture for easy testing and mocking 29 | - Comprehensive mock implementations for all APIs 30 | - Type-safe OpenAPI client integration 31 | - Support for account creation, signing, and transaction management 32 | - Policy engine integration for operation controls 33 | 34 | 35 | -------------------------------------------------------------------------------- /python/cdp/actions/solana/request_faucet.py: -------------------------------------------------------------------------------- 1 | from cdp.openapi_client.api.faucets_api import FaucetsApi 2 | from cdp.openapi_client.models.request_solana_faucet200_response import ( 3 | RequestSolanaFaucet200Response as RequestSolanaFaucetResponse, 4 | ) 5 | from cdp.openapi_client.models.request_solana_faucet_request import RequestSolanaFaucetRequest 6 | 7 | 8 | async def request_faucet( 9 | faucets: FaucetsApi, 10 | address: str, 11 | token: str, 12 | ) -> RequestSolanaFaucetResponse: 13 | """Request a faucet for the Solana account. 14 | 15 | Args: 16 | faucets (FaucetsApi): The faucets API. 17 | address (str): The address of the Solana account. 18 | token (str): The token to request the faucet for. 19 | 20 | Returns: 21 | RequestSolanaFaucetResponse: The response from the faucet. 22 | 23 | """ 24 | return await faucets.request_solana_faucet( 25 | request_solana_faucet_request=RequestSolanaFaucetRequest( 26 | address=address, 27 | token=token, 28 | ) 29 | ) 30 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_list_solana_token_balances_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.list_solana_token_balances_network import ListSolanaTokenBalancesNetwork 19 | 20 | class TestListSolanaTokenBalancesNetwork(unittest.TestCase): 21 | """ListSolanaTokenBalancesNetwork unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testListSolanaTokenBalancesNetwork(self): 30 | """Test ListSolanaTokenBalancesNetwork""" 31 | # inst = ListSolanaTokenBalancesNetwork() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_onramp_order_payment_method_type_id.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.onramp_order_payment_method_type_id import OnrampOrderPaymentMethodTypeId 19 | 20 | class TestOnrampOrderPaymentMethodTypeId(unittest.TestCase): 21 | """OnrampOrderPaymentMethodTypeId unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testOnrampOrderPaymentMethodTypeId(self): 30 | """Test OnrampOrderPaymentMethodTypeId""" 31 | # inst = OnrampOrderPaymentMethodTypeId() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_onramp_quote_payment_method_type_id.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.onramp_quote_payment_method_type_id import OnrampQuotePaymentMethodTypeId 19 | 20 | class TestOnrampQuotePaymentMethodTypeId(unittest.TestCase): 21 | """OnrampQuotePaymentMethodTypeId unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testOnrampQuotePaymentMethodTypeId(self): 30 | """Test OnrampQuotePaymentMethodTypeId""" 31 | # inst = OnrampQuotePaymentMethodTypeId() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/get_or_create_smart_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/get_or_create_smart_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | # Create an owner account 14 | owner = await cdp.evm.create_account() 15 | print("Created owner account:", owner.address) 16 | 17 | # Create a smart account with the owner 18 | name = "MySmartAccount" 19 | account = await cdp.evm.get_or_create_smart_account(name=name, owner=owner) 20 | print("Smart Account Address: ", account.address) 21 | 22 | # Try to get the same smart account again - should return the existing one 23 | account2 = await cdp.evm.get_or_create_smart_account(name=name, owner=owner) 24 | print("Second Smart Account Address: ", account2.address) 25 | print("Are accounts equal? ", account.address == account2.address) 26 | 27 | asyncio.run(main()) 28 | -------------------------------------------------------------------------------- /typescript/src/errors.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * TimeoutError is thrown when an operation times out. 3 | */ 4 | export class TimeoutError extends Error { 5 | /** 6 | * Initializes a new TimeoutError instance. 7 | * 8 | * @param message - The error message. 9 | */ 10 | constructor(message: string = "Timeout Error") { 11 | super(message); 12 | this.name = "TimeoutError"; 13 | if (Error.captureStackTrace) { 14 | Error.captureStackTrace(this, TimeoutError); 15 | } 16 | } 17 | } 18 | 19 | /** 20 | * UserInputValidationError is thrown when validation of a user-supplied input fails. 21 | */ 22 | export class UserInputValidationError extends Error { 23 | /** 24 | * Initializes a new UserInputValidationError instance. 25 | * 26 | * @param message - The user input validation error message. 27 | */ 28 | constructor(message: string) { 29 | super(message); 30 | this.name = "UserInputValidationError"; 31 | if (Error.captureStackTrace) { 32 | Error.captureStackTrace(this, UserInputValidationError); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /python/cdp/actions/evm/transfer/constants.py: -------------------------------------------------------------------------------- 1 | """Constants for the transfer module.""" 2 | 3 | ERC20_ABI = [ 4 | { 5 | "constant": True, 6 | "inputs": [], 7 | "name": "decimals", 8 | "outputs": [{"name": "", "type": "uint8"}], 9 | "payable": False, 10 | "stateMutability": "view", 11 | "type": "function", 12 | }, 13 | { 14 | "constant": False, 15 | "inputs": [{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}], 16 | "name": "transfer", 17 | "outputs": [{"name": "", "type": "bool"}], 18 | "payable": False, 19 | "stateMutability": "nonpayable", 20 | "type": "function", 21 | }, 22 | { 23 | "constant": False, 24 | "inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}], 25 | "name": "approve", 26 | "outputs": [{"name": "", "type": "bool"}], 27 | "payable": False, 28 | "stateMutability": "nonpayable", 29 | "type": "function", 30 | }, 31 | ] 32 | -------------------------------------------------------------------------------- /python/cdp/actions/solana/send_transaction.py: -------------------------------------------------------------------------------- 1 | from cdp.openapi_client.api.solana_accounts_api import SolanaAccountsApi 2 | from cdp.openapi_client.models.send_solana_transaction_request import ( 3 | SendSolanaTransactionRequest, 4 | ) 5 | 6 | 7 | async def send_transaction( 8 | solana_accounts_api: SolanaAccountsApi, 9 | transaction: str, 10 | network: str, 11 | idempotency_key: str | None = None, 12 | ) -> str: 13 | """Send a Solana transaction. 14 | 15 | Args: 16 | solana_accounts_api (SolanaAccountsApi): The Solana accounts API. 17 | transaction (str): The transaction to send. 18 | network (str): The network to send the transaction to. 19 | idempotency_key (str, optional): The idempotency key. Defaults to None. 20 | 21 | """ 22 | return await solana_accounts_api.send_solana_transaction( 23 | send_solana_transaction_request=SendSolanaTransactionRequest( 24 | network=network, 25 | transaction=transaction, 26 | ), 27 | x_idempotency_key=idempotency_key, 28 | ) 29 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_x402_supported_payment_kind_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.models.x402_supported_payment_kind_network import X402SupportedPaymentKindNetwork 19 | 20 | class TestX402SupportedPaymentKindNetwork(unittest.TestCase): 21 | """X402SupportedPaymentKindNetwork unit test stubs""" 22 | 23 | def setUp(self): 24 | pass 25 | 26 | def tearDown(self): 27 | pass 28 | 29 | def testX402SupportedPaymentKindNetwork(self): 30 | """Test X402SupportedPaymentKindNetwork""" 31 | # inst = X402SupportedPaymentKindNetwork() 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /examples/rust/README.md: -------------------------------------------------------------------------------- 1 | # CDP SDK Examples 2 | 3 | ## Setup 4 | 5 | Follow these steps to get started: 6 | 7 | 1. Get a CDP API key and wallet secret from the [CDP Portal](https://portal.cdp.coinbase.com/access/api) 8 | 1. Fill in your API key and wallet secret in `.env.example`, then run `mv .env.example .env` 9 | 1. In the `examples/rust` folder, run `cargo check` to verify dependencies are installed 10 | 11 | ## Usage 12 | 13 | To run an example, use `cargo run --example` followed by the example name, for example: 14 | 15 | ```bash 16 | cargo run --example wallet_client 17 | ``` 18 | 19 | ## Available Examples 20 | 21 | - `wallet_client` - Basic wallet client initialization and usage 22 | - `evm_account_management` - EVM account creation and management 23 | - `evm_signing` - EVM transaction signing examples 24 | - `smart_account_management` - Smart account operations and management 25 | - `solana_account_management` - Solana account creation and management 26 | - `solana_signing` - Solana transaction signing examples 27 | - `token_balances` - Retrieving and displaying token balances -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/evm_swaps_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class EvmSwapsNetwork(str, Enum): 23 | """ 24 | The network on which to perform the swap. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | BASE = 'base' 31 | ETHEREUM = 'ethereum' 32 | ARBITRUM = 'arbitrum' 33 | OPTIMISM = 'optimism' 34 | 35 | @classmethod 36 | def from_json(cls, json_str: str) -> Self: 37 | """Create an instance of EvmSwapsNetwork from a JSON string""" 38 | return cls(json.loads(json_str)) 39 | 40 | 41 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/abi_state_mutability.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class AbiStateMutability(str, Enum): 23 | """ 24 | State mutability of a function in Solidity. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | PURE = 'pure' 31 | VIEW = 'view' 32 | NONPAYABLE = 'nonpayable' 33 | PAYABLE = 'payable' 34 | 35 | @classmethod 36 | def from_json(cls, json_str: str) -> Self: 37 | """Create an instance of AbiStateMutability from a JSON string""" 38 | return cls(json.loads(json_str)) 39 | 40 | 41 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/onramp_order_payment_method_type_id.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class OnrampOrderPaymentMethodTypeId(str, Enum): 23 | """ 24 | The type of payment method to be used to complete an onramp order. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | GUEST_CHECKOUT_APPLE_PAY = 'GUEST_CHECKOUT_APPLE_PAY' 31 | 32 | @classmethod 33 | def from_json(cls, json_str: str) -> Self: 34 | """Create an instance of OnrampOrderPaymentMethodTypeId from a JSON string""" 35 | return cls(json.loads(json_str)) 36 | 37 | 38 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/list_solana_token_balances_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class ListSolanaTokenBalancesNetwork(str, Enum): 23 | """ 24 | The name of the supported Solana networks in human-readable format. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | SOLANA = 'solana' 31 | SOLANA_MINUS_DEVNET = 'solana-devnet' 32 | 33 | @classmethod 34 | def from_json(cls, json_str: str) -> Self: 35 | """Create an instance of ListSolanaTokenBalancesNetwork from a JSON string""" 36 | return cls(json.loads(json_str)) 37 | 38 | 39 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/api/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | # import apis into api package 4 | from cdp.openapi_client.api.evm_accounts_api import EVMAccountsApi 5 | from cdp.openapi_client.api.evm_smart_accounts_api import EVMSmartAccountsApi 6 | from cdp.openapi_client.api.evm_swaps_api import EVMSwapsApi 7 | from cdp.openapi_client.api.evm_token_balances_api import EVMTokenBalancesApi 8 | from cdp.openapi_client.api.end_user_accounts_api import EndUserAccountsApi 9 | from cdp.openapi_client.api.faucets_api import FaucetsApi 10 | from cdp.openapi_client.api.onchain_data_api import OnchainDataApi 11 | from cdp.openapi_client.api.onramp_api import OnrampApi 12 | from cdp.openapi_client.api.policy_engine_api import PolicyEngineApi 13 | from cdp.openapi_client.api.sqlapi_alpha_api import SQLAPIAlphaApi 14 | from cdp.openapi_client.api.solana_accounts_api import SolanaAccountsApi 15 | from cdp.openapi_client.api.solana_token_balances_api import SolanaTokenBalancesApi 16 | from cdp.openapi_client.api.webhooks_api import WebhooksApi 17 | from cdp.openapi_client.api.x402_facilitator_api import X402FacilitatorApi 18 | 19 | -------------------------------------------------------------------------------- /examples/python/evm/fund/account.quote_fund.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/fund/account.quote_fund.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | account = await cdp.evm.get_or_create_account(name="account") 13 | 14 | quote = await account.quote_fund( 15 | network="base", 16 | token="eth", 17 | amount=500000000000000, # 0.0005 eth 18 | ) 19 | 20 | # get details of the quote 21 | print("Fiat amount: ", quote.fiat_amount) 22 | print("Fiat currency: ", quote.fiat_currency) 23 | print("Token amount: ", quote.token_amount) 24 | print("Token: ", quote.token) 25 | print("Network: ", quote.network) 26 | for fee in quote.fees: 27 | print("Fee type: ", fee.type) # operation or network 28 | print("Fee amount: ", fee.amount) # amount in the token 29 | print("Fee currency: ", fee.currency) # currency of the amount 30 | 31 | 32 | asyncio.run(main()) -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.wait_for_user_operation.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.wait_for_user_operation.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from cdp.evm_call_types import EncodedCall 6 | from eth_account import Account 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() 10 | 11 | 12 | async def main(): 13 | async with CdpClient() as cdp: 14 | smart_account = await cdp.evm.create_smart_account(owner=Account.create()) 15 | 16 | user_operation = await smart_account.send_user_operation( 17 | network="base-sepolia", 18 | calls=[ 19 | EncodedCall( 20 | to="0x0000000000000000000000000000000000000000", 21 | data="0x", 22 | value=0, 23 | ) 24 | ], 25 | ) 26 | 27 | user_op_result = await smart_account.wait_for_user_operation( 28 | user_op_hash=user_operation.user_op_hash, 29 | ) 30 | print("User Operation Result:", user_op_result) 31 | 32 | 33 | asyncio.run(main()) 34 | -------------------------------------------------------------------------------- /python/cdp/auth/__init__.py: -------------------------------------------------------------------------------- 1 | """Authentication package for the SDK. 2 | 3 | This package provides authentication utilities and JWT token handling functionality. 4 | """ 5 | 6 | from .clients.urllib3.client import Urllib3AuthClient, Urllib3AuthClientOptions 7 | from .utils.http import GetAuthHeadersOptions, get_auth_headers 8 | from .utils.jwt import ( 9 | JwtOptions, 10 | WalletJwtOptions, 11 | generate_jwt, 12 | generate_wallet_jwt, 13 | ) 14 | from .utils.ws import ( 15 | GetWebSocketAuthHeadersOptions, 16 | get_websocket_auth_headers, 17 | ) 18 | 19 | __all__ = [ 20 | "GetAuthHeadersOptions", 21 | "GetWebSocketAuthHeadersOptions", 22 | "JwtOptions", 23 | # Client exports 24 | "Urllib3AuthClient", 25 | "Urllib3AuthClientOptions", 26 | "WalletJwtOptions", 27 | # JWT utils exports 28 | "generate_jwt", 29 | "generate_wallet_jwt", 30 | # HTTP utils exports 31 | "get_auth_headers", 32 | # WebSocket utils exports 33 | "get_websocket_auth_headers", 34 | ] 35 | 36 | """CDP SDK Auth package.""" 37 | 38 | # Empty file to mark directory as Python package 39 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/list_evm_token_balances_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class ListEvmTokenBalancesNetwork(str, Enum): 23 | """ 24 | The name of the supported EVM networks in human-readable format. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | BASE = 'base' 31 | BASE_MINUS_SEPOLIA = 'base-sepolia' 32 | ETHEREUM = 'ethereum' 33 | 34 | @classmethod 35 | def from_json(cls, json_str: str) -> Self: 36 | """Create an instance of ListEvmTokenBalancesNetwork from a JSON string""" 37 | return cls(json.loads(json_str)) 38 | 39 | 40 | -------------------------------------------------------------------------------- /examples/typescript/end-users/listEndUsers.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx end-users/listEndUsers.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | try { 9 | // List 10 end users sorted by creation date in descending order 10 | const sortedResult = await cdp.endUser.listEndUsers({ 11 | pageSize: 10, 12 | sort: ["createdAt=desc"] 13 | }); 14 | 15 | console.log(`Found ${sortedResult.endUsers.length} end users`); 16 | for (const endUser of sortedResult.endUsers) { 17 | console.log(` - User ID: ${endUser.userId}`); 18 | console.log(` Authentication Methods: ${JSON.stringify(endUser.authenticationMethods)}`); 19 | console.log(` EVM Accounts: ${endUser.evmAccounts}`); 20 | console.log(` EVM Smart Accounts: ${endUser.evmSmartAccounts}`); 21 | console.log(` Solana Accounts: ${endUser.solanaAccounts}`); 22 | console.log(); 23 | } 24 | } catch (error) { 25 | console.error("Error listing end users: ", (error as { errorMessage: string }).errorMessage); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Coinbase 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/x402_supported_payment_kind_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class X402SupportedPaymentKindNetwork(str, Enum): 23 | """ 24 | The network of the blockchain. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | BASE_MINUS_SEPOLIA = 'base-sepolia' 31 | BASE = 'base' 32 | SOLANA_MINUS_DEVNET = 'solana-devnet' 33 | SOLANA = 'solana' 34 | 35 | @classmethod 36 | def from_json(cls, json_str: str) -> Self: 37 | """Create an instance of X402SupportedPaymentKindNetwork from a JSON string""" 38 | return cls(json.loads(json_str)) 39 | 40 | 41 | -------------------------------------------------------------------------------- /typescript/src/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Coinbase 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /examples/python/evm/transactions/transfer.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/transactions/transfer.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from eth_account import Account 6 | from dotenv import load_dotenv 7 | from web3 import Web3 8 | 9 | load_dotenv() 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.evm.get_or_create_account(name="MyAccount") 14 | 15 | faucet_tx = await account.request_faucet(network="base-sepolia", token="eth") 16 | 17 | # Wait for the faucet transaction to be confirmed 18 | w3 = Web3(Web3.HTTPProvider("https://sepolia.base.org")) 19 | w3.eth.wait_for_transaction_receipt(faucet_tx) 20 | 21 | print("Faucet transaction receipt:", faucet_tx) 22 | 23 | hash = await account.transfer( 24 | to="0x4252e0c9A3da5A2700e7d91cb50aEf522D0C6Fe8", 25 | amount=Web3.to_wei("0.000001", "ether"), 26 | token="eth", 27 | network="base-sepolia", 28 | ) 29 | 30 | print("Transaction hash:", hash) 31 | 32 | if __name__ == "__main__": 33 | asyncio.run(main()) -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_evm_token_balances_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.api.evm_token_balances_api import EVMTokenBalancesApi 19 | 20 | 21 | class TestEVMTokenBalancesApi(unittest.IsolatedAsyncioTestCase): 22 | """EVMTokenBalancesApi unit test stubs""" 23 | 24 | async def asyncSetUp(self) -> None: 25 | self.api = EVMTokenBalancesApi() 26 | 27 | async def asyncTearDown(self) -> None: 28 | await self.api.api_client.close() 29 | 30 | async def test_list_evm_token_balances(self) -> None: 31 | """Test case for list_evm_token_balances 32 | 33 | List EVM token balances 34 | """ 35 | pass 36 | 37 | 38 | if __name__ == '__main__': 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/smartAccount.listTokenBalances.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/smartAccount.listTokenBalances.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import { createPublicClient, http } from "viem"; 5 | import { baseSepolia } from "viem/chains"; 6 | import "dotenv/config"; 7 | 8 | const cdp = new CdpClient(); 9 | 10 | const account = await cdp.evm.getOrCreateAccount({ name: "MyAccount" }); 11 | const smartAccount = await cdp.evm.createSmartAccount({ 12 | owner: account, 13 | }); 14 | 15 | const { transactionHash } = await cdp.evm.requestFaucet({ 16 | address: smartAccount.address, 17 | network: "base-sepolia", 18 | token: "eth", 19 | }); 20 | 21 | await createPublicClient({ 22 | transport: http(), 23 | chain: baseSepolia, 24 | }).waitForTransactionReceipt({ 25 | hash: transactionHash, 26 | }); 27 | 28 | const result = await smartAccount.listTokenBalances({ 29 | network: "base-sepolia", 30 | }); 31 | 32 | for (const balance of result.balances) { 33 | console.log("Token contract address:", balance.token.contractAddress); 34 | console.log("Token balance:", balance.amount.amount); 35 | } 36 | -------------------------------------------------------------------------------- /go/.golangci.yaml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | run: 3 | issues-exit-code: 1 4 | linters: 5 | default: none 6 | enable: 7 | - errcheck 8 | - govet 9 | - ineffassign 10 | - revive 11 | - staticcheck 12 | - unused 13 | - godot 14 | settings: 15 | perfsprint: 16 | strconcat: false 17 | godot: 18 | scope: declarations 19 | exclusions: 20 | generated: lax 21 | presets: 22 | - comments 23 | - common-false-positives 24 | - legacy 25 | - std-error-handling 26 | rules: 27 | - linters: 28 | - godox 29 | text: 'Line contains TODO/BUG/FIXME:' 30 | - linters: 31 | - dupl 32 | - funlen 33 | - gochecknoglobals 34 | - maintidx 35 | - scopelint 36 | - testpackage 37 | - wrapcheck 38 | path: _test\.go 39 | paths: 40 | - third_party$ 41 | - builtin$ 42 | - examples$ 43 | issues: 44 | max-same-issues: 0 45 | formatters: 46 | enable: 47 | - gofmt 48 | exclusions: 49 | generated: lax 50 | paths: 51 | - third_party$ 52 | - builtin$ 53 | - examples$ 54 | -------------------------------------------------------------------------------- /python/docs/cdp.auth.test.rst: -------------------------------------------------------------------------------- 1 | cdp.auth.test package 2 | ===================== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | :maxdepth: 4 9 | 10 | cdp.auth.test.factories 11 | 12 | Submodules 13 | ---------- 14 | 15 | cdp.auth.test.test\_client module 16 | --------------------------------- 17 | 18 | .. automodule:: cdp.auth.test.test_client 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | cdp.auth.test.test\_http module 24 | ------------------------------- 25 | 26 | .. automodule:: cdp.auth.test.test_http 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | cdp.auth.test.test\_jwt module 32 | ------------------------------ 33 | 34 | .. automodule:: cdp.auth.test.test_jwt 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | cdp.auth.test.test\_ws module 40 | ----------------------------- 41 | 42 | .. automodule:: cdp.auth.test.test_ws 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | Module contents 48 | --------------- 49 | 50 | .. automodule:: cdp.auth.test 51 | :members: 52 | :undoc-members: 53 | :show-inheritance: 54 | -------------------------------------------------------------------------------- /typescript/src/accounts/evm/networkToChainResolver.ts: -------------------------------------------------------------------------------- 1 | import * as chains from "viem/chains"; 2 | 3 | import type { Chain } from "viem"; 4 | 5 | /** 6 | * Network identifier to viem chain mapping 7 | */ 8 | export const NETWORK_TO_CHAIN_MAP: Record = { 9 | base: chains.base, 10 | "base-sepolia": chains.baseSepolia, 11 | ethereum: chains.mainnet, 12 | "ethereum-sepolia": chains.sepolia, 13 | polygon: chains.polygon, 14 | "polygon-mumbai": chains.polygonMumbai, 15 | arbitrum: chains.arbitrum, 16 | "arbitrum-sepolia": chains.arbitrumSepolia, 17 | optimism: chains.optimism, 18 | "optimism-sepolia": chains.optimismSepolia, 19 | }; 20 | 21 | /** 22 | * Resolves a network identifier to a viem chain 23 | * 24 | * @param network - The network identifier to resolve 25 | * @returns The resolved viem chain 26 | * @throws Error if the network identifier is not supported 27 | */ 28 | export function resolveNetworkToChain(network: string): Chain { 29 | const chain = NETWORK_TO_CHAIN_MAP[network.toLowerCase()]; 30 | if (!chain) { 31 | throw new Error(`Unsupported network identifier: ${network}`); 32 | } 33 | return chain; 34 | } 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_solana_token_balances_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.api.solana_token_balances_api import SolanaTokenBalancesApi 19 | 20 | 21 | class TestSolanaTokenBalancesApi(unittest.IsolatedAsyncioTestCase): 22 | """SolanaTokenBalancesApi unit test stubs""" 23 | 24 | async def asyncSetUp(self) -> None: 25 | self.api = SolanaTokenBalancesApi() 26 | 27 | async def asyncTearDown(self) -> None: 28 | await self.api.api_client.close() 29 | 30 | async def test_list_solana_token_balances(self) -> None: 31 | """Test case for list_solana_token_balances 32 | 33 | List Solana token balances 34 | """ 35 | pass 36 | 37 | 38 | if __name__ == '__main__': 39 | unittest.main() 40 | -------------------------------------------------------------------------------- /python/cdp/constants.py: -------------------------------------------------------------------------------- 1 | """Specifies package level constants used throughout the package.""" 2 | 3 | # SDK_DEFAULT_SOURCE (str): Denotes the default source for the Python SDK. 4 | SDK_DEFAULT_SOURCE = "sdk" 5 | 6 | """The public RSA key used to encrypt the private key when importing an EVM or Solana account.""" 7 | ImportAccountPublicRSAKey = """-----BEGIN PUBLIC KEY----- 8 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2Fxydgm/ryYk0IexQIuL 9 | 9DKyiIk2WmS36AZ83a9Z0QX53qdveg08b05g1Qr+o+COoYOT/FDi8anRGAs7rIyS 10 | uigrjHR6VrmFjnGrrTr3MINwC9cYQFHwET8YVGRq+BB3iFTB1kIb9XJ/vT2sk1xP 11 | hJ6JihEwSl4DgbeVjqw59wYqrNg355oa8EdFqkmfGU2tpbM56F8iv1F+shwkGo3y 12 | GhW/UOQ5OLauXvsqo8ranwsK+lqFblLEMlNtn1VSJeO2vMxryeKFrY2ob8VqGchC 13 | ftPJiLWs2Du6juw4C1rOWwSMlXzZ6cNMHkxdTcEHMr3C2TEHgzjZY41whMwNTB8q 14 | /pxXnIbH77caaviRs4R/POe8cSsznalXj85LULvFWOIHp0w+jEYSii9Rp9XtHWAH 15 | nrK/O/SVDtT1ohp2F+Zg1mojTgKfLOyGdOUXTi95naDTuG770rSjHdL80tJBz1Fd 16 | +1pzGTGXGHLZQLX5YZm5iuy2cebWfF09VjIoCIlDB2++tr4M+O0Z1X1ZE0J5Ackq 17 | rOluAFalaKynyH3KMyRg+NuLmibu5OmcMjCLK3D4X1YLiN2OK8/bbpEL8JYroDwb 18 | EXIUW5mGS06YxfSUsxHzL9Tj00+GMm/Gvl0+4/+Vn8IXVHjQOSPNEy3EnqCiH/OW 19 | 8v0IMC32CeGrX7mGbU+MzlsCAwEAAQ== 20 | -----END PUBLIC KEY-----""" 21 | -------------------------------------------------------------------------------- /typescript/src/constants.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * The URL to the Coinbase CDP API error docs page. 3 | */ 4 | export const ERROR_DOCS_PAGE_URL = "https://docs.cdp.coinbase.com/api-reference/v2/errors"; 5 | 6 | /** 7 | * The public RSA key used to encrypt the private key when importing an EVM or Solana account. 8 | */ 9 | export const ImportAccountPublicRSAKey = `-----BEGIN PUBLIC KEY----- 10 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA2Fxydgm/ryYk0IexQIuL 11 | 9DKyiIk2WmS36AZ83a9Z0QX53qdveg08b05g1Qr+o+COoYOT/FDi8anRGAs7rIyS 12 | uigrjHR6VrmFjnGrrTr3MINwC9cYQFHwET8YVGRq+BB3iFTB1kIb9XJ/vT2sk1xP 13 | hJ6JihEwSl4DgbeVjqw59wYqrNg355oa8EdFqkmfGU2tpbM56F8iv1F+shwkGo3y 14 | GhW/UOQ5OLauXvsqo8ranwsK+lqFblLEMlNtn1VSJeO2vMxryeKFrY2ob8VqGchC 15 | ftPJiLWs2Du6juw4C1rOWwSMlXzZ6cNMHkxdTcEHMr3C2TEHgzjZY41whMwNTB8q 16 | /pxXnIbH77caaviRs4R/POe8cSsznalXj85LULvFWOIHp0w+jEYSii9Rp9XtHWAH 17 | nrK/O/SVDtT1ohp2F+Zg1mojTgKfLOyGdOUXTi95naDTuG770rSjHdL80tJBz1Fd 18 | +1pzGTGXGHLZQLX5YZm5iuy2cebWfF09VjIoCIlDB2++tr4M+O0Z1X1ZE0J5Ackq 19 | rOluAFalaKynyH3KMyRg+NuLmibu5OmcMjCLK3D4X1YLiN2OK8/bbpEL8JYroDwb 20 | EXIUW5mGS06YxfSUsxHzL9Tj00+GMm/Gvl0+4/+Vn8IXVHjQOSPNEy3EnqCiH/OW 21 | 8v0IMC32CeGrX7mGbU+MzlsCAwEAAQ== 22 | -----END PUBLIC KEY-----`; 23 | -------------------------------------------------------------------------------- /examples/python/evm/accounts/get_or_create_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/accounts/get_or_create_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | # Single account creation example 14 | name = "Account1" 15 | account = await cdp.evm.get_or_create_account(name=name) 16 | print("Account Address: ", account.address) 17 | account2 = await cdp.evm.get_or_create_account(name=name) 18 | print("Account 2 Address: ", account2.address) 19 | print("Are accounts equal? ", account.address == account2.address) 20 | 21 | # Concurrent account creation example 22 | account_coros = [ 23 | cdp.evm.get_or_create_account(name="Account"), 24 | cdp.evm.get_or_create_account(name="Account"), 25 | cdp.evm.get_or_create_account(name="Account"), 26 | ] 27 | accounts = await asyncio.gather(*account_coros) 28 | for i, acc in enumerate(accounts, 1): 29 | print(f"EVM Account Address {i + 1}: ", acc.address) 30 | 31 | 32 | asyncio.run(main()) 33 | -------------------------------------------------------------------------------- /python/cdp/actions/solana/sign_message.py: -------------------------------------------------------------------------------- 1 | from cdp.openapi_client.api.solana_accounts_api import SolanaAccountsApi 2 | from cdp.openapi_client.models.sign_solana_message200_response import ( 3 | SignSolanaMessage200Response as SignSolanaMessageResponse, 4 | ) 5 | from cdp.openapi_client.models.sign_solana_message_request import SignSolanaMessageRequest 6 | 7 | 8 | async def sign_message( 9 | solana_accounts_api: SolanaAccountsApi, 10 | address: str, 11 | message: str, 12 | idempotency_key: str, 13 | ) -> SignSolanaMessageResponse: 14 | """Sign a message. 15 | 16 | Args: 17 | solana_accounts_api (SolanaAccountsApi): The Solana accounts API. 18 | address (str): The address of the Solana account. 19 | message (str): The message to sign. 20 | idempotency_key (str): The idempotency key. 21 | 22 | Returns: 23 | SignSolanaMessageResponse: The signature of the message. 24 | 25 | """ 26 | return await solana_accounts_api.sign_solana_message( 27 | sign_solana_message_request=SignSolanaMessageRequest( 28 | message=message, 29 | ), 30 | address=address, 31 | x_idempotency_key=idempotency_key, 32 | ) 33 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/onramp_quote_payment_method_type_id.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class OnrampQuotePaymentMethodTypeId(str, Enum): 23 | """ 24 | The type of payment method used to generate the onramp quote. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | CARD = 'CARD' 31 | ACH = 'ACH' 32 | APPLE_PAY = 'APPLE_PAY' 33 | PAYPAL = 'PAYPAL' 34 | FIAT_WALLET = 'FIAT_WALLET' 35 | CRYPTO_WALLET = 'CRYPTO_WALLET' 36 | 37 | @classmethod 38 | def from_json(cls, json_str: str) -> Self: 39 | """Create an instance of OnrampQuotePaymentMethodTypeId from a JSON string""" 40 | return cls(json.loads(json_str)) 41 | 42 | 43 | -------------------------------------------------------------------------------- /typescript/src/accounts/evm/chainToNetworkMapper.ts: -------------------------------------------------------------------------------- 1 | import type { KnownEvmNetworks } from "./types.js"; 2 | import type { Chain } from "viem"; 3 | 4 | /** 5 | * Maps a viem chain to a Coinbase network identifier. 6 | * This function only supports the networks defined in KnownEvmNetworks. 7 | * 8 | * @param chain - The viem chain object 9 | * @returns The Coinbase network identifier, or undefined if the chain is not supported 10 | */ 11 | export function mapChainToNetwork(chain: Chain): KnownEvmNetworks | undefined { 12 | // Map chain IDs to Coinbase network identifiers 13 | const chainIdToNetwork: Record = { 14 | // Ethereum networks 15 | 1: "ethereum", 16 | 11155111: "ethereum-sepolia", 17 | 17000: "ethereum-hoodi", // Holesky 18 | 19 | // Base networks 20 | 8453: "base", 21 | 84532: "base-sepolia", 22 | 23 | // Polygon networks 24 | 137: "polygon", 25 | 80001: "polygon-mumbai", 26 | 27 | // Arbitrum networks 28 | 42161: "arbitrum", 29 | 421614: "arbitrum-sepolia", 30 | 31 | // Optimism networks 32 | 10: "optimism", 33 | 11155420: "optimism-sepolia", 34 | }; 35 | 36 | return chainIdToNetwork[chain.id]; 37 | } 38 | -------------------------------------------------------------------------------- /typescript/patches/@orval__core@7.6.0.patch: -------------------------------------------------------------------------------- 1 | diff --git a/dist/index.js b/dist/index.js 2 | index 33ba2243e40324b31761ace9acb19723775151c4..fd7db963918280a2331a91512ad4f24e0f34814a 100644 3 | --- a/dist/index.js 4 | +++ b/dist/index.js 5 | @@ -51405,7 +51405,7 @@ var generateDependency = ({ 6 | } 7 | importString += `import ${onlyTypes ? "type " : ""}${defaultDep ? `${defaultDep.name}${depsString ? "," : ""}` : ""}${depsString ? `{ 8 | ${depsString} 9 | -}` : ""} from '${dependency}${key !== "default" && specsName[key] ? `/${specsName[key]}` : ""}';`; 10 | +}` : ""} from '${dependency}${key !== "default" && specsName[key] ? `/${specsName[key]}` : ""}${dependency.includes('coinbaseDeveloperPlatformAPIs.schemas') ? '.js' : ''}';`; 11 | return importString; 12 | }; 13 | var addDependency = ({ 14 | @@ -53088,7 +53088,7 @@ ${implementationMock}`; 15 | tag, 16 | tag + "." + getMockFileExtensionByTypeName(output.mock) 17 | ); 18 | - import_fs_extra5.default.appendFile(indexFilePath, `export * from '${localMockPath}' 19 | + import_fs_extra5.default.appendFile(indexFilePath, `export * from '${localMockPath}.js' 20 | `); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /python/cdp/evm_message_types.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa: N815 2 | # Ignoring mixed case because underlying library type uses camelCase 3 | 4 | from typing import Any 5 | 6 | from pydantic import BaseModel, Field 7 | 8 | 9 | class EIP712Domain(BaseModel): 10 | """The domain of the EIP-712 typed data.""" 11 | 12 | model_config = {"populate_by_name": True} 13 | 14 | name: str | None = Field(default=None, description="The name of the DApp or protocol.") 15 | version: str | None = Field(default=None, description="The version of the DApp or protocol.") 16 | chain_id: int | None = Field( 17 | default=None, description="The chain ID of the EVM network.", alias="chainId" 18 | ) 19 | verifying_contract: str | None = Field( 20 | default=None, 21 | description="The 0x-prefixed EVM address of the verifying smart contract.", 22 | alias="verifyingContract", 23 | ) 24 | salt: str | None = Field( 25 | default=None, description="The optional 32-byte 0x-prefixed hex salt for domain separation." 26 | ) 27 | 28 | def as_dict(self) -> dict[str, Any]: 29 | """Serialize the EIP712Domain object to a dictionary.""" 30 | return self.model_dump(by_alias=True) 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | *.so 6 | .Python 7 | build/ 8 | develop-eggs/ 9 | dist/ 10 | downloads/ 11 | eggs/ 12 | .eggs/ 13 | lib/ 14 | lib64/ 15 | parts/ 16 | sdist/ 17 | var/ 18 | wheels/ 19 | *.egg-info/ 20 | .installed.cfg 21 | *.egg 22 | MANIFEST 23 | .pytest_cache/ 24 | .coverage 25 | htmlcov/ 26 | .env 27 | .venv 28 | venv/ 29 | ENV/ 30 | **/.openapi-generator-ignore 31 | **/.openapi-generator/ 32 | 33 | # Sphinx 34 | _build 35 | _static 36 | _templates 37 | 38 | 39 | # Node 40 | node_modules/ 41 | npm-debug.log* 42 | yarn-debug.log* 43 | yarn-error.log* 44 | .env 45 | .env.test 46 | .env.production 47 | coverage/ 48 | dist/ 49 | build/ 50 | .next 51 | out/ 52 | .DS_Store 53 | *.pem 54 | .vercel 55 | .turbo 56 | _cjs 57 | _esm 58 | _types 59 | 60 | # TypeScript 61 | *.tsbuildinfo 62 | typescript/docs 63 | typescript/docs-md 64 | 65 | # Go 66 | *.exe 67 | *.exe~ 68 | *.dll 69 | *.so 70 | *.dylib 71 | *.test 72 | *.out 73 | go.work 74 | vendor/ 75 | go/docs 76 | 77 | # OpenAPI 78 | openapi-preprocessed.yaml 79 | openapi_preprocessed.yaml 80 | 81 | # IDE / OS 82 | .idea/ 83 | .vscode/ 84 | .*.sw? 85 | .DS_Store 86 | 87 | # Build Output 88 | target/ 89 | 90 | # Env files 91 | **/.env 92 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.get_user_operation.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.get_user_operation.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from cdp.evm_call_types import EncodedCall 6 | from eth_account import Account 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() 10 | 11 | 12 | async def main(): 13 | async with CdpClient() as cdp: 14 | smart_account = await cdp.evm.create_smart_account(owner=Account.create()) 15 | 16 | user_operation = await smart_account.send_user_operation( 17 | network="base-sepolia", 18 | calls=[ 19 | EncodedCall( 20 | to="0x0000000000000000000000000000000000000000", 21 | data="0x", 22 | value=0, 23 | ) 24 | ], 25 | ) 26 | 27 | await smart_account.wait_for_user_operation( 28 | user_op_hash=user_operation.user_op_hash, 29 | ) 30 | 31 | user_op = await smart_account.get_user_operation( 32 | user_op_hash=user_operation.user_op_hash, 33 | ) 34 | print("User Operation Result:", user_op) 35 | 36 | 37 | asyncio.run(main()) 38 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.list_token_balances.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.list_token_balances.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from web3 import Web3 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | account = await cdp.evm.get_or_create_account(name="MyAccount") 14 | smart_account = await cdp.evm.create_smart_account(owner=account) 15 | 16 | transaction_hash = await cdp.evm.request_faucet( 17 | address=smart_account.address, 18 | network="base-sepolia", 19 | token="eth", 20 | ) 21 | w3 = Web3(Web3.HTTPProvider("https://sepolia.base.org")) 22 | w3.eth.wait_for_transaction_receipt(transaction_hash) 23 | 24 | balances = await smart_account.list_token_balances( 25 | network="base-sepolia", 26 | page_size=10, 27 | ) 28 | 29 | for balance in balances.balances: 30 | print(f"Token contract address: {balance.token.contract_address}") 31 | print(f"Token balance: {balance.amount.amount}") 32 | 33 | 34 | asyncio.run(main()) 35 | -------------------------------------------------------------------------------- /examples/python/solana/accounts/get_or_create_account.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python solana/accounts/get_or_create_account.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | 8 | load_dotenv() 9 | 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | # Single account creation example 14 | name = "Account" 15 | account = await cdp.solana.get_or_create_account(name=name) 16 | print("Account Address: ", account.address) 17 | account2 = await cdp.solana.get_or_create_account(name=name) 18 | print("Account 2 Address: ", account2.address) 19 | print("Are accounts equal? ", account.address == account2.address) 20 | 21 | # Concurrent account creation example 22 | account_coros = [ 23 | cdp.solana.get_or_create_account(name="Account"), 24 | cdp.solana.get_or_create_account(name="Account"), 25 | cdp.solana.get_or_create_account(name="Account"), 26 | ] 27 | accounts = await asyncio.gather(*account_coros) 28 | for i, acc in enumerate(accounts, 1): 29 | print(f"Solana Account Address {i + 1}: ", acc.address) 30 | 31 | 32 | asyncio.run(main()) 33 | -------------------------------------------------------------------------------- /examples/typescript/evm/accounts/getOrCreateAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/accounts/getOrCreateAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | // Get or create an account 9 | const name = "Account1"; 10 | const account = await cdp.evm.getOrCreateAccount({ name }); 11 | console.log("EVM Account Address: ", account.address); 12 | 13 | const account2 = await cdp.evm.getOrCreateAccount({ name }); 14 | console.log("EVM Account 2 Address: ", account2.address); 15 | 16 | const areAccountsEqual = account.address === account2.address; 17 | console.log("Are accounts equal? ", areAccountsEqual); 18 | 19 | const accountPromise1 = cdp.evm.getOrCreateAccount({ name: "Account" }); 20 | const accountPromise2 = cdp.evm.getOrCreateAccount({ name: "Account" }); 21 | const accountPromise3 = cdp.evm.getOrCreateAccount({ name: "Account" }); 22 | Promise.all([accountPromise1, accountPromise2, accountPromise3]).then( 23 | ([account1, account2, account3]) => { 24 | console.log("EVM Account Address 1: ", account1.address); 25 | console.log("EVM Account Address 2: ", account2.address); 26 | console.log("EVM Account Address 3: ", account3.address); 27 | } 28 | ); 29 | -------------------------------------------------------------------------------- /examples/python/solana/policies/create_sol_message_policy.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python solana/policies/create_sol_message_policy.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | from cdp.policies.types import ( 8 | CreatePolicyOptions, 9 | SignSolMessageRule, 10 | SolMessageCriterion, 11 | ) 12 | 13 | load_dotenv() 14 | 15 | async def main(): 16 | async with CdpClient() as cdp: 17 | # Create a policy that only allows signing messages starting with "CDP:" 18 | policy = CreatePolicyOptions( 19 | scope="account", 20 | description="Allow messages with CDP prefix only", 21 | rules=[ 22 | SignSolMessageRule( 23 | action="accept", 24 | criteria=[ 25 | SolMessageCriterion( 26 | type="solMessage", 27 | match="^CDP:.*", 28 | ), 29 | ], 30 | ), 31 | ], 32 | ) 33 | 34 | result = await cdp.policies.create_policy(policy=policy) 35 | 36 | print("Created sol message policy: ", result.id) 37 | 38 | 39 | asyncio.run(main()) 40 | -------------------------------------------------------------------------------- /examples/python/end_user/create_end_user.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python end_user/create_end_user.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from cdp.openapi_client.models.authentication_method import AuthenticationMethod 7 | from cdp.openapi_client.models.create_end_user_request_evm_account import ( 8 | CreateEndUserRequestEvmAccount, 9 | ) 10 | from cdp.openapi_client.models.email_authentication import EmailAuthentication 11 | from dotenv import load_dotenv 12 | 13 | load_dotenv() 14 | 15 | 16 | async def main(): 17 | async with CdpClient() as cdp: 18 | try: 19 | # Create an end user with an email authentication method and an EVM account. 20 | end_user = await cdp.end_user.create_end_user( 21 | authentication_methods=[ 22 | AuthenticationMethod(EmailAuthentication(type="email", email="user@example.com")) 23 | ], 24 | evm_account=CreateEndUserRequestEvmAccount(create_smart_account=False), 25 | ) 26 | 27 | print("Created end user:", end_user) 28 | 29 | except Exception as e: 30 | print(f"Error creating end user: {e}") 31 | raise e 32 | 33 | 34 | asyncio.run(main()) 35 | 36 | -------------------------------------------------------------------------------- /examples/python/end_user/list_end_users.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python end_user/list_end_users.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | try: 13 | # List all end users with 10 per page and sorted by creation date in descending order 14 | result = await cdp.end_user.list_end_users( 15 | page_size=10, 16 | sort=["createdAt=desc"] 17 | ) 18 | 19 | print(f"Found {len(result.end_users)} end users") 20 | for end_user in result.end_users: 21 | print(f" - User ID: {end_user.user_id}") 22 | print(f" Authentication Methods: {end_user.authentication_methods}") 23 | print(f" EVM Accounts: {end_user.evm_accounts}") 24 | print(f" EVM Smart Accounts: {end_user.evm_smart_accounts}") 25 | print(f" Solana Accounts: {end_user.solana_accounts}") 26 | print() 27 | 28 | except Exception as e: 29 | print(f"Error listing end users: {e}") 30 | raise e 31 | 32 | 33 | asyncio.run(main()) 34 | 35 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/spend_permission_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class SpendPermissionNetwork(str, Enum): 23 | """ 24 | The network the spend permission is on. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | BASE = 'base' 31 | BASE_MINUS_SEPOLIA = 'base-sepolia' 32 | ETHEREUM = 'ethereum' 33 | ETHEREUM_MINUS_SEPOLIA = 'ethereum-sepolia' 34 | OPTIMISM = 'optimism' 35 | ARBITRUM = 'arbitrum' 36 | AVALANCHE = 'avalanche' 37 | POLYGON = 'polygon' 38 | 39 | @classmethod 40 | def from_json(cls, json_str: str) -> Self: 41 | """Create an instance of SpendPermissionNetwork from a JSON string""" 42 | return cls(json.loads(json_str)) 43 | 44 | 45 | -------------------------------------------------------------------------------- /examples/python/evm/policies/delete_policy.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/policies/delete_policy.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | from cdp.policies.types import CreatePolicyOptions, EthValueCriterion, SignEvmTransactionRule 8 | 9 | load_dotenv() 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | policy = CreatePolicyOptions( 14 | scope="account", 15 | description="Temporary Policy", 16 | rules=[ 17 | SignEvmTransactionRule( 18 | action="accept", 19 | criteria=[ 20 | EthValueCriterion( 21 | ethValue="1000000000000000000", 22 | operator="<=", 23 | ), 24 | ], 25 | ) 26 | ], 27 | ) 28 | 29 | result = await cdp.policies.create_policy(policy=policy) 30 | print("Created account policy: ", result.id) 31 | 32 | print("Deleting account policy: ", result.id) 33 | await cdp.policies.delete_policy(id=result.id) 34 | print("Deleted account policy: ", result.id) 35 | 36 | 37 | asyncio.run(main()) 38 | -------------------------------------------------------------------------------- /examples/python/evm/policies/get_policy_by_id.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/policies/get_policy_by_id.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | from cdp.policies.types import CreatePolicyOptions, EthValueCriterion, SignEvmTransactionRule 8 | 9 | load_dotenv() 10 | 11 | async def main(): 12 | async with CdpClient() as cdp: 13 | policy = CreatePolicyOptions( 14 | scope="account", 15 | description="Account Allowlist Example", 16 | rules=[ 17 | SignEvmTransactionRule( 18 | action="accept", 19 | criteria=[ 20 | EthValueCriterion( 21 | ethValue="1000000000000000000", 22 | operator="<=", 23 | ), 24 | ], 25 | ) 26 | ], 27 | ) 28 | result = await cdp.policies.create_policy(policy=policy) 29 | print("Created policy: ", result) 30 | 31 | print("Retrieving policy by id: ", result.id) 32 | policy = await cdp.policies.get_policy_by_id(result.id) 33 | print("Retrieved policy: ", policy) 34 | 35 | 36 | asyncio.run(main()) 37 | -------------------------------------------------------------------------------- /examples/typescript/solana/accounts/getOrCreateAccount.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx solana/accounts/getOrCreateAccount.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.solana.getOrCreateAccount({ name: "Account1" }); 9 | console.log("Account:", JSON.stringify(account, null, 2)); 10 | 11 | const account2 = await cdp.solana.getAccount({ 12 | address: account.address, 13 | }); 14 | 15 | console.log("Account 2:", JSON.stringify(account, null, 2)); 16 | 17 | const areAccountsEqual = account.address === account2.address; 18 | console.log("Are accounts equal? ", areAccountsEqual); 19 | 20 | const accountPromise1 = cdp.solana.getOrCreateAccount({ name: "Account" }); 21 | const accountPromise2 = cdp.solana.getOrCreateAccount({ name: "Account" }); 22 | const accountPromise3 = cdp.solana.getOrCreateAccount({ name: "Account" }); 23 | Promise.all([accountPromise1, accountPromise2, accountPromise3]).then( 24 | ([account1, account2, account3]) => { 25 | console.log("Solana Account Address 1: ", account1.address); 26 | console.log("Solana Account Address 2: ", account2.address); 27 | console.log("Solana Account Address 3: ", account3.address); 28 | } 29 | ); 30 | -------------------------------------------------------------------------------- /.github/workflows/typescript_test.yml: -------------------------------------------------------------------------------- 1 | name: TypeScript Tests 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened, ready_for_review] 6 | 7 | permissions: 8 | contents: read 9 | 10 | defaults: 11 | run: 12 | working-directory: ./typescript 13 | 14 | jobs: 15 | test: 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - name: Harden the runner (Audit all outbound calls) 20 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 21 | with: 22 | egress-policy: audit 23 | 24 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 25 | 26 | - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0 27 | name: Install pnpm 28 | with: 29 | version: 10 30 | run_install: false 31 | 32 | - name: Install Node.js 33 | uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 34 | with: 35 | node-version: 22 36 | cache: "pnpm" 37 | cache-dependency-path: "./typescript/pnpm-lock.yaml" 38 | 39 | - name: Install dependencies 40 | run: pnpm install 41 | 42 | - name: Run unit tests 43 | run: pnpm test 44 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.send_user_operation.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.send_user_operation.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from cdp.evm_call_types import EncodedCall 6 | from eth_account import Account 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() 10 | 11 | 12 | async def main(): 13 | async with CdpClient() as cdp: 14 | smart_account = await cdp.evm.create_smart_account(owner=Account.create()) 15 | 16 | user_operation = await smart_account.send_user_operation( 17 | network="base-sepolia", 18 | calls=[ 19 | EncodedCall( 20 | to="0x0000000000000000000000000000000000000000", 21 | data="0x", 22 | value=0, 23 | # override_gas_limit="1000000", if you want to override the gas limit 24 | ) 25 | ], 26 | ) 27 | 28 | user_op_result = await cdp.evm.wait_for_user_operation( 29 | smart_account_address=smart_account.address, 30 | user_op_hash=user_operation.user_op_hash, 31 | ) 32 | print("User Operation Result:", user_op_result) 33 | 34 | 35 | asyncio.run(main()) 36 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_sqlapi_alpha_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.api.sqlapi_alpha_api import SQLAPIAlphaApi 19 | 20 | 21 | class TestSQLAPIAlphaApi(unittest.IsolatedAsyncioTestCase): 22 | """SQLAPIAlphaApi unit test stubs""" 23 | 24 | async def asyncSetUp(self) -> None: 25 | self.api = SQLAPIAlphaApi() 26 | 27 | async def asyncTearDown(self) -> None: 28 | await self.api.api_client.close() 29 | 30 | async def test_get_sql_grammar(self) -> None: 31 | """Test case for get_sql_grammar 32 | 33 | Get SQL grammar 34 | """ 35 | pass 36 | 37 | async def test_run_sql_query(self) -> None: 38 | """Test case for run_sql_query 39 | 40 | Run SQL Query 41 | """ 42 | pass 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /examples/python/evm/policies/create_usd_spend_restriction_policy.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/policies/create_usd_spend_restriction_policy.py 2 | 3 | import asyncio 4 | 5 | from cdp import CdpClient 6 | from dotenv import load_dotenv 7 | from cdp.policies.types import ( 8 | CreatePolicyOptions, 9 | SendEvmTransactionRule, 10 | NetUSDChangeCriterion, 11 | ) 12 | 13 | load_dotenv() 14 | 15 | async def main(): 16 | async with CdpClient() as cdp: 17 | # Create a policy that allows sending up to 100 dollars worth of assets at a time 18 | policy = CreatePolicyOptions( 19 | scope="account", 20 | description="Accept up to 100 dollars", 21 | rules=[ 22 | SendEvmTransactionRule( 23 | action="accept", 24 | criteria=[ 25 | NetUSDChangeCriterion( 26 | changeCents=10000, 27 | operator="<", 28 | ), 29 | ], 30 | ), 31 | ], 32 | ) 33 | 34 | result = await cdp.policies.create_policy(policy=policy) 35 | 36 | print("Created USD spend restrictions policy: ", result.id) 37 | 38 | 39 | asyncio.run(main()) 40 | -------------------------------------------------------------------------------- /typescript/src/spend-permissions/utils.ts: -------------------------------------------------------------------------------- 1 | import { getErc20Address } from "../actions/evm/transfer/utils.js"; 2 | import { UserInputValidationError } from "../errors.js"; 3 | 4 | import type { Network } from "../actions/evm/transfer/types.js"; 5 | import type { SpendPermissionNetwork } from "../openapi-client/index.js"; 6 | import type { Address } from "../types/misc.js"; 7 | 8 | /** 9 | * Resolve the address of a token for a given network. 10 | * 11 | * @param token - The token symbol or contract address. 12 | * @param network - The network to get the address for. 13 | * 14 | * @returns The address of the token. 15 | */ 16 | export function resolveTokenAddress( 17 | token: "eth" | "usdc" | Address, 18 | network: SpendPermissionNetwork, 19 | ): Address { 20 | if (token === "eth") { 21 | return "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"; 22 | } 23 | 24 | if (token === "usdc" && (network === "base" || network === "base-sepolia")) { 25 | return getErc20Address(token, network as Network); 26 | } 27 | 28 | if (token === "usdc") { 29 | throw new UserInputValidationError( 30 | `Automatic token address lookup for ${token} is not supported on ${network}. Please provide the token address manually.`, 31 | ); 32 | } 33 | 34 | return token; 35 | } 36 | -------------------------------------------------------------------------------- /examples/typescript/evm/spend-permissions/createSpendPermission.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/spend-permissions/createSpendPermission.ts 2 | import { 3 | CdpClient, 4 | parseUnits, 5 | type SpendPermissionInput, 6 | } from "@coinbase/cdp-sdk"; 7 | import "dotenv/config"; 8 | 9 | const cdp = new CdpClient(); 10 | 11 | const account = await cdp.evm.getOrCreateSmartAccount({ 12 | name: "Example-Account", 13 | owner: await cdp.evm.getOrCreateAccount({ 14 | name: "Example-Account-Owner", 15 | }), 16 | enableSpendPermissions: true, 17 | }); 18 | 19 | const spender = await cdp.evm.createAccount(); 20 | 21 | console.log("Account Address:", account.address); 22 | console.log("Spender Address:", spender.address); 23 | 24 | const spendPermission: SpendPermissionInput = { 25 | account: account.address, 26 | spender: spender.address, 27 | token: "usdc", 28 | allowance: parseUnits("0.01", 6), 29 | periodInDays: 30, // monthly 30 | }; 31 | 32 | const { userOpHash } = await cdp.evm.createSpendPermission({ 33 | spendPermission, 34 | network: "base-sepolia", 35 | }); 36 | 37 | const userOperationResult = await cdp.evm.waitForUserOperation({ 38 | smartAccountAddress: account.address, 39 | userOpHash, 40 | }); 41 | 42 | console.log("User Operation:", userOperationResult); 43 | -------------------------------------------------------------------------------- /examples/typescript/evm/account.signTypedData.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/account.signTypedData.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | const account = await cdp.evm.createAccount(); 9 | 10 | console.log("Created account:", account.address); 11 | 12 | const signature = await account.signTypedData({ 13 | domain: { 14 | name: "Permit2", 15 | chainId: 1, 16 | verifyingContract: "0x000000000022D473030F116dDEE9F6B43aC78BA3", 17 | }, 18 | types: { 19 | PermitTransferFrom: [ 20 | { name: "permitted", type: "TokenPermissions" }, 21 | { name: "spender", type: "address" }, 22 | { name: "nonce", type: "string" }, 23 | { name: "deadline", type: "string" }, 24 | ], 25 | TokenPermissions: [ 26 | { name: "token", type: "address" }, 27 | { name: "amount", type: "string" }, 28 | ], 29 | }, 30 | primaryType: "PermitTransferFrom", 31 | message: { 32 | permitted: { 33 | token: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", 34 | amount: "1000000", 35 | }, 36 | spender: "0xFfFfFfFFfFFfFFfFFfFFFFFffFFFffffFfFFFfFf", 37 | nonce: "0", 38 | deadline: "1717123200", 39 | }, 40 | }); 41 | 42 | console.log("Signature:", signature); 43 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_evm_swaps_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.api.evm_swaps_api import EVMSwapsApi 19 | 20 | 21 | class TestEVMSwapsApi(unittest.IsolatedAsyncioTestCase): 22 | """EVMSwapsApi unit test stubs""" 23 | 24 | async def asyncSetUp(self) -> None: 25 | self.api = EVMSwapsApi() 26 | 27 | async def asyncTearDown(self) -> None: 28 | await self.api.api_client.close() 29 | 30 | async def test_create_evm_swap_quote(self) -> None: 31 | """Test case for create_evm_swap_quote 32 | 33 | Create a swap quote 34 | """ 35 | pass 36 | 37 | async def test_get_evm_swap_price(self) -> None: 38 | """Test case for get_evm_swap_price 39 | 40 | Get a price estimate for a swap 41 | """ 42 | pass 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/evm_user_operation_network.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class EvmUserOperationNetwork(str, Enum): 23 | """ 24 | The network the user operation is for. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | BASE_MINUS_SEPOLIA = 'base-sepolia' 31 | BASE = 'base' 32 | ARBITRUM = 'arbitrum' 33 | OPTIMISM = 'optimism' 34 | ZORA = 'zora' 35 | POLYGON = 'polygon' 36 | BNB = 'bnb' 37 | AVALANCHE = 'avalanche' 38 | ETHEREUM = 'ethereum' 39 | ETHEREUM_MINUS_SEPOLIA = 'ethereum-sepolia' 40 | 41 | @classmethod 42 | def from_json(cls, json_str: str) -> Self: 43 | """Create an instance of EvmUserOperationNetwork from a JSON string""" 44 | return cls(json.loads(json_str)) 45 | 46 | 47 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_faucets_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.api.faucets_api import FaucetsApi 19 | 20 | 21 | class TestFaucetsApi(unittest.IsolatedAsyncioTestCase): 22 | """FaucetsApi unit test stubs""" 23 | 24 | async def asyncSetUp(self) -> None: 25 | self.api = FaucetsApi() 26 | 27 | async def asyncTearDown(self) -> None: 28 | await self.api.api_client.close() 29 | 30 | async def test_request_evm_faucet(self) -> None: 31 | """Test case for request_evm_faucet 32 | 33 | Request funds on EVM test networks 34 | """ 35 | pass 36 | 37 | async def test_request_solana_faucet(self) -> None: 38 | """Test case for request_solana_faucet 39 | 40 | Request funds on Solana devnet 41 | """ 42 | pass 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /python/cdp/actions/solana/sign_transaction.py: -------------------------------------------------------------------------------- 1 | from cdp.openapi_client.api.solana_accounts_api import SolanaAccountsApi 2 | from cdp.openapi_client.models.sign_solana_transaction200_response import ( 3 | SignSolanaTransaction200Response as SignSolanaTransactionResponse, 4 | ) 5 | from cdp.openapi_client.models.sign_solana_transaction_request import ( 6 | SignSolanaTransactionRequest, 7 | ) 8 | 9 | 10 | async def sign_transaction( 11 | solana_accounts_api: SolanaAccountsApi, 12 | address: str, 13 | transaction: str, 14 | idempotency_key: str, 15 | ) -> SignSolanaTransactionResponse: 16 | """Sign a transaction. 17 | 18 | Args: 19 | solana_accounts_api (SolanaAccountsApi): The Solana accounts API. 20 | address (str): The address of the Solana account. 21 | transaction (str): The transaction to sign. 22 | idempotency_key (str): The idempotency key. 23 | 24 | Returns: 25 | SignSolanaTransactionResponse: The signature of the transaction. 26 | 27 | """ 28 | return await solana_accounts_api.sign_solana_transaction( 29 | sign_solana_transaction_request=SignSolanaTransactionRequest( 30 | transaction=transaction, 31 | ), 32 | address=address, 33 | x_idempotency_key=idempotency_key, 34 | ) 35 | -------------------------------------------------------------------------------- /python/templates/__init__package.mustache: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | {{>partial_header}} 6 | 7 | __version__ = "{{packageVersion}}" 8 | 9 | # import apis into sdk package 10 | {{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classFilename}} import {{classname}} 11 | {{/apis}}{{/apiInfo}} 12 | # import ApiClient 13 | from {{packageName}}.api_response import ApiResponse 14 | from {{packageName}}.api_client import ApiClient 15 | from {{packageName}}.cdp_api_client import CdpApiClient 16 | from {{packageName}}.configuration import Configuration 17 | from {{packageName}}.exceptions import OpenApiException 18 | from {{packageName}}.exceptions import ApiTypeError 19 | from {{packageName}}.exceptions import ApiValueError 20 | from {{packageName}}.exceptions import ApiKeyError 21 | from {{packageName}}.exceptions import ApiAttributeError 22 | from {{packageName}}.exceptions import ApiException 23 | {{#hasHttpSignatureMethods}} 24 | from {{packageName}}.signing import HttpSigningConfiguration 25 | {{/hasHttpSignatureMethods}} 26 | 27 | # import models into sdk package 28 | {{#models}} 29 | {{#model}} 30 | from {{modelPackage}}.{{classFilename}} import {{classname}} 31 | {{/model}} 32 | {{/models}} 33 | 34 | 35 | {{#recursionLimit}} 36 | 37 | __import__('sys').setrecursionlimit({{{.}}}) 38 | {{/recursionLimit}} 39 | -------------------------------------------------------------------------------- /examples/typescript/evm/smart-accounts/update.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/smart-accounts/smartAccount.update.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | 8 | // Create a CDP account to use as the owner 9 | const owner = await cdp.evm.createAccount(); 10 | 11 | // Create a smart account with the CDP account as owner 12 | const smartAccount = await cdp.evm.getOrCreateSmartAccount({ 13 | owner, 14 | name: "my-smart-account" 15 | }); 16 | 17 | console.log("Created smart account:", smartAccount.address); 18 | console.log("Original name:", smartAccount.name); 19 | 20 | // Update the smart account with a new name 21 | const updatedSmartAccount = await cdp.evm.updateSmartAccount({ 22 | address: smartAccount.address, 23 | owner, 24 | update: { 25 | name: "updated-smart-account-name" 26 | } 27 | }); 28 | 29 | console.log("Updated smart account:", updatedSmartAccount.address); 30 | console.log("New name:", updatedSmartAccount.name); 31 | 32 | // Verify the update by retrieving the smart account again 33 | const retrievedSmartAccount = await cdp.evm.getSmartAccount({ 34 | address: smartAccount.address, 35 | owner: owner 36 | }); 37 | 38 | console.log("Retrieved smart account name:", retrievedSmartAccount.name); 39 | -------------------------------------------------------------------------------- /python/cdp/test/factories/solana_token_balances_factory.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from cdp.openapi_client.models.list_solana_token_balances200_response import ( 4 | ListSolanaTokenBalances200Response, 5 | ) 6 | from cdp.openapi_client.models.solana_token import SolanaToken 7 | from cdp.openapi_client.models.solana_token_amount import SolanaTokenAmount 8 | from cdp.openapi_client.models.solana_token_balance import SolanaTokenBalance 9 | 10 | 11 | @pytest.fixture 12 | def solana_token_balances_model_factory(): 13 | """Create and return a factory for ListSolanaTokenBalances200Response fixtures.""" 14 | 15 | def _create_token_balances_model( 16 | next_page_token="next-page-token", 17 | balances=None, 18 | ): 19 | if balances is None: 20 | token = SolanaToken( 21 | mint_address="So11111111111111111111111111111111111111111", 22 | symbol="TEST", 23 | name="Test Token", 24 | ) 25 | amount = SolanaTokenAmount(amount="1000000000", decimals=9) 26 | balances = [SolanaTokenBalance(token=token, amount=amount)] 27 | 28 | return ListSolanaTokenBalances200Response( 29 | next_page_token=next_page_token, balances=balances 30 | ) 31 | 32 | return _create_token_balances_model 33 | -------------------------------------------------------------------------------- /typescript/src/actions/solana/signMessage.ts: -------------------------------------------------------------------------------- 1 | import { SignMessageOptions, SignatureResult } from "../../client/solana/solana.types.js"; 2 | import { CdpOpenApiClientType } from "../../openapi-client/index.js"; 3 | 4 | /** 5 | * Sign a message. 6 | * 7 | * @param apiClient - The API client. 8 | * @param {SignMessageOptions} options - Parameters for signing the message. 9 | * @param {string} options.address - The address to sign the message for. 10 | * @param {string} options.message - The message to sign. 11 | * @param {string} [options.idempotencyKey] - An idempotency key. 12 | * 13 | * @returns A promise that resolves to the transaction signature. 14 | * 15 | * @example 16 | * ```ts 17 | * const signature = await signMessage(cdp.solana, { 18 | * address: "1234567890123456789012345678901234567890", 19 | * message: "Hello, world!", 20 | * }); 21 | * ``` 22 | */ 23 | export async function signMessage( 24 | apiClient: CdpOpenApiClientType, 25 | options: SignMessageOptions, 26 | ): Promise { 27 | const signature = await apiClient.signSolanaMessage( 28 | options.address, 29 | { message: options.message }, 30 | options.idempotencyKey, 31 | ); 32 | 33 | return { 34 | signature: signature.signature, 35 | }; 36 | } 37 | -------------------------------------------------------------------------------- /examples/typescript/evm/policies/updatePolicy.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/policies/updatePolicy.ts 2 | 3 | import { CdpClient } from "@coinbase/cdp-sdk"; 4 | import "dotenv/config"; 5 | 6 | const cdp = new CdpClient(); 7 | const policy = await cdp.policies.createPolicy({ 8 | policy: { 9 | scope: "account", 10 | description: "Initial Allowlist Policy", 11 | rules: [ 12 | { 13 | action: "accept", 14 | operation: "signEvmTransaction", 15 | criteria: [ 16 | { 17 | type: "evmAddress", 18 | addresses: ["0x000000000000000000000000000000000000dEaD"], 19 | operator: "in", 20 | }, 21 | ], 22 | }, 23 | ], 24 | }, 25 | }); 26 | 27 | const updatedPolicy = await cdp.policies.updatePolicy({ 28 | id: policy.id, 29 | policy: { 30 | description: "Updated Denylist Policy", 31 | rules: [ 32 | { 33 | action: "accept", 34 | operation: "signEvmTransaction", 35 | criteria: [ 36 | { 37 | type: "evmAddress", 38 | addresses: ["0x000000000000000000000000000000000000dEaD"], 39 | operator: "not in", 40 | }, 41 | ], 42 | }, 43 | ], 44 | }, 45 | }); 46 | console.log("Updated policy: ", JSON.stringify(updatedPolicy, null, 2)); 47 | -------------------------------------------------------------------------------- /examples/python/evm/smart-accounts/smart_account.quote_fund_and_execute.py: -------------------------------------------------------------------------------- 1 | # Usage: uv run python evm/smart-accounts/smart_account.quote_fund_and_execute.py 2 | 3 | import asyncio 4 | from cdp import CdpClient 5 | from dotenv import load_dotenv 6 | 7 | load_dotenv() 8 | 9 | 10 | async def main(): 11 | async with CdpClient() as cdp: 12 | account = await cdp.evm.get_or_create_account(name="account") 13 | smart_account = await cdp.evm.create_smart_account(owner=account) 14 | 15 | quote = await smart_account.quote_fund( 16 | network="base", 17 | token="usdc", 18 | amount=1000000, # 1 USDC 19 | ) 20 | 21 | # get details of the quote 22 | print(quote.fiat_amount) 23 | print(quote.token_amount) 24 | print(quote.token) 25 | print(quote.network) 26 | for fee in quote.fees: 27 | print(fee.type) # operation or network 28 | print(fee.amount) # amount in the token 29 | print(fee.currency) # currency of the amount 30 | 31 | response = await quote.execute() 32 | 33 | completed_transfer = await smart_account.wait_for_fund_operation_receipt( 34 | transfer_id=response.id, 35 | ) 36 | 37 | print(completed_transfer) 38 | 39 | 40 | asyncio.run(main()) -------------------------------------------------------------------------------- /python/cdp/openapi_client/test/test_onchain_data_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | import unittest 17 | 18 | from cdp.openapi_client.api.onchain_data_api import OnchainDataApi 19 | 20 | 21 | class TestOnchainDataApi(unittest.IsolatedAsyncioTestCase): 22 | """OnchainDataApi unit test stubs""" 23 | 24 | async def asyncSetUp(self) -> None: 25 | self.api = OnchainDataApi() 26 | 27 | async def asyncTearDown(self) -> None: 28 | await self.api.api_client.close() 29 | 30 | async def test_list_data_token_balances(self) -> None: 31 | """Test case for list_data_token_balances 32 | 33 | List EVM token balances 34 | """ 35 | pass 36 | 37 | async def test_list_tokens_for_account(self) -> None: 38 | """Test case for list_tokens_for_account 39 | 40 | List token addresses for account 41 | """ 42 | pass 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /typescript/src/accounts/evm/getBaseNodeRpcUrl.ts: -------------------------------------------------------------------------------- 1 | import { generateJwt } from "../../auth/utils/jwt.js"; 2 | import { config } from "../../openapi-client/cdpApiClient.js"; 3 | 4 | /** 5 | * Get the base node RPC URL for a given network. Can also be used as a Paymaster URL 6 | * 7 | * @param network - The network identifier 8 | * @returns The base node RPC URL or undefined if the network is not supported 9 | */ 10 | export async function getBaseNodeRpcUrl( 11 | network: "base" | "base-sepolia", 12 | ): Promise { 13 | if (!config) { 14 | return; 15 | } 16 | 17 | try { 18 | const basePath = config.basePath?.replace("/platform", ""); 19 | 20 | const jwt = await generateJwt({ 21 | apiKeyId: config.apiKeyId, 22 | apiKeySecret: config.apiKeySecret, 23 | requestMethod: "GET", 24 | requestHost: basePath.replace("https://", ""), 25 | requestPath: "/apikeys/v1/tokens/active", 26 | }); 27 | 28 | const response = await fetch(`${basePath}/apikeys/v1/tokens/active`, { 29 | headers: { 30 | Authorization: `Bearer ${jwt}`, 31 | "Content-Type": "application/json", 32 | }, 33 | }); 34 | 35 | const json = await response.json(); 36 | return `${basePath}/rpc/v1/${network}/${json.id}`; 37 | } catch { 38 | return; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /python/cdp/openapi_client/models/onramp_order_status.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | Coinbase Developer Platform APIs 5 | 6 | The Coinbase Developer Platform APIs - leading the world's transition onchain. 7 | 8 | The version of the OpenAPI document: 2.0.0 9 | Contact: cdp@coinbase.com 10 | Generated by OpenAPI Generator (https://openapi-generator.tech) 11 | 12 | Do not edit the class manually. 13 | """ # noqa: E501 14 | 15 | 16 | from __future__ import annotations 17 | import json 18 | from enum import Enum 19 | from typing_extensions import Self 20 | 21 | 22 | class OnrampOrderStatus(str, Enum): 23 | """ 24 | The status of an onramp order. 25 | """ 26 | 27 | """ 28 | allowed enum values 29 | """ 30 | ONRAMP_ORDER_STATUS_PENDING_AUTH = 'ONRAMP_ORDER_STATUS_PENDING_AUTH' 31 | ONRAMP_ORDER_STATUS_PENDING_PAYMENT = 'ONRAMP_ORDER_STATUS_PENDING_PAYMENT' 32 | ONRAMP_ORDER_STATUS_PROCESSING = 'ONRAMP_ORDER_STATUS_PROCESSING' 33 | ONRAMP_ORDER_STATUS_COMPLETED = 'ONRAMP_ORDER_STATUS_COMPLETED' 34 | ONRAMP_ORDER_STATUS_FAILED = 'ONRAMP_ORDER_STATUS_FAILED' 35 | 36 | @classmethod 37 | def from_json(cls, json_str: str) -> Self: 38 | """Create an instance of OnrampOrderStatus from a JSON string""" 39 | return cls(json.loads(json_str)) 40 | 41 | 42 | -------------------------------------------------------------------------------- /examples/typescript/evm/transactions/baseAccount.sendTransaction.ts: -------------------------------------------------------------------------------- 1 | // Usage: pnpm tsx evm/transactions/baseAccount.sendTransaction.ts 2 | 3 | import { CdpClient, parseEther } from "@coinbase/cdp-sdk"; 4 | 5 | import "dotenv/config"; 6 | 7 | const cdp = new CdpClient(); 8 | 9 | const account = await cdp.evm.getOrCreateAccount({ name: "MyAccount" }); 10 | const baseAccount = await account.useNetwork("base-sepolia"); 11 | 12 | const { transactionHash: faucetTransactionHash } = 13 | await baseAccount.requestFaucet({ 14 | token: "eth", 15 | }); 16 | 17 | const faucetTxReceipt = await baseAccount.waitForTransactionReceipt({ 18 | hash: faucetTransactionHash, 19 | }); 20 | 21 | console.log( 22 | "Successfully requested ETH from faucet:", 23 | faucetTxReceipt.transactionHash 24 | ); 25 | 26 | const transaction = await baseAccount.sendTransaction({ 27 | transaction: { 28 | to: "0x4252e0c9A3da5A2700e7d91cb50aEf522D0C6Fe8", 29 | value: parseEther("0.000001"), 30 | }, 31 | }); 32 | 33 | console.log("Transaction sent! Waiting for confirmation..."); 34 | 35 | const receipt = await baseAccount.waitForTransactionReceipt(transaction); 36 | 37 | console.log("Transaction confirmed!", receipt); 38 | console.log( 39 | `To view your transaction details, visit: https://sepolia.basescan.org/tx/${receipt.transactionHash}` 40 | ); 41 | --------------------------------------------------------------------------------